Why interviewers ask this
It tests data structure choice and complexity awareness.
How to approach it
Start with the simple nested loop, then improve using a set or hash map and explain the trade-off.
Example answer
A brute force approach compares every pair in quadratic time. Better, I walk through the array once while storing seen values in a set and record any value already present, which runs in linear time.
What a weak answer sounds like
I would use two loops and compare every pair.
It is vague, has no example and gives the interviewer nothing to remember.
A simple structure for your answer
- Start with the brute force idea
- Explain why it is slow
- Improve using a set or hash map
- Compare time and memory
Freshers and experienced candidates
Freshers can reach the hash set solution with hints; experienced candidates should discuss sorted input and memory limits.
Common mistake
Stopping at the brute force solution.
Self-check before the interview
Did you state complexity for both approaches?
Follow-up questions to expect
- Can you make it faster?
- What is the space trade-off?
- How would you do it for a sorted array?
How to practise
Practise saying the brute force first, then improving it. Interviewers value the thinking process.
Use this as a pattern, not a script. Answer in your own words with your own examples.