Skip to lesson

Array traversal patterns

Almost every array algorithm is built on top of a clean loop that visits elements in a deliberate order. Knowing the exact loop bounds for forward, backward, step, and neighbour-comparison passes eliminates off-by-one crashes before they happen.

Forward, backward, and step loops

A traversal is visiting every element of a data structure once, in a planned order, such as left to right through an array.

A traversal visits array elements in a fixed pattern: forward, backward, or every k-th index. Valid indices run from 0 to n - 1. The code below runs all three on one array.

Each of these loops does O(1) work per visited element, taking O(n) time and O(1) auxiliary space.

Example 1 · Forward, backward, and step-by-2 traversals on the same array

TraversalOrdersDemo.javaJava
public class TraversalOrdersDemo {    public static void main(String[] args) {        int[] nums = {10, 20, 30, 40, 50, 60};
        StringBuilder forward = new StringBuilder();        for (int i = 0; i < nums.length; i++) {            forward.append(nums[i]).append(" ");        }
        StringBuilder backward = new StringBuilder();        for (int i = nums.length - 1; i >= 0; i--) {            backward.append(nums[i]).append(" ");        }
        StringBuilder evenIndices = new StringBuilder();        for (int i = 0; i < nums.length; i += 2) {            evenIndices.append(nums[i]).append(" ");        }
        StringBuilder oddIndices = new StringBuilder();        for (int i = 1; i < nums.length; i += 2) {            oddIndices.append(nums[i]).append(" ");        }
        System.out.println("Forward      : " + forward.toString().trim());        System.out.println("Backward     : " + backward.toString().trim());        System.out.println("Even indices : " + evenIndices.toString().trim());        System.out.println("Odd indices  : " + oddIndices.toString().trim());    }}
Output
Forward      : 10 20 30 40 50 60
Backward     : 60 50 40 30 20 10
Even indices : 10 30 50
Odd indices  : 20 40 60

What this code does

  • The backward loop starts at nums.length - 1 (5) and uses i >= 0 with i-- so index 0 is included and -1 is never read.
  • Stepping by i += 2 from 0 visits indices 0, 2, 4, while starting from 1 visits 1, 3, 5.

A traversal is a pass through an array that visits elements according to a fixed pattern. In Java, an array arr of length n has valid indices from 0 to n - 1 inclusive:

  • Forward loop (0 to n - 1): for (int i = 0; i < arr.length; i++) visits elements left to right. When you only need each element's value and not its index, the enhanced loop for (int x : arr) is even cleaner.
  • Backward loop (n - 1 down to 0): for (int i = arr.length - 1; i >= 0; i--) visits elements right to left. This is essential when shifting elements right, scanning for the last occurrence of a value, or tracking what lies to the right of each index.
  • Step loop (i += k): for (int i = 0; i < arr.length; i += 2) visits every second element (such as all even indices 0, 2, 4, ...). Starting at i = 1 visits all odd indices 1, 3, 5, ....
  • Forward: starts at 0, continues while i < arr.length, increments with i++.
  • Backward: starts at arr.length - 1, continues while i >= 0, decrements with i--.
  • Step by k: increments with i += k (k >= 1); visits ⌈ n / k ⌉ elements, which is still O(n).

Running max, min, sum, and counting with conditions

You do not need separate passes to compute the minimum, maximum, sum, and conditional counts of an array — a single forward pass can update several running accumulators at once.

Example 2 · Computing running min, max, sum, and prefix maximums in one pass

RunningStatsDemo.javaJava
import java.util.Arrays;
public class RunningStatsDemo {    public static void main(String[] args) {        int[] temps = {-4, 2, -1, 7, 5, 9, 3};
        int min = temps[0];        int max = temps[0];        long sum = 0L;        int[] runningMax = new int[temps.length];
        for (int i = 0; i < temps.length; i++) {            int t = temps[i];            min = Math.min(min, t);            max = Math.max(max, t);            sum += t;            runningMax[i] = max; // Largest value seen in temps[0..i]        }
        System.out.println("Min         : " + min);        System.out.println("Max         : " + max);        System.out.println("Sum         : " + sum);        System.out.println("Running max : " + Arrays.toString(runningMax));    }}
Output
Min         : -4
Max         : 9
Sum         : 21
Running max : [-4, 2, 2, 7, 7, 9, 9]

What this code does

