Ctrl K

Spread Out the Labels

Medium
Boxes stand on a warehouse conveyor, each with a number label: labels[i] is the label of box i. The operator wants to reorder the boxes so that no two neighbouring boxes carry the same label. This is guaranteed to be possible. There are usually many valid orders, so build this particular one: 1. Line the boxes up in a queue: first every box with the most frequent label, then the next most frequent, and so on. Labels that appear equally often go in increasing order. 2. Hand the boxes out from the queue to positions 0, 2, 4, …, and once the even positions run out, to positions 1, 3, 5, …. Return the resulting row of labels. Think about why it never puts two equal labels side by side.
Example 1
labels=[7, 3, 7, 3, 7] → [7, 3, 7, 3, 7]

Label 7 appears three times and 3 twice, so the queue is 7, 7, 7, 3, 3. Slots 0, 2 and 4 get the 7s, slots 1 and 3 get the 3s.

Example 2
labels=[5, 2, 9, 2, 5, 9] → [2, 5, 2, 9, 5, 9]

Every label appears twice, so ties are broken by value: 2, 2, 5, 5, 9, 9. The even slots get 2, 2, 5 and the odd slots get 5, 9, 9.

Example 3
labels=[4] → [4]
Constraints
  • 1 ≤ len(labels) ≤ 10⁴
  • 1 ≤ labels[i] ≤ 10⁴
  • No label appears more than ⌈len(labels) / 2⌉ times
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsJobs With a Cooldown MediumMost Common Values MediumMost Searched Words MediumNo Twin Letters Side by Side MediumPick Within Tag Limits Medium
loading Python…
Input
labels=[7, 3, 7, 3, 7]
Expected
[7, 3, 7, 3, 7]

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