Learn / Arrays

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.

ProblemStateStart
Sumtotal0
Largestlargest so farfirst element
Second largestlargest and second"nothing yet"
Longest run of 1scurrent run, best run0, 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".

xWhat happenslargestsecond
12bigger than largest12nothing
35bigger than largest, so 12 drops to second3512
1smaller than both3512
10smaller than second3512
34below largest but above second3534

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] when i is already the last index.
  • Rotating by k without first taking k % n, when k can be larger than the length.

Problems

0 of 15 solved

Check yourself

To find the largest element, what should the running "largest" start as?

An element is a "leader" if it is bigger than everything to its right. Which direction of walk makes this one pass?

How do you rotate [1, 2, 3, 4, 5] right by 2 in place?

In Java, C++ and Python, which test correctly finds odd numbers, including negative ones such as -3?