Bitpath

Boss lesson · Unit 03

Choose k

Groups where order does not matter

13 exercisesabout 3 min

What you practise

  • A start index prevents duplicates
  • Count subsets that hit a target sum

Try a question from this lesson

Pick one

You pick 2 pizza toppings out of 4. Ham then olives is the same pizza as olives then ham. How many different pizzas?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Never look backward

The boss problem: list every group of k items, each group once.

The trick is a start index. After picking item i, the recursive call may only pick from i + 1 onward. A group can then only be built in one order, left to right, so it appears once.

def teams(s, k, start, cur):
    if len(cur) == k:
        print(cur)
        return
    for i in range(start, len(s)):
        teams(s, k, i + 1, cur + s[i])

teams("abcd", 2, 0, "")
function teams(s, k, start, cur) {
  if (cur.length === k) {
    console.log(cur);
    return;
  }
  for (let i = start; i < s.length; i++) {
    teams(s, k, i + 1, cur + s[i]);
  }
}

teams("abcd", 2, 0, "");
function teams(
  s: string, k: number,
  start: number, cur: string,
): void {
  if (cur.length === k) {
    console.log(cur);
    return;
  }
  for (let i = start; i < s.length; i++) {
    teams(s, k, i + 1, cur + s[i]);
  }
}

teams("abcd", 2, 0, "");

Python noterange(start, len(s)) begins at start, so earlier letters are never offered again.

TypeScript noteFour parameters, four annotations. TypeScript rejects a call that passes them in the wrong order when the types differ.

Concept

Subsets that hit a target

Second half of the boss: how many subsets of a list of numbers add up to a target?

Walk the take-or-leave tree and carry t, the amount still needed. Taking a number subtracts it from t. At the end of the list, the subset counts only if t is exactly 0.

def count(nums, i, t):
    if i == len(nums):
        return 1 if t == 0 else 0
    take = count(nums, i + 1, t - nums[i])
    skip = count(nums, i + 1, t)
    return take + skip
function count(nums, i, t) {
  if (i === nums.length) {
    return t === 0 ? 1 : 0;
  }
  return (
    count(nums, i + 1, t - nums[i]) +
    count(nums, i + 1, t)
  );
}
function count(
  nums: number[], i: number, t: number,
): number {
  if (i === nums.length) {
    return t === 0 ? 1 : 0;
  }
  return (
    count(nums, i + 1, t - nums[i]) +
    count(nums, i + 1, t)
  );
}

Python note1 if t == 0 else 0 is a conditional expression: Python's version of t === 0 ? 1 : 0.

TypeScript noteThe return type : number is required: the function adds up its own results.

10 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy