Array traversal patterns
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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()); }}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 usesi >= 0withi--so index0is included and-1is never read. - Stepping by
i += 2from0visits indices0, 2, 4, while starting from1visits1, 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 (
0ton - 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 loopfor (int x : arr)is even cleaner. - Backward loop (
n - 1down to0):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 indices0, 2, 4, ...). Starting ati = 1visits all odd indices1, 3, 5, .... - Forward: starts at
0, continues whilei < arr.length, increments withi++. - Backward: starts at
arr.length - 1, continues whilei >= 0, decrements withi--. - 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
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)); }}Min : -4 Max : 9 Sum : 21 Running max : [-4, 2, 2, 7, 7, 9, 9]
What this code does
- Initialising
minandmaxtotemps[0](-4) works regardless of whether the array is all negative or mixed. runningMax[i]stores the highest value seen up to indexi, a building block used in stock-profit and rainwater problems.
- Guard against an empty array (
if (nums.length == 0)) when minimum or maximum is required. - Initialise
max = nums[0]andmin = nums[0], andlong sum = 0L. - Update
max = Math.max(max, x),min = Math.min(min, x), andsum += xon each element. - 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
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})); }}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
countIncreasesreadsnums[i - 1]andnums[i], so it starts ati = 1and ends ati = nums.length - 1(2->5,3->8, and8->9are the 3 increases).countLocalPeaksreads bothnums[i - 1]andnums[i + 1], so it loops fromi = 1toi < nums.length - 1(5at index 1 and9at index 4 are the 2 peaks). On[10, 20],1 < 1isfalse, so it safely returns0.
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]andnums[i], start ati = 1and stop ati < nums.length. - If your loop body reads
nums[i]andnums[i + 1], start ati = 0and stop ati < 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 ati = 1and stop ati < 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 3nums.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