Delayed Count of Equal Elements Problem
#3837
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3837.
You are given an integer array nums of length n and an integer k.
For each index i, define the delayed count as the number of indices j such that:
i + k < j <= n - 1, andnums[j] == nums[i]
Return an array ans where ans[i] is the delayed count of index i.
Example 1:
Input: nums = [1,2,1,1], k = 1
Output: [2,0,0,0]
Explanation:
i nums[i] possible j nums[j] satisfying nums[j] == nums[i] ans[i]
0 1 [2, 3] [1, 1] [2, 3] 2
1 2 [3] [1] [] 0
2 1 [] [] [] 0
3 1 [] [] [] 0
Thus, ans = [2, 0, 0, 0].
Example 2:
Input: nums = [3,1,3,1], k = 0
Output: [1,1,0,0]
Explanation:
i nums[i] possible j nums[j] satisfying nums[j] == nums[i] ans[i]
0 3 [1, 2, 3] [1, 3, 1] [2] 1
1 1 [2, 3] [3, 1] [3] 1
2 3 [3] [1] [] 0
3 1 [] [] [] 0
Thus, ans = [1, 1, 0, 0].
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^50 <= k <= n - 1
Solution
Approach: Hash Table + Reverse Enumeration
For index i, the valid positions j are exactly the indices after i + k, so we want the number of copies of nums[i] in the suffix that starts at i + k + 1. Go from right to left and keep a hash table cnt of the values in that suffix. When we move to index i, the suffix gains one new element, nums[i + k + 1], so add it to cnt and then set ans[i] = cnt[nums[i]]. Indices i >= n - k - 1 have no valid j, so their answer stays 0.
Complexity:
- Time:
O(n). - Space:
O(n).
from collections import Counter
class Solution:
def delayedCount(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
cnt = Counter()
ans = [0] * n
for i in range(n - k - 2, -1, -1):
cnt[nums[i + k + 1]] += 1
ans[i] = cnt[nums[i]]
return ans