4048. Count Values With Equally Spaced Occurrences I
DifficultyEasy
Description
You are given an integer array nums.
An integer x is called special if:
xappears exactly three times innums.- All three occurrences of
xare equally spaced innums. In other words, if all occurrences ofxare at indicesi1 < i2 < i3, theni2 - i1 = i3 - i2.
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 exactly three times at equally spaced indices 0, 2, and 4.
- 5 is special because it occurs exactly three times 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: 0
Explanation:
8 is not special because it does not occur exactly three times. Therefore, the answer is 0.
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 <= 1001 <= nums[i] <= 100
Solutions
Solution 1: Hash Table
Thinking
\(n \le 100\), so even scanning the array once per distinct value would pass. A special integer must appear exactly three times, and those three indices must form an arithmetic progression.
After collecting the indices of each value, the check reduces to two facts: the list has length \(3\), and the first plus the last index equals twice the middle one.
A hash table groups the indices in a single pass.
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. If \(\textit{pos}\) has length \(3\) and \(\textit{pos}[0] + \textit{pos}[2] = 2 \times \textit{pos}[1]\) (the three occurrences are equally spaced), 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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |