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 True
7 return False

The corrected version appears here once you have revealed everything below.

Your task

  1. Explain why n = 10⁵ times out: how many pair checks are made?
  2. Identify the redundant work: for a fixed nums[i], what single question are we asking about the rest of the array?
  3. Give an O(n) solution and an O(n log n) O(1)-extra-space solution.
  4. Discuss: which one returns indices easily, which one handles duplicates and the x + x == target case, 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.

0/6

Related concepts