KatInterview

Three-Bucket Rearrangement With Constant Extra Space

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersin-placepartitioning

Last updated

Tests in-place three-way partitioning of an array holding only 0, 1 and 2 using constant extra space and a single linear pass, with careful pointer invariants.

Group the Labels

A warehouse scanner tags each parcel with a label that is one of 0, 1, or 2. You are given the tags as a list labels.

Reorder the list in place so that every 0 appears first, then every 1, then every 2. The function must also return the same list object once it has been rearranged.

Requirements

  • Change the input list itself rather than building a new one.
  • Use only O(1) additional memory.
  • Aim for a solution that finishes in a single left-to-right sweep, running in O(n) time.
  • The relative order of equal values is irrelevant, since equal values are indistinguishable.
  • An empty list is valid and should be returned unchanged.

Constraints

  • 0 <= len(labels) <= 10^5
  • Each element of labels is exactly 0, 1, or 2.
  • The returned list must contain the same multiset of values as the input, arranged in non-decreasing order.

Examples

Example 1

Input: group_labels([2, 0, 2, 1, 1, 0])

Output: [0, 0, 1, 1, 2, 2]

Example 2

Input: group_labels([0, 1, 2])

Output: [0, 1, 2]

Example 3

Input: group_labels([2, 2, 1, 1, 0, 0])

Output: [0, 0, 1, 1, 2, 2]

Example 4

Input: group_labels([1, 0, 1, 2, 0, 2, 1])

Output: [0, 0, 1, 1, 1, 2, 2]

Hints

Hint 1

Think of the list as split into four zones: confirmed 0s on the left, confirmed 1s next, a not-yet-inspected middle, and confirmed 2s on the right. Which pointers mark the boundaries?

Hint 2

Inspect the element at the start of the unknown zone. If it is 0, swap it into the 0 zone; if it is 1, just grow the 1 zone; if it is 2, swap it to the end of the unknown zone.

Hint 3

After swapping with the right boundary, the value that arrives at your current position has not been inspected yet, so do not advance the current pointer in that case. Loop while the current index is less than or equal to the right boundary.