Ctrl K

Distances to Twins

Medium
You get an array labels. For every position i, compute the sum of distances |i − j| to every other position j holding the same value. If there is no such position, the sum is 0. Return an array of these sums, the same length as labels. Comparing every pair is O(n²); do better.
Example 1
labels=[7, 2, 7, 2, 7] → [6, 2, 4, 2, 6]

The 7s sit at positions 0, 2, 4: position 0 gets 2 + 4 = 6, position 2 gets 2 + 2 = 4, position 4 gets 4 + 2 = 6. The 2s at positions 1 and 3 are 2 apart. The answer is [6, 2, 4, 2, 6].

Example 2
labels=[9, 8] → [0, 0]

No element has a twin, so both get 0.

Example 3
labels=[0, 0, 0] → [3, 2, 3]
Constraints
  • 1 ≤ len(labels) ≤ 10⁵
  • 0 ≤ labels[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Run with a Given Sum MediumA Stretch Divisible by k MediumAs Many Heads as Tails MediumStretches With an Exact Total MediumWindows With an Exact Alarm Count Medium
loading Python…
Input
labels=[7, 2, 7, 2, 7]
Expected
[6, 2, 4, 2, 6]

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.