Arrays · Core Array Techniques

Array Traversal Basics

Iterating an array once to track a running answer (min, max, sum, count) without extra data structures.

  • 4 min read
  • 13 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach
  3. A second flavor: more than one running value
  4. Where you'll see it
  5. Which tool for which job?
  6. Common mistakes
  7. Check yourself
  8. Key takeaways
  9. Quick revise
  10. Practice

Description

Array traversal means one pass over the elements while you keep some running state: a total, a smallest value, a count. It's the simplest array technique, and most of the others build on it. This skill makes that single pass automatic. You'll pick the right starting value, decide what an empty array should return, and learn when one pass isn't enough.

We'll go from simple to more technical:

  1. The pattern: one loop and one running value.
  2. Tracking more than one value in the same pass.
  3. Where the same shape appears in production code.
  4. The two edge cases that break it: empty input and the wrong starting value.

The approach

Keep one variable that holds the answer so far. Start it at a value that can't distort the result, then update it once per element. For a sum, start at 0. For a maximum, start from the first element, not from 0.

Here's why 0 is wrong for a maximum. Find the largest value in [-4, -2, -7, -1]:

After readingStarting from the first elementStarting from 0
-4-40
-2-20
-7-20
-1-10

The right answer is -1. Starting from 0 returns 0, a value that isn't even in the array.

Java

int findMax(int[] nums) {
    if (nums.length == 0) throw new IllegalArgumentException("empty array");
    int best = nums[0];                       // the first element, never 0
    for (int i = 1; i < nums.length; i++) {
        best = Math.max(best, nums[i]);
    }
    return best;
}

Python

def find_max(nums: list[int]) -> int:
    if not nums:
        raise ValueError("empty list")
    best = nums[0]                            # the first element, never 0
    for x in nums[1:]:
        best = max(best, x)
    return best

Every one-pass question has this shape. Only the starting value and the update change: 0 and + for a sum, the first element and max for a maximum, 0 and +1 for a count.

A second flavor: more than one running value

Some questions need two values from the same pass, such as the smallest and the largest. Keep one variable for each and update both inside the same loop. You still read every element once. "Two separate passes" and "one pass with two variables" are both O(n), but the second reads the data only once, which matters when the data comes from a stream.

Where you'll see it

Summing today's orders as they come out of a database cursor is the same loop. You keep one running total, and you see each row exactly once. A stream like that is often too big to hold in memory and can't be read twice. That's why "running state only" is worth getting comfortable with.

Which tool for which job?

You needUse
One number from the whole array (sum, min, max, count)a single pass with an accumulator
Answers about many sub-rangesprefix sums
Something about a contiguous windowa sliding window
Pairs from both endstwo pointers
A running total you can't hold in memorythe same pass over a stream

Common mistakes

MistakeWhat happensDo this instead
Starting a max at 0an all-negative array reports 0start from the first element (or the identity, -inf)
Starting a min at 0an all-positive array reports 0start from the first element (or +inf)
Ignoring the empty arraya crash, or a made-up answerdecide: error, sentinel or Optional/None
Summing large ints in a Java intsilent overflowaccumulate in a long
A fancier structure for a one-number questionextra code and memoryone pass is optimal

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. A function that finds the maximum starts with max = 0. What's wrong, and when does it show up?

Show answer

When every element is negative, it returns 0, a value that was never in the array. On ordinary inputs with at least one non-negative number it works. That's why the bug can ship unnoticed.

2. Why is Optional<Integer> often a better return type for "find the minimum" than a plain int?

Show answer

An int can't say "there is no answer". Any value you pick for that, such as 0 or -1, could also be a real minimum. The caller can't tell "the minimum is -1" from "the array was empty". Optional.empty() makes the missing case explicit.

3. Two pointers, sliding windows and Kadane's algorithm are all "a single pass with extra bookkeeping". What's the extra bookkeeping?

Show answer

More than one running value, updated by rules that fit the problem. Two pointers keep two indexes. A sliding window keeps its two edges and a running total of what's inside. Kadane's keeps the best sum ending here and the best sum overall. The single pass itself doesn't change.

Key takeaways

  • One pass with one running value (sum, min, max, count) is O(n) time and O(1) space.
  • The starting value must not distort the answer: 0 for a sum, the first element for a max or min.
  • Decide what empty input returns: an error, Optional/None, or a documented value.
  • Most other array techniques are this same pass with more values tracked.

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
One number from the arraya single pass
Many range questionsprefix sums
Contiguous windowssliding window
Both endstwo pointers
Min and max togetherpairwise comparisons
Variance in one passWelford's algorithm

Snippets worth knowing by heart

Java

long total = 0;                         // long: no overflow
int best = nums[0];                     // start from the first element, not 0
for (int x : nums) {
    total += x;
    best = Math.max(best, x);
}

Python

if not nums:
    raise ValueError("empty input")     # decide what empty means
best = nums[0]
for x in nums[1:]:
    best = max(best, x)

The traps

  • A max that starts at 0 (or a min): an all-negative array reports 0. Start from the first element.
  • Empty input with no decision: you crash or invent an answer. Choose an error, a sentinel or an empty result.
  • Java int sums: large totals overflow silently. Accumulate in a long.
  • Over-engineering: a sort or a map for a one-number question costs time and memory. One pass is already optimal.

Staff-level points, one line each

  • The invariant: after i elements, the accumulator is f of that prefix - so the initial value is f of nothing.
  • Folds: Stream.reduce, functools.reduce; itertools.accumulate gives every prefix.
  • Min and max in pairs: 1,498 comparisons instead of 1,998 for 1,000 elements.
  • 1,000 x 3,000,000 in a Java int wrapped to -1294967296.
  • 0.1 added ten times in a loop: 0.9999999999999999; Python's sum() (3.12+) and math.fsum give 1.0.
  • Naive variance of 1e9 + {4, 7, 13, 16} was 0.0; Welford gave 22.5.

Say it in an interview

  • "After each element, the running value is the answer for the prefix so far."
  • "I start the maximum from the first element so all-negative arrays work."
  • "I'd accumulate in a long so the sum can't overflow."
  • "Min and max together can be done in about 3n/2 comparisons by pairing elements."

Practice

This skill comes with 13 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Array Traversal Basics free

Second Largest, in One Pass

MediumProCoding problemJava · Python

Given an array of integers, find the second-largest distinct value in a single pass (no sorting, no library max called twice, no second loop). If fewer than two distinct values exist, print NONE.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Array Traversal Basics free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime