Skip to content
Brute force first

Lesson 3.1

Try every pair

6 min · 7 steps

  1. 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. i runs from the start, j starts at i + 1. That way each pair is checked exactly once, and no item is paired with itself.

  2. Step 2 of 7 · Predict the result

    How many times does checks++ run for n = 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}
    1. 6
    2. 16
    3. 12
    4. 4
  3. Step 3 of 7 · Predict the result

    Here j starts at 0, not i + 1. What does it return for [1, 4, 2, 3] and target 5?

    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}
    1. 4
    2. 2
    3. 6
  4. Step 4 of 7 · Find the bug

    Problem "Return true if two different items add up to target." For [3, 5] and target 6, this code returns true. 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}
  5. 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++) {}
  6. Step 6 of 7 · Write the code

    solution(nums)

    Return how many pairs (i, j) have i < j and nums[i] > nums[j].
    Constraints: 0 ≤ nums.length ≤ 100.

    function solution(nums) {  // [3, 1, 2] -> 2: (3, 1), (3, 2) }
  7. Step 7 of 7 · Recap

    • Brute force first. A slow right answer beats a fast wrong one.
    • For pairs, j starts at i + 1. Each pair once, and no item paired with itself.
    • j from 0 counts each pair twice and pairs items with themselves.

    Pattern card

    Every pair
    When to use it: When a problem asks about two items and the input is small. It's also the reference to check a faster solution against.
    for (let i = 0; i < n; i++) {  for (let j = i + 1; j < n; j++) {    // cek / check (nums[i], nums[j])  }}