Foundation · Module 3 · Lesson 2
In-place manipulation
Reverse, rotate, partition, and remove values.
Lesson 14 of 123
1d streakIn-Place Algorithms: Zero Extra Memory Tricks
In-place algorithms modify the input array directly using only $O(1)$ auxiliary memory. In technical interviews, in-place manipulation tests your ability to coordinate pointer movements without overwriting values you will need later.
Rotate array [1, 2, 3, 4, 5, 6, 7] right by k = 3 positions:
Goal: [5, 6, 7, 1, 2, 3, 4]
Step 1: Reverse entire array:
[1, 2, 3, 4, 5, 6, 7] --> [7, 6, 5, 4, 3, 2, 1]
Step 2: Reverse first k = 3 elements:
[7, 6, 5, 4, 3, 2, 1] --> [5, 6, 7, 4, 3, 2, 1]
Step 3: Reverse remaining n - k elements:
[5, 6, 7, 4, 3, 2, 1] --> [5, 6, 7, 1, 2, 3, 4]
Time Complexity: O(n) | Auxiliary Space: O(1) | Zero extra buffer allocated!// Algorithm 1: Rotate Array in O(n) time and O(1) space
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1); // 1. Reverse all
reverse(nums, 0, k - 1); // 2. Reverse first k
reverse(nums, k, nums.length - 1); // 3. Reverse remaining
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start++] = nums[end];
nums[end--] = temp;
}
}
// Algorithm 2: Dutch National Flag (Sort 0s, 1s, and 2s in a single pass)
public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
swap(nums, low++, mid++);
} else if (nums[mid] == 1) {
mid++;
} else { // nums[mid] == 2
swap(nums, mid, high--); // Notice: mid does NOT advance here!
}
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}Active Recall Checkpoint
In the Dutch National Flag algorithm, why does mid NOT advance after swapping with high?
Hint: Consider where the element at high came from before the swap.
Show answer & explanation
The element swapped in from high is unexamined—it could be a 0, 1, or 2. We must keep mid at the same position so the next loop iteration inspects this newly swapped element.
Cost Model
Complexity & Trade-offs
When to use it
- Contiguous data, strings, matrix grids, and in-place transformations.
- Problems where indexes encode processed regions.
- Cache-friendly scans and compact storage.
Common mistakes
- Using a stale index after insertion, deletion, or a boundary move.
- Overwriting a value before it has been consumed.
- Assuming a matrix is square or a string is mutable.
Practice prompts
- Reproduce the worked In-place manipulation example without looking at the trace.
- Change one input condition and explain whether the In-place manipulation invariant still holds.
- Implement the approach, derive its cost, and compare it with a straightforward baseline.
Mastery check