  • Initialising min and max to temps[0] (-4) works regardless of whether the array is all negative or mixed.
  • runningMax[i] stores the highest value seen up to index i, a building block used in stock-profit and rainwater problems.
  1. Guard against an empty array (if (nums.length == 0)) when minimum or maximum is required.
  2. Initialise max = nums[0] and min = nums[0], and long sum = 0L.
  3. Update max = Math.max(max, x), min = Math.min(min, x), and sum += x on each element.
  4. Increment a counter count++ whenever the element (or adjacent pair) satisfies your condition.

To track a running maximum or running minimum safely when the array may contain negative numbers, initialise int max = nums[0] and int min = nums[0] (after checking nums.length > 0), or use Integer.MIN_VALUE and Integer.MAX_VALUE. For a running sum, declare long sum = 0L whenever nums.length * maxValue can exceed Integer.MAX_VALUE (2,147,483,647). When counting with conditions, you either check a single element (if (nums[i] % 2 == 0) count++;) or compare adjacent neighbours (if (nums[i] > nums[i - 1]) count++;).

Index bugs to avoid when comparing neighbours

Comparing nums[i] with a neighbour is the most common source of ArrayIndexOutOfBoundsException, because the loop bounds must change with the neighbour you read. The code below shows safe bounds.

Notice how all three rules come from one simple check: plug your first i and last i into every [...] expression in the loop body and verify the result stays inside 0 .. nums.length - 1.

Example 3 · Safe loop bounds when comparing adjacent neighbours and local peaks

NeighbourComparisonDemo.javaJava
public class NeighbourComparisonDemo {    // Counts indices i >= 1 where nums[i] > nums[i - 1]    static int countIncreases(int[] nums) {        int count = 0;        for (int i = 1; i < nums.length; i++) {            if (nums[i] > nums[i - 1]) {                count++;            }        }        return count;    }
    // Counts interior indices 1 <= i <= n - 2 that are strictly greater than both neighbours    static int countLocalPeaks(int[] nums) {        int peaks = 0;        for (int i = 1; i < nums.length - 1; i++) {            if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {                peaks++;            }        }        return peaks;    }
    public static void main(String[] args) {        int[] elevation = {2, 5, 3, 8, 9, 4};        System.out.println("Increases in [2, 5, 3, 8, 9, 4] : " + countIncreases(elevation));        System.out.println("Peaks in [2, 5, 3, 8, 9, 4]     : " + countLocalPeaks(elevation));        System.out.println("Peaks in short array [10, 20]   : " + countLocalPeaks(new int[]{10, 20}));    }}
Output
Increases in [2, 5, 3, 8, 9, 4] : 3
Peaks in [2, 5, 3, 8, 9, 4]     : 2
Peaks in short array [10, 20]   : 0

What this code does

  • countIncreases reads nums[i - 1] and nums[i], so it starts at i = 1 and ends at i = nums.length - 1 (2->5, 3->8, and 8->9 are the 3 increases).
  • countLocalPeaks reads both nums[i - 1] and nums[i + 1], so it loops from i = 1 to i < nums.length - 1 (5 at index 1 and 9 at index 4 are the 2 peaks). On [10, 20], 1 < 1 is false, so it safely returns 0.

The most common ArrayIndexOutOfBoundsException in beginner DSA code happens when a loop compares nums[i] with its neighbour nums[i + 1] or nums[i - 1] using standard 0 to n - 1 bounds:

  • If your loop body reads nums[i - 1] and nums[i], start at i = 1 and stop at i < nums.length.
  • If your loop body reads nums[i] and nums[i + 1], start at i = 0 and stop at i < nums.length - 1.
  • If your loop body checks whether nums[i] is a strict local peak (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]), start at i = 1 and stop at i < nums.length - 1.

Find the bug

Find the loop bound bug

Tap the line with the wrong loop bounds.

Counts neighbours where the left one is bigger. Crashes on the last pass.

Round 1 of 3
For an empty array (nums.length == 0), i < nums.length - 1 evaluates to 0 < -1 (false), so a loop starting at i = 0 with condition i < nums.length - 1 safely executes zero times!

Next step

Check your understanding

10 quick questions