Lesson 3.3
Read the constraints
6 min · 7 steps
Step 1 of 7 · Explanation
Constraints quietly tell you how fast your solution must be. Use a budget of about 10⁸ simple steps per second, then look at the limit on
n.n ≤ 10³: O(n²) is fine, about 10⁶ steps.n ≤ 10⁵: you need O(n) or O(n log n).n ≤ 10⁹: even one loop is too slow. Find a formula, or O(log n).
Step 2 of 7 · Pick the approach
"Return how many pairs add up to
target." Constraints:2 ≤ nums.length ≤ 1000.
Is brute force over every pair enough?- Yes, about 5 × 10⁵ checks, well under budget
- No, nested loops are always too slow
- No, you must use a hash map to be safe
Step 3 of 7 · Pick the approach
"Return how many pairs add up to
target." Constraints:2 ≤ nums.length ≤ 10⁵.
What do you do?- Find an O(n) or O(n log n) way, like a hash map or sorting first
- Still brute force, but stop early when you find one
- Brute force with
j = i + 1to halve it
Step 4 of 7 · Pick the approach
"Return 1 + 2 + ... + n." Constraints:
1 ≤ n ≤ 10⁹. What's the right choice?- The formula
n * (n + 1) / 2, one step - A loop from 1 to
n - Store every number in an array, then add them up
- The formula
Step 5 of 7 · Predict the result
What does it return for
n = 100?function solution(n) { return n * (n + 1) / 2}5050101005000
Step 6 of 7 · Find the bug
"Return the largest number, or 0 if the array is empty." Constraints:
0 ≤ nums.length ≤ 10⁵.
For[], this code returnsundefined. Tap the wrong line.function solution(nums) { let best = nums[0] for (let i = 1; i < nums.length; i++) { if (nums[i] > best) best = nums[i] } return best}Step 7 of 7 · Recap
- Budget about 10⁸ steps per second. Compare that with your solution's step count.
n ≤ 10³allows O(n²).n ≤ 10⁵needs O(n log n) or O(n).n ≤ 10⁹needs a formula or O(log n).- The lower bound matters too.
0 ≤ lengthmeans the empty array will be tested.