Partition three colors
Return a sorted copy of a list containing only 0, 1 and 2, using one traversal and constant auxiliary space apart from the copy.
items = [2, 0, 1]
mid, high = 0, 2
items[mid], items[high] = items[high], items[mid]
print(items) # inspect mid againReason about the state
Maintain completed low and high regions around an unknown middle. After swapping from the high end, inspect the incoming value before advancing. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return a sorted copy of a list containing only 0, 1 and 2, using one traversal and constant auxiliary space apart from the copy.
The explanation opens here once every check passes.