Traversal and in-place tricks
Walk the array once, carrying a small running state (a total, a best-so-far, a run length), and change it in place with two indexes when you need to rearrange.
How to recognise it
- The answer is one number or one yes/no about the whole array (a sum, a count, the largest, "is it sorted?").
- Each element only needs to be compared with what you have seen so far, or with its neighbour.
- The question asks you to rearrange the array without extra memory (reverse, rotate).
- Something depends on everything to the right of an element, such as leaders. Walk from the right instead.
The idea in one picture
Picture walking along a row of numbered boxes with a notebook. You open each box once, glance at it, update one or two notes ("largest so far: 9", "current run of ones: 3"), and move on. At the end, your notes hold the answer. That is a traversal: one pass, O(n) time, a few variables.
Some jobs need the boxes moved instead. Put one finger on the leftmost box and one on the rightmost, swap them, and move both fingers inwards. That is the in-place two-index trick behind reversing and rotating.
Template 1: one pass with a running state
state = starting value # 0 for a sum, the first element for a max, ...
for x in nums:
update state using x
return state (or something computed from it)
The only design work is choosing the state and its starting value.
| Problem | State | Start |
|---|---|---|
| Sum | total | 0 |
| Largest | largest so far | first element |
| Second largest | largest and second | "nothing yet" |
| Longest run of 1s | current run, best run | 0, 0 |
| Is sorted? | (compare with previous) | - |
Template 2: two indexes moving inwards
left = 0
right = n - 1
while left < right:
swap nums[left] and nums[right]
left = left + 1
right = right - 1
Reversing a range this way is the building block for rotation. Rotating right by k is three reversals: the whole array,
the first k, then the rest.
Template 3: walk from the right
When a question depends on "everything after this element", walk from the end and carry the summary of what is to the right. Leaders in an array is the first example. Later, "next greater element" and suffix sums use the same idea.
A guided example: the second largest distinct value in [12, 35, 1, 10, 34]
Keep two notes, largest and second, both "nothing yet".
| x | What happens | largest | second |
|---|---|---|---|
| 12 | bigger than largest | 12 | nothing |
| 35 | bigger than largest, so 12 drops to second | 35 | 12 |
| 1 | smaller than both | 35 | 12 |
| 10 | smaller than second | 35 | 12 |
| 34 | below largest but above second | 35 | 34 |
One pass, and the answer is 34. Sorting would also work, but costs O(n log n).
Common mistakes
- Starting a maximum at 0, which fails on all-negative arrays.
- Testing odd numbers with
x % 2 == 1, which misses negatives in Java and C++. - Reading
nums[i + 1]wheniis already the last index. - Rotating by
kwithout first takingk % n, whenkcan be larger than the length.
Problems
- Sum of Array Elementseasyguide ready
- Count of odd numbers in Arrayeasyguide ready
- Check if the Array is Sorted Ieasyguide ready
- Reverse an arrayeasyguide ready
- Linear Searcheasyguide ready
- Largest Elementeasyguide ready
- Second Largest Elementeasyguide ready
- Max Consecutive Oneseasyguide ready
- Leaders in an Arrayeasyguide ready
- Find the maximum and minimum element in an arrayeasyguide ready
- Minimise the maximum difference between heightseasyguide ready
- Maximum and minimum of an array using minimum number of comparisonseasyguide ready
- Searching in an array where adjacent differ by at most keasyguide ready
- Rotate Arraymediumguide ready
- Check if Array Is Sorted and Rotatedeasyguide ready