Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Shipping fees depend on order total: 0 to 49.99 costs 7, 50 to 99.99 costs 4, 100 and above is free. Using a TreeMap<BigDecimal, BigDecimal> keyed by the lower bound, write the lookup and explain the NavigableMap method you used.

We store each tier under its lower bound, put(0, 7), put(50, 4) and put(100, 0), and look up a fee with floorEntry(total).getValue(). floorEntry returns the entry with the greatest key that is less than or equal to the total, which is exactly the tier the total falls into. It returns null for totals below the smallest key, so we must handle that case.

Why this question is asked

Price tiers, tax bands, discount levels and rate cards all have the same shape: a range of values maps to one result. Many developers write a chain of if statements for this, and the chain grows and breaks every time the business adds a tier. Interviewers ask this question to see whether we know that TreeMap can answer range questions directly, and whether we notice the details that make money code tricky, such as null results and the scale of BigDecimal. In this answer, we will recap what TreeMap and NavigableMap give us, write the lookup, look at the edge cases, explain why the lookup is fast, and see a BigDecimal surprise that TreeMap and HashMap handle differently.

1A Quick Recap of TreeMap and NavigableMap

A TreeMap is a Map that keeps its keys sorted. A HashMap puts keys into buckets by their hash, so it has no idea which key is smaller or larger than another. A TreeMap instead compares keys, either with their natural order (compareTo) or with a Comparator we give it, and stores them in sorted order.

Because the keys are sorted, TreeMap can answer questions that a HashMap cannot. These questions are declared in the NavigableMap interface, which TreeMap implements. The four neighbour methods are the ones we use most: floorEntry(k) gives the entry with the greatest key less than or equal to k, ceilingEntry(k) gives the smallest key greater than or equal to k, lowerEntry(k) gives the greatest key strictly less than k, and higherEntry(k) gives the smallest key strictly greater than k. Each has a variant that returns only the key, such as floorKey(k).

2Writing the Lookup With floorEntry

The idea is to store only the start of each tier. A total of 73.20 belongs to the tier that starts at 50, because 50 is the largest lower bound that is not above 73.20. That is the definition of a floor, so floorEntry does the whole search for us.

Java
import java.math.BigDecimal;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
class ShippingFees {
private final NavigableMap<BigDecimal, BigDecimal> tiers = new TreeMap<>();
ShippingFees() {
tiers.put(new BigDecimal("0"), new BigDecimal("7"));
tiers.put(new BigDecimal("50"), new BigDecimal("4"));
tiers.put(new BigDecimal("100"), BigDecimal.ZERO);
}
BigDecimal feeFor(BigDecimal total) {
Map.Entry<BigDecimal, BigDecimal> tier = tiers.floorEntry(total);
if (tier == null) {
throw new IllegalArgumentException("Order total cannot be negative: " + total);
}
return tier.getValue();
}
}
ShippingFees fees = new ShippingFees();
fees.feeFor(new BigDecimal("0")); // 7
fees.feeFor(new BigDecimal("49.99")); // 7: floor key is 0
fees.feeFor(new BigDecimal("50.00")); // 4: floor key is 50, an exact match counts
fees.feeFor(new BigDecimal("99.99")); // 4
fees.feeFor(new BigDecimal("250")); // 0: floor key is 100
fees.feeFor(new BigDecimal("-5")); // IllegalArgumentException
How floorEntry picks a tier
Order totalfloorEntry keyFee
49.9907
50.00504
73.20504
1001000
-5null (no key <= -5)error
floorEntry returns the greatest key that is less than or equal to the total.

Notice that we never write the upper bound of any tier. The tier from 0 ends where the next tier begins, so there is no risk of a gap between 49.99 and 50, and no risk of two tiers overlapping. Adding a new tier, say 3 for totals from 75, is one more put() call and nothing else changes.

3Handling the Null Result

floorEntry returns null when no key is less than or equal to the argument. With our tiers, that happens only for negative totals. If we wrote tiers.floorEntry(total).getValue() in one line, a negative total would end in a NullPointerException with no useful message.

So we decide what a total below the first tier means. For shipping, a negative order total is a bug upstream, so throwing an IllegalArgumentException with the value in the message is right. In other domains, a default makes more sense, and Optional.ofNullable(tiers.floorEntry(total)).map(Map.Entry::getValue).orElse(defaultFee) expresses that. The important thing is to choose on purpose rather than let a null slip through.

4Why the Lookup Is O(log n)

