1254. Sandwich Triples
A museum logs the visitor id of every ticket scan at its gate, in order, in the array nums. A sandwich is a triple of positions i < j < k such that scans i and k carry the same id while scan j carries a different id. Two triples are different if they use different positions, even when the ids are the same.
Return the number of sandwich triples as a 64-bit integer. Checking every triple is far too slow for 2*10^5 scans. Aim for O(n) expected time and O(n) space: group the positions of each id, and for two occurrences of one id count the positions strictly between them that hold other ids, adding these counts up with running totals per id.
Example 1
- Input:
- nums = [41,7,19,7,41,88,7,41,19]
- Output:
- 21
- Explanation:
Id 41 appears at positions 0, 4 and 7 and id 7 at positions 1, 3 and 6, and summing the scans with a different id between each equal pair gives 21 sandwiches.
Example 2
- Input:
- nums = [250,13,250,90,6,13,17,250]
- Output:
- 13
- Explanation:
Id 250 appears three times and id 13 twice, and the equal-id pairs enclose 13 scans with a different id in total.
Example 3
- Input:
- nums = [905,12,905,47,63,12]
- Output:
- 4
- Explanation:
Only ids 905 and 12 repeat, so just two equal pairs exist and together they enclose 4 scans with a different id.
Constraints
3 ≤ n ≤ 2*105 where n = nums.length; 1 ≤ nums[i] ≤ 109; the answer fits in a 64-bit integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)