Ctrl K

Distance to Twins

Medium
You are given an array labels of length n. The twins of an element are the other elements of the array with the same value. The distance between positions i and j is |i - j|. Return an array of length n whose entry at position i is the sum of distances from i to every twin of labels[i]. With no twins, the sum is 0. Checking every pair takes O(n²); try to do better.
Example 1
labels=[4, 7, 4, 4, 7] → [5, 3, 3, 4, 3]

The 4s are at positions 0, 2 and 3: position 0 gets |0-2| + |0-3| = 5, position 2 gets 2 + 1 = 3, position 3 gets 3 + 1 = 4. The 7s at 1 and 4 are 3 apart.

Example 2
labels=[8, 1, 6] → [0, 0, 0]

All values differ, so no element has a twin and every answer is 0.

Example 3
labels=[2, 2, 2, 2] → [6, 4, 4, 6]
Constraints
  • 1 ≤ n ≤ 10⁵
  • 1 ≤ 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=[4, 7, 4, 4, 7]
Expected
[5, 3, 3, 4, 3]

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