Spot the bug
This version scrambles the order of the cars. Which line is wrong?
def compact(a: list[int]) -> list[int]:lo, hi = 0, len(a) - 1while lo < hi:if a[lo] == 0:a[lo], a[hi] = a[hi], a[lo]hi -= 1else:lo += 1return aprint(compact([0, 1, 2]))
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 5
a[lo], a[hi] = a[hi], a[lo]
Line 5 swaps an empty slot with whatever is at the far end, so cars from the back jump ahead of earlier cars. A read/write pointer pair moving in the same direction keeps order.
Steps come from running the Python solution.
Text version
Mixed row:
Cells: [0, 1, 0, 3, 12]
- Write 0, read 0: [0, 1, 0, 3, 12]. Zero: skip
- Write 0, read 1: [1, 0, 0, 3, 12]. Keep 1: write it at 0
- Write 1, read 2: [1, 0, 0, 3, 12]. Zero: skip
- Write 1, read 3: [1, 3, 0, 0, 12]. Keep 3: write it at 1
- Write 2, read 4: [1, 3, 12, 0, 0]. Keep 12: write it at 2
Result: [1, 3, 12, 0, 0]
Already packed:
Cells: [5, 6, 0]
- Write 0, read 0: [5, 6, 0]. Keep 5: write it at 0
- Write 1, read 1: [5, 6, 0]. Keep 6: write it at 1
- Write 2, read 2: [5, 6, 0]. Zero: skip
Result: [5, 6, 0]