Title: Find the Range of an Array
In this guide, you will learn how to find the range of an array in Java. The range is the difference between the largest and smallest values, and it is one of the simplest ways to describe how spread out a dataset is.
We will frame the problem, build a full Java program with a single pass, trace it on a concrete input, and then look at the overflow trap, the else if micro-optimisation, and the follow-up questions a Java interviewer tends to ask on this problem.
Understanding the Problem
Given an array of n integers, the range is defined as max(numbers) - min(numbers). For the input [12, 7, 25, 3, 18, 9], the maximum is 25 and the minimum is 3, so the range is 22.
The range is always non-negative because max is at least as large as min. There is one Java-specific pitfall hiding in the one-line formula: subtracting Integer.MIN_VALUE from Integer.MAX_VALUE overflows a plain int, so the return type needs to be long if the input can span the full int range.
Approach / Algorithm Steps
- Reject the input early if the array is
nullor empty, since the range is undefined when there are no values. - Seed
minandmaxtonumbers[0]. Using the first element avoids any need to reach forInteger.MIN_VALUEorInteger.MAX_VALUEas a sentinel. - Walk the array starting at index
1. For each element, updateminif the element is smaller, otherwise check whether to updatemax. Theelse ifis correctness-neutral but avoids a pointless comparison, since a value cannot simultaneously be smaller than the current min and larger than the current max after both are seeded from the same element. - After the loop, cast
maxtolongand subtractmin. The cast widens the subtraction so it cannot overflow for any pair ofintvalues. - Return the
longdifference.
Java Program
public class ArrayRange {
public static long findRange(int[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Array must not be null or empty");
}
int min = numbers[0];
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
} else if (numbers[i] > max) {
max = numbers[i];
}
}
return (long) max - min;
}
public static void main(String[] args) {
int[] values = {12, 7, 25, 3, 18, 9};
long range = findRange(values);
System.out.println("Range: " + range);
}
}Explanation of the Program
The class ArrayRange exposes a single static method, findRange, which takes an int[] and returns a long. The long return type is deliberate: for inputs that contain both Integer.MIN_VALUE and Integer.MAX_VALUE, the true range is 4294967295, which does not fit in a signed int.
The method starts by rejecting null or empty input with an IllegalArgumentException. The range of an empty array is undefined, and silently returning 0 would be worse than throwing because 0 is a valid range for a non-empty input of all equal values.
Both min and max are seeded to numbers[0]. Seeding from the first element removes the need for sentinel values and keeps the code honest about where min and max actually came from. The loop then starts at index 1, since the element at index 0 is already accounted for by the seed.
Inside the loop, the else if is a small but intentional choice. Once min and max are seeded from the same element, no single later value can be both strictly less than min and strictly greater than max. The else if captures that fact in the control flow and saves one comparison per iteration for elements that update min.
The final line, return (long) max - min;, is where the overflow protection lives. The (long) cast widens max before the subtraction, so the - operation is a long subtraction and can represent any difference between two int values. Without the cast, Integer.MAX_VALUE - Integer.MIN_VALUE would wrap to -1.
The main method is a tiny driver: it builds a sample array, calls findRange, and prints the result. Running it prints Range: 22, which matches 25 - 3 for the sample input.
Step-by-Step Trace
Let us trace findRange on the input [8, 3, 11, 5, 2, 9]. The expected final answer is 11 - 2 = 9.
| Iteration (i) | numbers[i] | min (before) | max (before) | Branch | min / max (after) |
|---|---|---|---|---|---|
| seed | 8 | – | – | seed from numbers[0] | 8 / 8 |
| 1 | 3 | 8 | 8 | 3 < 8, update min | 3 / 8 |
| 2 | 11 | 3 | 8 | 11 > 8, update max | 3 / 11 |
| 3 | 5 | 3 | 11 | neither branch | 3 / 11 |
| 4 | 2 | 3 | 11 | 2 < 3, update min | 2 / 11 |
| 5 | 9 | 2 | 11 | neither branch | 2 / 11 |
At the end of iteration i, min and max hold the smallest and largest values seen so far across numbers[0..i]. After the loop exits, the final (long) 11 - 2 evaluates to 9.
Examples
Example 1: All positive integers
A straightforward input where the range is simply the gap between the largest and smallest positive values.
int[] nums = {10, 2, 8, 15, 6};
long range = findRange(nums);
System.out.println(range);
// min = 2, max = 15
// Output: 13Example 2: Mixed positive and negative values
Negative inputs work the same way. The range crosses zero but stays non-negative.
int[] nums = {-5, 3, -2, 7, 1};
long range = findRange(nums);
System.out.println(range);
// min = -5, max = 7
// Output: 12Example 3: All identical elements
When every element has the same value, min and max are equal, so the range is zero.
int[] nums = {4, 4, 4, 4};
long range = findRange(nums);
System.out.println(range);
// min = 4, max = 4
// Output: 0Common Mistakes to Avoid
The algorithm is short, but Java’s integer arithmetic and the seed-vs-sentinel decision together produce several reliable traps. These are the mistakes learners actually make on this problem.
- Int subtraction overflow – computing
max - mininintarithmetic silently wraps when the array contains bothInteger.MIN_VALUEandInteger.MAX_VALUE, producing a negative range of-1. Cast one operand tolongbefore the subtraction. - Seeding
minto0– fails on arrays with only positive values (for example[5, 7, 9]) becauseminincorrectly stays at0. Seedminandmaxfromnumbers[0]instead. - Seeding
maxtoInteger.MIN_VALUEonly – works for finding the max, but if the symmetric mistake is applied tominand you then forget to initialise one of them, the error is silent on most inputs and surfaces only on the empty-array path. Prefer the first-element seed and the up-front empty check together. - Returning
min - maxby typo – produces a negative range, sincemin <= maxby construction. Watch the final expression carefully. - Using
if/ifinstead ofelse if– correctness-neutral but checks for a condition that can never be true (a single value cannot be both the new min and the new max once both are seeded from the same element). Useelse ifto make the mutual exclusion visible.
Edge Cases to Test
Walk through this checklist before you call the solution done. The first few are the ones an interviewer is most likely to probe.
- Empty array
- Null array reference
- Single-element array (range is
0) - All identical elements
- All negative elements
- Already sorted and reverse-sorted inputs
Integer.MIN_VALUEandInteger.MAX_VALUEboth present (overflow risk)- Array of exactly two elements (smallest case where the loop runs once)
Additional Considerations
The algorithm runs in O(n) time, since every element is visited exactly once, and there is no way to do better because any element can be the new min or new max. The space complexity is O(1), because only three local variables (min, max, and the loop counter) are allocated regardless of the input size.
The Integer.MIN_VALUE and Integer.MAX_VALUE edge case is the one worth internalising. In int arithmetic, Integer.MAX_VALUE - Integer.MIN_VALUE evaluates to -1 because the subtraction wraps modulo 2^32. Widening either operand to long before the subtraction removes the wrap, since long has enough headroom to represent any difference between two int values.
A classic micro-optimisation for this problem is to walk the array in pairs: compare each pair of adjacent elements first (one comparison), then compare the smaller against min and the larger against max (two more comparisons). That yields 3n / 2 comparisons instead of 2n, at the cost of slightly more code and worse branch prediction on modern CPUs. For most inputs the plain else if version is already fast enough.
Interview Follow-up Questions
The base problem is only the opening move. Expect the interviewer to push with questions like these, each probing a different axis of the solution.
- How would you compute the range of a sorted array? – the answer collapses to O(1): return
numbers[n - 1] - numbers[0], taking care to widen tolong. - How would you compute the range of a stream of numbers of unknown length? – maintain a running
minandmax; the loop body is identical but termination comes from end-of-stream rather than array length. - How would you support repeated range queries over arbitrary subarrays of a static array? – build a sparse table or segment tree over min and max in O(n log n) preprocessing time, then answer each query in O(log n) (or O(1) for the sparse table).
- How would you reduce the number of comparisons below
2n? – walk the array in pairs: compare the pair, then feed the smaller to themincheck and the larger to themaxcheck for a total of3n / 2comparisons. - How would you compute the range of billions of values that do not fit in memory? – partition the input, compute the
(min, max)pair of each partition independently, then take the min of the mins and the max of the maxes; the partition step is embarrassingly parallel.
Conclusion
Finding the range of an array in Java is a single pass that tracks min and max side by side, with two decisions tucked inside it: seed both from numbers[0] so no sentinel is needed, and widen to long before the final subtraction so the result survives the full int range. Once those two habits are in place, the same shape of code extends cleanly to streams, to parallel reduce, and to the pair-wise comparison variant that cuts the comparison count by a quarter.
Try adapting the code above to also return the (min, max) pair rather than just the range, and compare the two methods on arrays that touch both Integer.MIN_VALUE and Integer.MAX_VALUE. The pair-returning version avoids the overflow entirely, since no subtraction ever happens.
You can learn more Array problems like this one here: Arrays.