TreeMap is implemented as a red-black tree, a binary search tree that rebalances itself on every insert and remove so that its height stays proportional to log n. To find a floor, TreeMap starts at the root, goes left when the key is larger than the node and right when it is smaller, and remembers the best candidate it has passed. It reaches a leaf after about log2(n) steps.

So floorEntry, ceilingEntry, lowerEntry and higherEntry all cost O(log n), as do put, get and remove. With three tiers this hardly matters, but the same code works for a rate card of 10,000 bands with about 14 comparisons per lookup, while a chain of if statements would compare against each band in turn.

5The BigDecimal Scale Surprise

BigDecimal stores a number as an unscaled value and a scale, the number of digits after the decimal point. So 50.0 has scale 1 and 50.00 has scale 2. BigDecimal.equals compares both value and scale, so it says they are different. BigDecimal.compareTo compares only the numeric value, so it says they are the same.

Java
BigDecimal a = new BigDecimal("50.0");
BigDecimal b = new BigDecimal("50.00");
a.equals(b); // false: scale 1 versus scale 2
a.compareTo(b); // 0: same numeric value
Map<BigDecimal, String> hash = new HashMap<>();
hash.put(a, "x");
hash.get(b); // null: HashMap uses equals and hashCode
Map<BigDecimal, String> tree = new TreeMap<>();
tree.put(a, "x");
tree.get(b); // x: TreeMap uses compareTo

TreeMap never calls equals on its keys. It only compares them, so for a TreeMap two BigDecimals with the same value are the same key. That is what we want for money tiers, and it is one more reason TreeMap fits this problem. A HashMap keyed by BigDecimal amounts is a common source of missed lookups, because an amount read from a database column with two decimal places and a literal typed as 50 are not equal. If we ever need a hash-based map of amounts, we normalise the keys first, for example with stripTrailingZeros() or setScale(2).

6Follow-up questions

How would you get all tiers between two amounts?

NavigableMap gives range views. tiers.subMap(from, true, to, true) returns a live view of the entries whose keys lie between from and to, with the two booleans saying whether each end is included. For tiers, we usually also want the tier that contains the lower amount, whose key may be below from, so we start the view at tiers.floorKey(from) instead. headMap(to, inclusive) and tailMap(from, inclusive) give the open-ended versions. These views cost O(log n) to create and then iterate in key order.

Why not use a HashMap with every possible total as a key?

Totals are continuous, so there are far too many possible values to enumerate, and the map would not be able to answer a question about a value it was never given. A HashMap only answers exact-match questions. A TreeMap answers which key is nearest below or above, which is what a range lookup needs.

Is the TreeMap safe to share between threads?

TreeMap is not thread-safe for writes. If we build it once in the constructor and never change it afterwards, concurrent reads are fine as long as the object is safely published, for example through a final field. If the tiers change at runtime, the simple approach is to build a new map and swap a volatile reference, or to use ConcurrentSkipListMap, which offers the same NavigableMap methods.

7Conclusion

In this answer, we saw that a TreeMap keyed by the lower bound of each tier turns a range lookup into one call, floorEntry(total), which returns the greatest key less than or equal to the total. We handled the null that floorEntry returns below the first tier, saw that TreeMap's red-black tree makes every neighbour lookup O(log n), and saw that TreeMap compares BigDecimal keys with compareTo, so 50.0 and 50.00 are the same key there, unlike in a HashMap.

What to say in the interviewAbout 80 seconds aloud

Open with

I would store each tier under its lower bound in a TreeMap of BigDecimal to BigDecimal: put zero to seven, fifty to four, and one hundred to zero.

Then, if they want more

Then the lookup is just floorEntry of the total, followed by getValue. floorEntry is a NavigableMap method that returns the entry with the greatest key less than or equal to the argument, so a total of 73.20 gets the tier that starts at fifty, and an exact 50 counts as the fifty tier.

The nice part is that I only write lower bounds, so there are no gaps or overlaps, and adding a tier is one put. floorEntry returns null when the total is below the smallest key, which here means a negative total, so I check for null and throw an IllegalArgumentException rather than letting a NullPointerException happen.

TreeMap is a red-black tree, so floorEntry, ceilingEntry, lowerEntry and higherEntry are all O(log n). One detail I would mention is BigDecimal scale: TreeMap compares keys with compareTo, which ignores scale, so 50.0 and 50.00 are the same key. A HashMap uses equals, which includes scale, so the same lookup would miss there.

For a range of tiers, I would use subMap starting from floorKey of the lower amount.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Shipping fees depend on order total: 0 to 49.99 costs 7, 50 to 99.99 costs 4, 100 and...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/2ab7ffa88a/