Lesson 3.1
Try every pair
6 min · 7 steps
Step 1 of 7 · Explanation
Brute force means: list every candidate, then check each one. Speed is a later problem. First the answer has to be right.
For pairs, use two loops.
iruns from the start,jstarts ati + 1. That way each pair is checked exactly once, and no item is paired with itself.Step 2 of 7 · Predict the result
How many times does
checks++run forn = 4?function solution(n) { let checks = 0 for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { checks++ } } return checks}616124
Step 3 of 7 · Predict the result
Here
jstarts at 0, noti + 1. What does it return for[1, 4, 2, 3]and target5?function solution(nums, target) { let count = 0 for (let i = 0; i < nums.length; i++) { for (let j = 0; j < nums.length; j++) { if (nums[i] + nums[j] === target) count++ } } return count}426
Step 4 of 7 · Find the bug
Problem "Return true if two different items add up to
target." For[3, 5]and target6, this code returnstrue. Tap the wrong line.function solution(nums, target) { for (let i = 0; i < nums.length; i++) { for (let j = i; j < nums.length; j++) { if (nums[i] + nums[j] === target) return true } } return false}Step 5 of 7 · Arrange the code
Build a function that returns the largest sum of two different items. Two lines don't belong.
for (let j = 0; j < nums.length; j++) {}function solution(nums) {best = Math.max(best, nums[i] + nums[j])}for (let j = i + 1; j < nums.length; j++) {return bestlet best = -Infinitylet best = 0for (let i = 0; i < nums.length; i++) {}Step 6 of 7 · Write the code
solution(nums)Return how many pairs
(i, j)havei < jandnums[i] > nums[j].
Constraints:0 ≤ nums.length ≤ 100.function solution(nums) { // [3, 1, 2] -> 2: (3, 1), (3, 2) }Step 7 of 7 · Recap
- Brute force first. A slow right answer beats a fast wrong one.
- For pairs,
jstarts ati + 1. Each pair once, and no item paired with itself. jfrom 0 counts each pair twice and pairs items with themselves.