Algos Flashcards

1
Q

Backtracking

A

Incrementally build candidates for a solution. Abandon a candidate (backtrack) as soon it becomes clear it won’t work.

2
Q

What are the hallmarks of a backtracking problem

A

n combinations of n things
when you need to build up a solution gradually
when the solution space is so vast that it can’t be done in loops

sums can be any possible length [3], [1,2], [1,1,1]
3-sum and 2-sum don’t use backtracking because the combinations are fixed in length (3 and 2)

3
Q

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may not use the same element twice.

A

If the list is unsorted:

• If you need to return the numbers, you can use a set.
• If you need to return the indices, use a hashmap.

If the list is sorted:
- Use two pointers from opposite sides.

4
Q

Three Sum

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

A

Sort the list to avoid duplicates and so it’s possible to exit early.
Pin the first number and do a loop.
Call two sum (using pointers because the list is sorted) within the outer loop.
If the number in the outer loop is greater than the target, exit early.
Only want to do the outer loop if the next number in the list, is different than the number from the previous iteration but be careful you don’t hit an array out of bounds errors the first time through when i - 1 would be -1.

5
Q

Combination Sum or N Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]

A

The clue here that this can’t be done with loops is that the combinations can be 1..n in length.

When you see n combinations of n things, think backtracking. Try to organize the inputs into a tree then use DFS.