Quick revision
The short answer
ArrayList.contains scans the list from the start, so it is O(n), and calling it once per line makes the whole loop O(n^2): 50 times more lines means about 2,500 times more work, which turns 20 ms into tens of seconds. Replacing the list with a LinkedHashSet keeps the first-seen order and makes each check O(1) on average, as long as Line has correct equals and hashCode. We catch this class of problem with tests on production-sized inputs, performance budgets in CI, request size limits, and profiles that show time piling up in ArrayList.indexOf.
What to remember
In this answer, we saw that ArrayList.contains is a linear scan, so calling it for every line makes deduplication O(n^2) and a 50 times larger input about 2,500 times slower. A LinkedHashSet, or stream().distinct(), makes it O(n) on average while keeping the first-seen order, provided Line has equals and hashCode that match the business meaning of a duplicate, which a record gives us. To catch this before production, we test with production-sized inputs, keep performance budgets in CI, limit request sizes and read profiles for time in ArrayList.indexOf.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
ArrayList.contains scans the list from the start, so it is O(n), and calling it once per line makes the whole loop O(n^2): 50 times more lines means about 2,500 times more work, which turns 20 ms into tens of seconds. Replacing the list with a LinkedHashSet keeps the first-seen order and makes each check O(1) on average, as long as Line has correct equals and hashCode. We catch this class of problem with tests on production-sized inputs, performance budgets in CI, request size limits, and profiles that show time piling up in ArrayList.indexOf.
Why this question is asked
This is one of the most common performance bugs in business code, because the code is correct, short and fast in every test that uses ten lines. It only shows its cost when a customer sends a big order. Interviewers ask it to see whether we can read growth from code, explain the numbers, choose the right fix and, at this level, prevent the next one. In this answer, we will explain why the time grows the way it does, check the numbers, fix it with a hash-based structure, make sure Line supports hashing, and then look at how to catch quadratic code before it reaches production.
1Why the Loop Is Quadratic
The loop looks like one pass over the lines, but it hides a second loop. ArrayList.contains(l) calls indexOf(l), which compares l with each element of result in turn using equals() until it finds a match or reaches the end. So each contains call costs time proportional to the current size of result.
If most lines are distinct, result grows to nearly n elements. The first line is compared with 0 elements, the second with 1, the third with 2, and so on, so the total number of comparisons is about 0 + 1 + ... + (n - 1), which is n(n - 1)/2. That grows with the square of n, which we write as O(n^2).
Notice that 50,000 squared divided by 1,000 squared is 2,500. So 50 times more data means about 2,500 times more work.
2Checking the Numbers Against the Measurements
If 1,000 lines took 20 ms and the time were all in the loop, 2,500 times more work would predict about 50 seconds. The measured 30 seconds is in the same range: part of the 20 ms at small sizes is fixed overhead such as parsing and serialising, and the per-comparison cost changes as the data grows and the JIT warms up. What matters is the shape. A linear algorithm would have gone from 20 ms to about 1 second; a quadratic one goes to tens of seconds. When a 50 times bigger input is 1,000 to 2,500 times slower, the code is almost certainly quadratic.
| Lines (n) | ArrayList.contains loop | LinkedHashSet |
|---|---|---|
| 1,000 | about 500,000 | about 1,000 hash lookups |
| 10,000 | about 50 million | about 10,000 |
| 50,000 | about 1.25 billion | about 50,000 |
| 500,000 | about 125 billion: hours | about 500,000: well under a second |
3The Fix: A Hash-Based Structure That Keeps Order
A HashSet answers contains in O(1) on average by hashing the element to a bucket instead of scanning. But the endpoint probably needs to return lines in the order they were first seen, and a plain HashSet does not keep any order. LinkedHashSet does: it is a HashSet that also links its entries in insertion order. And because add() returns false when the element is already present, the separate contains check disappears.
stream().distinct() gives the same result for a sequential stream. It keeps encounter order for ordered streams and tracks the elements it has already seen in a hash set internally, so it also relies on equals and hashCode. For a large input, pre-sizing helps a little: LinkedHashSet.newLinkedHashSet(lines.size()) on Java 19 and later avoids resizing on the way.
4Line Must Support Hashing
A hash set only works if two lines that are equal also have the same hash code. If Line overrides equals() but not hashCode(), two equal lines usually land in different buckets, the set never compares them, and duplicates survive. If Line overrides neither, equality is object identity and nothing is deduplicated unless the same object appears twice. The old ArrayList code only used equals(), so a class that worked with the old code can silently break with the new one.
Notice the second line. We must decide what "duplicate" means for the business, and make equals and hashCode match it. If two lines with prices 9.99 and 9.990 are the same line, we normalise the price with stripTrailingZeros() before building the Line, or deduplicate on a key such as the SKU and quantity. A record is the simplest way to get correct, consistent equals and hashCode.
5Catching Quadratic Code Before Production
The first defence is tests that use production-sized inputs. If the largest order we accept is 50,000 lines, at least one test or benchmark should run with 50,000 lines. A useful trick that avoids flaky absolute timings is a growth test: run the operation at n and at 10n, and fail if the time grows by much more than 10 to 20 times.
The second is performance budgets in CI: a small JMH or integration benchmark suite for hot endpoints, with a stated budget such as 200 ms for 50,000 lines, run on every merge to the main branch, so a regression shows up as a red build instead of an incident. The third is request size limits: rejecting orders above a documented maximum protects the service even when a slow path exists.
The fourth is profiling. If an endpoint is slow in production, a CPU profile from async-profiler or Java Flight Recorder shows where the time goes. Most of the time sitting in ArrayList.indexOf, or in equals() called from indexOf, is a strong hint of a quadratic scan; the same pattern with List.remove(Object) or String.indexOf inside a loop points to the same kind of bug. Code review checklists that ask "what is inside this loop?" catch many of these earlier still.
- Code reviewcontains,
indexOforremove(Object)inside a loop? - Growth testtime at 10n more than 20 times time at n?
- CI benchmarkover the 200 ms budget for the largest allowed input?
- Request size limitbounds the damage if a slow path slips through
- Production profiletime in
ArrayList.indexOf-> look for a scan inside a loop
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why not sort the lines and remove adjacent duplicates?
Sorting makes deduplication O(n log n), which is also fine for 50,000 lines, but it loses the original order and needs a Comparator that matches the business meaning of duplicate. A LinkedHashSet is simpler, O(n) on average and keeps the first-seen order, so it is usually the better choice unless the output must be sorted anyway.
What if Line is a JPA entity?
Then equals and hashCode need care, because a generated id changes when the entity is saved and Hibernate may hand us proxies. For deduplication of incoming request lines, it is cleaner to deduplicate the request DTOs, usually records, before mapping them to entities, or to deduplicate on an explicit business key.
How much memory does the LinkedHashSet add?
About 40 to 50 bytes per entry for the entry object and its links, plus the bucket array: around 2 to 3 MB for 50,000 lines. That is a small price for turning 30 seconds into a few milliseconds.
7Conclusion
In this answer, we saw that ArrayList.contains is a linear scan, so calling it for every line makes deduplication O(n^2) and a 50 times larger input about 2,500 times slower. A LinkedHashSet, or stream().distinct(), makes it O(n) on average while keeping the first-seen order, provided Line has equals and hashCode that match the business meaning of a duplicate, which a record gives us. To catch this before production, we test with production-sized inputs, keep performance budgets in CI, limit request sizes and read profiles for time in ArrayList.indexOf.
Open with
The loop is quadratic. contains on an ArrayList is a linear scan through indexOf, comparing with equals against every element collected so far, and we call it once per line, so the total is about n squared over two comparisons.
Then, if they want more
Going from 1,000 to 50,000 lines is 50 times more data and about 2,500 times more work, which matches 20 milliseconds turning into tens of seconds. The fix is a hash-based structure: new LinkedHashSet of the lines, then copy to a list, or lines.stream().distinct().
Both keep the first occurrence in its original order and make each check O(1) on average, so 50,000 lines take a few milliseconds. One thing I would check before shipping: Line must have equals and hashCode that agree with each other and with what the business calls a duplicate.
The old code only needed equals, so a missing hashCode would silently let duplicates through. A record is the easiest way to get that right. To catch this earlier, I would have a test or benchmark at the largest allowed input size, a growth check comparing n and 10n, a performance budget in CI, and a request size limit.
In production, a profile with time concentrated in ArrayList.indexOf is the classic sign of this bug.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 19
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 "An endpoint that deduplicates order lines runs in 20 ms for 1,000 lines but takes 30...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/8d4c879c01/