Count Values With Equally Spaced Occurrences II Problem
#4049
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 4049.
You are given an integer array nums.
An integer x is called special if:
xappears at least three times innums.- All occurrences of
xare equally spaced innums. In other words, if all occurrences ofxare at indicesi_1 < i_2 < ... < i_m, theni_2 - i_1 = i_3 - i_2 = ... = i_m - i_(m-1).
Return the number of distinct special integers in nums.
Example 1:
Input: nums = [1,8,1,5,1,5,8,5]
Output: 2
Explanation:
- 1 is special because it occurs at equally spaced indices 0, 2, and 4.
- 5 is special because it occurs at equally spaced indices 3, 5, and 7.
- 8 is not special because it occurs only twice.
Therefore, the answer is 2.
Example 2:
Input: nums = [8,8,8,8]
Output: 1
Explanation:
8 is special because it occurs at equally spaced indices 0, 1, 2, and 3. Therefore, the answer is 1.
Example 3:
Input: nums = [8,6,6,8,8]
Output: 0
Explanation:
8 occurs at indices 0, 3, and 4, which are not equally spaced. 6 occurs only twice. Therefore, no integer is special.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Hash Table
Record the indices at which each value occurs, by scanning nums once and appending i to the list of nums[i].
For each list pos, skip it if it has fewer than 3 entries. Otherwise let d = pos[1] - pos[0] and check that every pair of neighbouring indices differs by exactly d. If so, the value is special; count it.
Complexity: O(n) time and O(n) space.
from collections import defaultdict
class Solution:
def countSpecialIntegers(self, nums: List[int]) -> int:
g = defaultdict(list)
for i, x in enumerate(nums):
g[x].append(i)
ans = 0
for pos in g.values():
if len(pos) < 3:
continue
d = pos[1] - pos[0]
if all(j - i == d for i, j in zip(pos, pos[1:])):
ans += 1
return ans