Array Manipulation: Complete Guide with In-Place Examples
Array manipulation shows up in nearly every coding interview. Whether you need to reverse a string, sort three distinct values without extra space, or find a maximum subarray, the core skill is the same: rearrange data in place. These techniques turn
Definition: array manipulation covers a family of in-place algorithms that rearrange elements using pointers, swaps, and markers. The common thread is that every operation happens within the original array, using at most a constant amount of extra memory
Real-World Analogy
Imagine organizing a crowded bookshelf with no extra space. You want to group all the red-spined books on one side and all the blue-spined books on the other. Since you cannot set books aside on the floor, you pick up one book at a time and swap it with whatever is sitting in the spot it should occupy. Every swap moves one book closer to its target, and you never need more than the space of one book to hold the temporary value.
This is exactly what in-place array algorithms do. The array is your shelf. Each swap or assignment is a single book moving into position. No second shelf, no extra storage. Just careful, targeted swaps until every element lands where it belongs.
Visual Explanation
The fundamental building block of in-place array manipulation is the two-pointer reversal. Two pointers start at opposite ends and swap elements as they close in toward the center.
graph TD
I["Initialize left=0, right=n-1"] --> C{"left < right?"}
C -->|Yes| S["Swap edges and close in"]
S --> M["Advance pointers inward"]
M --> C
C -->|No| D["Done. Array is reversed"]
Each swap pairs the outermost unprocessed elements. The pointers move inward because the edges are settled after each swap. When they cross, the entire array has been reversed in a single pass.
You can extend this same idea to more complex operations. Rotation chains three reversals. The Dutch flag algorithm adds a third pointer to partition three value groups. Kadane’s algorithm replaces pointers with running sums. The principle stays the same: process each element once, make your decision, and move on.
When to Use This Pattern
These techniques are the right tool when the problem has a few specific characteristics.
- You have a linear data structure (array, string, linked list) and need to rearrange elements without allocating a second structure. If the problem says “in-place” orextra memory, this pattern is likely the answer.O(1)
- You need to reverse, rotate, or partition elements by a condition. Straight reversals, three-reversal rotations, and Dutch flag partitioning are all manifestations of the same two-pointer idea.
- You are looking for a contiguous subarray with optimal properties, like maximum sum or minimum length. Kadane’s algorithm and its variants handle these cases in one pass.
- The brute-force solution checks every pair or permutation, and you notice the problem can be solved with a single scan. That is when you reach for pointers or running accumulators.
- The values in your array fall into a small, known set of categories. Dutch flag partition handles three categories, and the technique generalizes to k categories with k pointers or a write-index.
Complexity Analysis
All the techniques in this chapter share a common cost profile: a single pass through the input, constant extra space.
| Operation | Time | Space | Notes |
|---|---|---|---|
| Two-pointer reversal | O(N) | O(1) | Each element swapped exactly once |
| Array rotation | O(N) | O(1) | Three reversals, each linear |
| Dutch flag partition | O(N) | O(1) | Single pass, three pointers |
| Move zeroes (write pointer) | O(N) | O(1) | One read, one write pointer |
| Kadane’s algorithm | O(N) | O(1) | Two running variables, one pass |
The time is
Common Mistakes
These errors all share a root cause: losing track of pointer positions or boundary conditions.
Mistaking the loop condition. The most common bug in two-pointer reversal is writing while (left <= right) instead of while (left < right). With an odd-length array, the middle element would be swapped with itself on the final iteration. The result is correct but it wastes an operation and signals inattention if the interviewer notices. With an even-length array, the pointers pass each other, and on the next iteration they swap elements that have already been processed, corrupting the array.
To catch this during practice, trace through an array of length 2 and length 3 on paper before you write any code. Notice where the pointers end up at each step.
Forgetting the modulo in rotation. When rotating an array by k positions, you must compute k = k % array.length at the start. If k is larger than the array length, you rotate past the full cycle and land in a position that looks right but is off by some multiple of n. The three-reversal technique will then reverse the wrong segment.
Confusing the scan pointer with the boundary pointer in Dutch flag. The Dutch flag algorithm uses three pointers: low (end of zeros), mid (current scan position), and high (start of twos). When you see a zero, you swap with low and advance both low and mid. You advance only mid when you see a one. You swap with high when you see a two but do not advance mid because the swapped-in value is unprocessed. Newcomers frequently advance mid after a two-swap, which skips a value that has not been examined.
Initializing Kadane’s accumulator to zero. If every element in the array is negative, starting max_ending_here at 0 will produce 0 as the answer instead of the least-negative element. Initialize it to nums[0] and start the loop at index 1.
Related Patterns
- Two Pointers . Reversal is a specific application of the two-pointer technique. The two-pointers page covers the general case for sorted arrays and pair-finding problems.
- Sliding Window . Sliding window also processes arrays in one pass with two pointers, but it maintains a window between them rather than moving them from opposite ends. Use sliding window when a contiguous segment must meet a running condition like sum or character frequency.
- Prefix Sum
. Where Kadane’s algorithm tracks the best subarray ending at each position, prefix sums tradepreprocessing forO(N)range-sum queries. Choose prefix sum when you need many subarray sum queries on a static array.O(1)
Next Steps
Once the concept is clear, the next step is making the code automatic. Check out the code templates for memorizable implementations in 6 languages, then work through the practice problems to apply the pattern to real interview questions.