Java
Range Lookup
Programming
Code Implementation
Software Development

Range lookup in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Range lookup means mapping a value into the interval that contains it. Typical examples are tax brackets, grade bands, pricing tiers, and risk levels. In Java, the best implementation depends on how many ranges you have, whether they change at runtime, and whether lookups happen much more often than updates.

Start With A Clear Range Model

Before choosing a data structure, define the rules precisely:

  • are range boundaries inclusive or exclusive,
  • can ranges overlap,
  • are the ranges sorted,
  • what happens if no range matches.

Those rules matter more than the syntax because they determine whether the lookup logic is correct.

Simple Sequential Lookup

For a small fixed list of ranges, a linear scan is often perfectly fine and easier to maintain than a more complex structure.

java
1import java.util.List;
2
3record Range(int startInclusive, int endInclusive, String label) {
4    boolean contains(int value) {
5        return value >= startInclusive && value <= endInclusive;
6    }
7}
8
9public class LinearRangeLookup {
10    public static String lookup(int value, List<Range> ranges) {
11        for (Range range : ranges) {
12            if (range.contains(value)) {
13                return range.label();
14            }
15        }
16        return "UNKNOWN";
17    }
18}

If there are only five or ten ranges, this is often the most reasonable solution.

Binary Search On Sorted Boundaries

If the ranges are sorted and lookups are frequent, binary search reduces lookup cost.

java
1import java.util.List;
2
3record Range(int startInclusive, int endInclusive, String label) {}
4
5public class BinaryRangeLookup {
6    public static String lookup(int value, List<Range> ranges) {
7        int left = 0;
8        int right = ranges.size() - 1;
9
10        while (left <= right) {
11            int mid = left + (right - left) / 2;
12            Range range = ranges.get(mid);
13
14            if (value < range.startInclusive()) {
15                right = mid - 1;
16            } else if (value > range.endInclusive()) {
17                left = mid + 1;
18            } else {
19                return range.label();
20            }
21        }
22
23        return "UNKNOWN";
24    }
25}

This works only if the ranges are non-overlapping and sorted by start value. If those assumptions are false, binary search will produce unreliable results.

TreeMap Is Useful For Dynamic Thresholds

When the lookup is based on threshold starts rather than full range objects, TreeMap offers a clean approach with floorEntry.

java
1import java.util.Map;
2import java.util.TreeMap;
3
4public class TreeMapRangeLookup {
5    public static void main(String[] args) {
6        TreeMap<Integer, String> bands = new TreeMap<>();
7        bands.put(0, "LOW");
8        bands.put(50, "MEDIUM");
9        bands.put(80, "HIGH");
10
11        int score = 72;
12        Map.Entry<Integer, String> entry = bands.floorEntry(score);
13
14        System.out.println(entry != null ? entry.getValue() : "UNKNOWN");
15    }
16}

This style is ideal when each threshold means "from here upward until the next threshold." It is common in grading and pricing problems.

Validate Ranges Up Front

A robust solution checks for overlaps and invalid input during construction instead of letting bad ranges silently produce wrong answers later.

java
1import java.util.Comparator;
2import java.util.List;
3
4public class RangeValidator {
5    public static void validate(List<Range> ranges) {
6        List<Range> sorted = ranges.stream()
7                .sorted(Comparator.comparingInt(Range::startInclusive))
8                .toList();
9
10        for (int i = 1; i < sorted.size(); i++) {
11            Range prev = sorted.get(i - 1);
12            Range curr = sorted.get(i);
13            if (curr.startInclusive() <= prev.endInclusive()) {
14                throw new IllegalArgumentException("Overlapping ranges detected");
15            }
16        }
17    }
18}

That kind of guardrail often matters more than micro-optimizing the lookup itself.

Which Approach To Choose

Use a simple scan when:

  • the range list is small,
  • clarity matters more than asymptotic improvement,
  • the ranges rarely change.

Use binary search when:

  • the ranges are sorted and non-overlapping,
  • lookups are frequent,
  • you want predictable fast lookup in a static list.

Use TreeMap when:

  • thresholds can change dynamically,
  • floor-based lookup expresses the business rule naturally,
  • you want built-in ordered navigation operations.

Common Pitfalls

  • Failing to define whether boundaries are inclusive or exclusive.
  • Applying binary search to unsorted or overlapping ranges.
  • Using a complex structure when a short linear scan would be simpler and sufficient.
  • Forgetting to handle values outside every defined range.
  • Storing only labels without validating that the thresholds actually describe valid intervals.

Summary

  • Range lookup is mostly about precise interval rules, not just data structures.
  • A linear scan is often enough for small, fixed rule sets.
  • Binary search is a good fit for sorted, non-overlapping ranges.
  • 'TreeMap.floorEntry is elegant for threshold-based mappings.'
  • Validate ranges early so bad configuration does not turn into silent wrong answers.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.