The Intervals Between Identical Elements interview question asks you to find the sum of absolute differences between the indices of identical elements in an array. For each index , you need to calculate for all such that arr[j] == arr[i]. The output is an array of these sums.
Companies like Google ask this to evaluate your ability to optimize an distance calculation into . It tests your knowledge of Hash Table interview patterns and the Prefix Sum interview pattern. It’s a great example of how mathematical derivation can simplify a problem.
This problem follows the Prefix Sum and Frequency Counting pattern.
value -> [idx1, idx2, idx3]).(i * P[i] - prefixSum[i]) + (suffixSum[i] - (count - i - 1) * P[i]).
Array: [2, 1, 3, 1, 2, 1]. Let's look at '1' (indices: [1, 3, 5]).
Whenever you see a sum of absolute differences , your first goal should be to remove the absolute value. This is almost always done by Sorting the indices and using Prefix Sums.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Contiguous Array | Medium | Solve | |
| Count of Interesting Subarrays | Medium | Solve | |
| Make Sum Divisible by P | Medium | Solve | |
| Maximum Good Subarray Sum | Medium | Solve | |
| Maximum Size Subarray Sum Equals k | Medium | Solve |