Sub topic 9
In-place algorithms
This chapter assumes you can read Big O notation, know how Python lists and recursion work, and have seen the difference between input space and auxiliary space. An in-place algorithm is one that transforms its input using only O(1) auxiliary space, apart from the input itself. It overwrites or rearranges the data it was given instead of building a second structure.
What "in place" means
The definition counts only auxiliary space. The input already exists, so reusing it costs nothing extra. Two consequences follow:
- An in-place function usually changes its argument. The caller sees the change.
- A function can run in O(1) auxiliary space and still not be in place if it returns a new object. Returning a fresh list means allocating one.
Strictly, "in place" means constant extra memory. In practice, some authors also call an algorithm in place if it uses O(log n) extra space, for example the recursion stack of quicksort. State which meaning you use when you compare algorithms.
Copy versus in place
Reversing a list shows the difference clearly.
def reverse_copy(a):
return a[::-1]
def reverse_in_place(a):
i, j = 0, len(a) - 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1reverse_copy allocates a new list of the same length, so it needs O(n) auxiliary space. reverse_in_place keeps two integer indexes and swaps elements inside the input, so it needs O(1) auxiliary space. Both run in O(n) time.
The trade-offs
In-place code saves memory, but it has costs.
| Aspect | Copying version | In-place version |
|---|---|---|
| Auxiliary space | O(n) | O(1) |
| Original input | Preserved | Destroyed or changed |
| Safe with shared references | Yes | No, other holders see the change |
| Ease of reasoning | Simple | Needs care with indexes and order |
The main risk is aliasing. In Python, two names can refer to the same list. If another part of the program still relies on the original order, an in-place reversal breaks it without any error.
Common errors
- Hidden copies. Writing
a = a[::-1]inside a function looks like an in-place update, but it builds a new list and rebinds the local name. The caller's list is unchanged, and you paid O(n) space. Usea[:] = a[::-1]only if you accept the temporary copy, or use a swap loop to avoid it. - Overwriting data you still need. When writing results into the input, make sure you have already read the value you are about to replace. Two-pointer loops that read ahead and write behind are safe. Loops that write ahead of the reader are not.
- Counting the recursion stack. A recursive reversal that swaps the ends and recurses on the middle changes the input in place, but each call adds a stack frame. Its auxiliary space is O(n), so it is not in place by the strict definition.
- Assuming in place means faster. It saves memory. Time may stay the same, and it can get worse if the algorithm needs extra passes to avoid a buffer.
When to choose in place
Use an in-place approach when the input is large, memory is limited, and no one needs the original data afterward. Prefer a copying approach when the input is shared, when you need the original for comparison or undo, or when clarity matters more than a few kilobytes.
Exercise
The function below removes duplicates from a sorted list and returns the count of unique values, moving them to the front of the same list. What is its auxiliary space, and is it in place? Why must the read index stay ahead of the write index? def dedupe_sorted(a): 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
Show answer
Auxiliary space is O(1): it uses only the integers w and r, and it writes into the input list. It is in place. The read index r is always at least as large as the write index w, so a write never overwrites an element that has not been read yet. If w could pass r, the function would destroy unread values.