4049. Count Values With Equally Spaced Occurrences II
DifficultyMedium
Description
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 indicesi1 < i2 < ... < im, theni2 - i1 = i3 - i2 = ... = im - im-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 <= 1051 <= nums[i] <= 109
Solutions
Solution 1: Hash Table
Thinking
The previous problem only handled exactly three occurrences. Here a value must appear at least three times, and every occurrence must lie on the same common difference. With \(n = 10^5\) we cannot rescan the original array for each value.
After grouping indices by value, the lists still have total length \(n\). If every adjacent gap equals the first gap, the whole sequence is an arithmetic progression.
Grouping followed by a linear scan of each list is enough.
We use a hash table to record all indices where each integer appears. Traverse \(\textit{nums}\) and append index \(i\) to the list of \(\textit{nums}[i]\).
Then iterate over each index list \(\textit{pos}\) in the hash table. Skip it if its length is less than \(3\). Otherwise let \(d = \textit{pos}[1] - \textit{pos}[0]\) and check whether every adjacent gap equals \(d\). If so, the integer is special and we increment the answer by \(1\).
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |