Optimization challengeBeginner
Quadratic pair search
Scenario
This function finds whether any two distinct elements of nums add up to target. It times out for n = 10⁵. Make it fast enough, and discuss the trade-offs of the two standard approaches.
Broken
1def has_pair(nums, target):2 n = len(nums)3 for i in range(n):4 for j in range(i + 1, n):5 if nums[i] + nums[j] == target:6 return True7 return FalseThe corrected version appears here once you have revealed everything below.
Your task
- Explain why
n = 10⁵times out: how many pair checks are made? - Identify the redundant work: for a fixed
nums[i], what single question are we asking about the rest of the array? - Give an
O(n)solution and anO(n log n)O(1)-extra-space solution. - Discuss: which one returns indices easily, which one handles duplicates and the
x + x == targetcase, which works on a stream?
OptimizationComplexity AnalysisPattern Recognition
Work it out
Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.
Reveal
Progressive — each section builds on the previous one.
The bottleneck
Key observation
The fix
Edge cases
Complexity
What this tests
Self-check
Tick what your analysis covered. Be honest — this feeds your readiness profile.