Spot the bug
This version sometimes leaves a 0 in the wrong place. Which line is wrong?
def tray(a: list[int]) -> list[int]:lo, mid, hi = 0, 0, len(a) - 1while mid <= hi:if a[mid] == 0:a[lo], a[mid] = a[mid], a[lo]lo += 1; mid += 1elif a[mid] == 1:mid += 1else:a[mid], a[hi] = a[hi], a[mid]hi -= 1; mid += 1return aprint(tray([1, 2, 0]))
Choose an answer, then open Show answer below to check it.
Show answer
- Answer: line 11
hi -= 1; mid += 1
Line 11 advances mid after swapping with hi, so the value that came from the right end is never inspected. Here a 0 swapped in from the end gets skipped.