Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 30 min · revision 1

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

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]:

  1. Reversing the whole array flips AB into rev(B) rev(A) = [60, 50, 40, 30, 20, 10]—now the last k items sit at the front, just backwards.
  2. Reversing the first k items ([0..k-1]) restores B: [50, 60, 40, 30, 20, 10].
  3. Reversing the last n - k items ([k..n-1]) restores A: [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.

Python · range reversal and three-reversal rotation
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)
Expected output
rotate_right(k=2): [50, 60, 10, 20, 30, 40]
k=8 gives the same list: True

03. 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 element a[r] is swapped into a[w] and w advances by 1. The invariant is simple: after each iteration, a[:w] holds only even numbers and a[w : r + 1] holds only odd numbers. Note that swapping a[w], a[r] is unstable: on the input [3, 8, 5, 2, 7, 4] below, the odd values arrive in the order 3, 5, 7 but end in the order 3, 7, 5. If you need stability with O(n) time, an O(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), a is already sorted, so duplicates sit adjacent. Keep a[0] (w = 1), then copy a[r] to a[w] only when a[r] != a[w - 1]. Notice carefully: slots a[w:] at the tail are leftover values, not cleared or deleted, because shortening the list is optional (del a[w:] if the caller requires length w). Returning w is what keeps the algorithm O(1) extra space.
Python · write-pointer partition and deduplication
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)
Expected output
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.

Python · cyclic placement for values in 1..n
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)
Expected output
cyclic_place: [1, 6, 3, 1, 5, 6] swaps= 3 missing= [2, 4]

05. Check your understanding

Practice check · 3 questions

Invariants of in-place transformations

Predict edge cases and complexity invariants.

Q1. Why does `cyclic_place` bind `j = a[i] - 1` before `a[i], a[j] = a[j], a[i]` instead of writing `a[i], a[a[i] - 1] = a[a[i] - 1], a[i]`?
Q2. You delete the line `k %= n` from `rotate_right`. A test with `a = [4, 8, 15, 16]` and `k = 4` still passes, because rotating by `n` leaves the list unchanged. What happens when the same code runs with `k = 6`?
Q3. When is an in-place transformation like `cyclic_place` the **wrong** choice compared to allocating an `O(n)` `set` or new list?
Practice only: not graded, not saved, not evidence.

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:

  1. Walk through the three reversals that rotate [7, 14, 21, 28, 35] right by k = 3.
  2. Why does dedupe_sorted return an integer w instead of resizing a inside the loop?
  3. Prove why cyclic_place executes at most n swaps across all iterations of the outer for loop.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check