1157. Circular Twin Distances
Lamps hang evenly around a circular ring of n positions, and nums[i] is the colour code of the lamp at position i. The distance between positions i and j along the ring is min(|i - j|, n - |i - j|), the shorter way round.
For every position i, return the sum of the ring distances from i to every other position j that holds the same colour code. A lamp whose colour is unique gets 0. The result is an array of n 64-bit integers. Constraints: 1 <= n <= 10^5 and 1 <= nums[i] <= 10^9. Checking every pair is too slow; aim for O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [1,2,1,3,1]
- Output:
- [3,0,4,0,3]
- Explanation:
The three 1s sit at 0, 2 and 4; from index 0 the circular distances are 2 and 1, giving 3, and similarly 4 and 3 for indices 2 and 4.
Example 2
- Input:
- nums = [7]
- Output:
- [0]
- Explanation:
A value that appears once has no twin, so its total is 0.
Example 3
- Input:
- nums = [4,4,4,4]
- Output:
- [4,4,4,4]
- Explanation:
On a ring of 4, each lamp sees distances 1, 2 and 1, which total 4.
Constraints
1 ≤ n ≤ 105
1 ≤ nums[i] ≤ 109
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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)