Ctrl K

Swapping Close Values

Medium
You get an array of positive integers values and a number gap. In one move you may swap any two elements whose values differ by at most gap, and you may make as many moves as you like. Return the lexicographically smallest array you can reach. Array a is smaller than array b if, at the first position where they differ, a holds the smaller number.
Example 1
values=[6, 2, 9, 4, 20, 7], gap=2 → [2, 4, 6, 7, 20, 9]

The values 2, 4, 6, 7, 9 are chained by gaps of at most 2, so they can be rearranged freely over their positions (indices 0, 1, 2, 3, 5). 20 is far from everyone and stays put.

Example 2
values=[15, 3, 11, 1], gap=3 → [15, 1, 11, 3]

3 and 1 may swap (difference 2), but 15 and 11 may not (difference 4). Nothing smaller than [15, 1, 11, 3] is reachable.

Example 3
values=[5, 5, 1], gap=0 → [5, 5, 1]

Only equal numbers may be swapped, which changes nothing.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁹
  • 0 ≤ gap ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMerge Contact Cards MediumWhen Everyone Is Linked MediumRearrange Through Links MediumCell Levels by Rows and Columns HardScooter Trips Under a Road Limit Hard
loading Python…
Input
values=[6, 2, 9, 4, 20, 7], gap=2
Expected
[2, 4, 6, 7, 20, 9]

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