In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort
Implement four O(1)-extra-space list transformations—range reversal, three-reversal rotation, write-pointer partitioning/deduplication, and O(n) cyclic placement—and prove why each works.
Contentsand lesson path
On this page
- The problem
- Step 1: range reversal and three-reversal rotation
- Step 2: read/write pointers for partition and deduplication
- Step 3: cyclic placement for values in 1..n
- Check your understanding
- Apply it
- Review prompt
Lessons of Arrays & Strings
- How a Python List Grows Concept · 20 min
- A Cost Table for Lists and Strings Concept · 15 min
- In-Place Moves: Reverse, Rotate, Partition, Cyclic Sort Worked example · 30 min
- Building Strings Without Quadratic Traps Worked example · 15 min
- Lab: Grid Walks and Matrix Rotation Lab · 25 min
- Check: Array and String Drills Knowledge check · 8 questions
What you will learn
- Implement in-place array transformations (reverse, rotate, partition, remove duplicates from sorted input, cyclic placement of values 1..n at their own index) using O(1) extra space.
Prerequisites: Complexity Analysis
01. The problem
Building a new filtered or rotated list with a comprehension or slice is clean and safe—and when n fits comfortably in memory and caller data must stay unchanged, allocating a copy is the right choice. Sometimes, however, constraints forbid O(n) extra memory: you must transform a list in place using O(1) auxiliary space and O(n) time, without shifting elements via repeated insert(0) or pop(i).
Remember from How a Python List Grows that a CPython list stores contiguous pointers, so mutating elements inside existing indices takes O(1) per swap, while inserting or deleting in the middle shifts the tail in O(n). Below we walk through four foundational in-place moves—range reversal, rotation by k, read/write partitioning and deduplication, and cyclic placement for values 1..n—explaining the loop invariant that makes each step safe and linear.
02. Step 1: range reversal and three-reversal rotation
Two pointers left and right moving inward from the ends of a slice [left..right] swap symmetric elements until left >= right. Each element is swapped at most once, so reversing takes O(right - left) time and O(1) extra space.
Now suppose you need to rotate an n-element array right by k steps (k can exceed n, so reduce k %= n first). Why do three reversals rotate [10, 20, 30, 40, 50, 60] by k = 2 into [50, 60, 10, 20, 30, 40]? Think about the blocks A = [10, 20, 30, 40] and B = [50, 60]:
- Reversing the whole array flips
ABintorev(B) rev(A) = [60, 50, 40, 30, 20, 10]—now the lastkitems sit at the front, just backwards. - Reversing the first
kitems ([0..k-1]) restoresB:[50, 60, 40, 30, 20, 10]. - Reversing the last
n - kitems ([k..n-1]) restoresA:[50, 60, 10, 20, 30, 40].
What if you split at n - k instead of k after reversing the whole array, or reversed the two parts first and the whole array last? That swaps the block sizes and rotates left by k instead of right! Every element participates in two swaps total, giving O(n) time and O(1) auxiliary space.
def reverse_range(a: list[int], left: int, right: int) -> None:
while left < right:
a[left], a[right] = a[right], a[left]
left += 1
right -= 1
def rotate_right(a: list[int], k: int) -> None:
n = len(a)
if n <= 1:
return
k %= n
if k == 0:
return
reverse_range(a, 0, n - 1)
reverse_range(a, 0, k - 1)
reverse_range(a, k, n - 1)
arr = [10, 20, 30, 40, 50, 60]
rotate_right(arr, 2)
print("rotate_right(k=2):", arr)
again = [10, 20, 30, 40, 50, 60]
rotate_right(again, 8)
print("k=8 gives the same list:", again == arr)rotate_right(k=2): [50, 60, 10, 20, 30, 40]
k=8 gives the same list: True03. Step 2: read/write pointers for partition and deduplication
Whenever you want to keep or group matching elements in place without calling pop(i) (which would shift the tail in O(n) per pop), use two indices moving left to right: a read index r that scans every element once, and a write index w marking the end of the accepted prefix a[:w].
- In
partition_evens_first(a), every even elementa[r]is swapped intoa[w]andwadvances by1. The invariant is simple: after each iteration,a[:w]holds only even numbers anda[w : r + 1]holds only odd numbers. Note that swappinga[w], a[r]is unstable: on the input[3, 8, 5, 2, 7, 4]below, the odd values arrive in the order3, 5, 7but end in the order3, 7, 5. If you need stability withO(n)time, anO(n)extra-space filter[x for x in a if x % 2 == 0] + [x for x in a if x % 2 != 0]is cleaner. - In
dedupe_sorted(a),ais already sorted, so duplicates sit adjacent. Keepa[0](w = 1), then copya[r]toa[w]only whena[r] != a[w - 1]. Notice carefully: slotsa[w:]at the tail are leftover values, not cleared or deleted, because shortening the list is optional (del a[w:]if the caller requires lengthw). Returningwis what keeps the algorithmO(1)extra space.
def partition_evens_first(a: list[int]) -> int:
w = 0
for r in range(len(a)):
if a[r] % 2 == 0:
a[w], a[r] = a[r], a[w]
w += 1
return w
def dedupe_sorted(a: list[int]) -> int:
if not a:
return 0
w = 1
for r in range(1, len(a)):
if a[r] != a[w - 1]:
a[w] = a[r]
w += 1
return w
p = [3, 8, 5, 2, 7, 4]
evens = partition_evens_first(p)
print("partition_evens_first:", p, "even_count=", evens)
d = [1, 1, 2, 2, 2, 3, 5, 5]
w = dedupe_sorted(d)
print("dedupe_sorted:", d[:w], "raw_list=", d)partition_evens_first: [8, 2, 4, 3, 7, 5] even_count= 3
dedupe_sorted: [1, 2, 3, 5] raw_list= [1, 2, 3, 5, 2, 3, 5, 5]04. Step 3: cyclic placement for values in 1..n
Suppose a list of length n contains integers that mostly fall in 1..n, and you want to find missing or duplicate values in O(1) extra space without sorting in O(n log n) or allocating a set of size O(n). The insight is that value v belongs at index v - 1. Walk i from 0 to n - 1: while 1 <= a[i] <= n and the target slot a[a[i] - 1] does not already hold a[i], swap a[i] into a[a[i] - 1].
At first glance, a while loop nested inside for i in range(n) looks like O(n^2)—a single i can perform many swaps! Why is the total running time actually O(n)? Measure total swaps across the whole run, not swaps per i: every single swap places at least one number into its permanent home slot (a[v - 1] == v), and once a value sits at its home slot, a[a[i] - 1] != a[i] prevents it from ever being moved out again. With n slots, there can be at most n swaps across all iterations combined, so total work is O(n)!
When NOT to mutate in place: avoid in-place algorithms when callers expect their input list to stay unchanged, when the input arrives as an immutable tuple or read-only sequence, or when stability is mandatory and a readable O(n) list comprehension fits memory easily.
def cyclic_place(a: list[int]) -> int:
n = len(a)
swaps = 0
for i in range(n):
while 1 <= a[i] <= n and a[a[i] - 1] != a[i]:
j = a[i] - 1
a[i], a[j] = a[j], a[i]
swaps += 1
return swaps
c = [5, 1, 6, 1, 3, 6]
swaps = cyclic_place(c)
missing = [i + 1 for i, v in enumerate(c) if v != i + 1]
print("cyclic_place:", c, "swaps=", swaps, "missing=", missing)cyclic_place: [1, 6, 3, 1, 5, 6] swaps= 3 missing= [2, 4]05. Check your understanding
06. Apply it
Add a pytest file covering rotate_right, dedupe_sorted, and cyclic_place, including empty lists [], single-element lists [7], and k > len(a) (using Hypothesis to verify rotate_right against slice rotation). Then write find_missing_and_duplicate(nums: list[int]) -> tuple[list[int], list[int]] using cyclic_place without allocating any extra set or dict.
Next, bring the same quadratic-trap awareness to immutable text in Building Strings Without Quadratic Traps.
07. Review prompt
Without looking back:
- Walk through the three reversals that rotate
[7, 14, 21, 28, 35]right byk = 3. - Why does
dedupe_sortedreturn an integerwinstead of resizingainside the loop? - Prove why
cyclic_placeexecutes at mostnswaps across all iterations of the outerforloop.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.