Programming basics · Scenario
Passes the samples, then Time Limit Exceeded
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Your solution to 'count the pairs whose sum equals k' passes the sample tests, but the hidden tests say 'Time Limit Exceeded'. The time limit is one second. Walk me through what you'd check and how you'd fix it.
Then
Follow-ups the interviewer asks next
- What's the first thing you look at?
- Your code has two nested loops, and n can be 2 lakh. How many steps is that?
- How would you make it faster, and what's the new complexity?
- Can reading the input be slow by itself? In which languages, and what's the fix?
- After your fix, one test now says Wrong Answer; the right answer is about 2 × 10^10. What went wrong?
- What do you do differently in the next test?
The answer
What a strong answer covers
- Read the constraints first: n up to 2 × 10^5. Nested loops check about n²/2 = 2 × 10^10 pairs, far more than the roughly 10^8 simple steps a second allows.
- Fix: one pass with a hash map of how many times each value has been seen. For each x, add
count[k - x]to the answer, then increasecount[x]. That's O(n) time and O(n) space. Sorting with two pointers, O(n log n), also works if duplicates are handled. - Slow input: Java's Scanner is slow for big inputs, so use BufferedReader; in C++ use
ios::sync_with_stdio(false); cin.tie(nullptr);and '\n' instead of endl; in Python use sys.stdin. - Wrong Answer: when every value is the same, the number of pairs is n(n − 1)/2, about 2 × 10^10, which doesn't fit in a 32-bit int (about 2.1 × 10^9 at most), so it wraps to a negative number. Use long (Java) or long long (C++).
- Next time: work out the step count from the constraints before coding, and test the largest and the all-same inputs.
The red pen
Common traps
Avoid:tuning the nested loop instead of changing the approach; "the judge's machine is slow"; switching language as the first fix.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.