InterviewCake Flashcards
What is the greedy approach
An algorithm that builds up a solution by choosing the option that looks the best at every step.
Simple greedy example
Say you’re a cashier and need to give someone 67 cents (US) using as few coins as possible. How would you do it?
Whenever picking which coin to use, you’d take the highest-value coin you could. A quarter, another quarter, then a dime, a nickel, and finally two pennies. That’s a greedy algorithm, because you’re always greedily choosing the coin that covers the biggest portion of the remaining amount.
Other greedy examples
Looking for a minimum spanning tree in a graph? At each step, greedily pick the cheapest edge that reaches a new vertex.
Trying to fit as many overlapping meetings as possible in a conference room? At each step, schedule the meeting that ends earliest.
Binary Search
Start in the middle: is it bigger or smaller than the target. Repeat until the target is found. Only works with an ordered list
Triangular series
A series of numbers where each number could be the row of an equilateral triangle. Always starts with 1 and increases by 1 with each number. Pairs of numbers on each side will always add up to the same value (1 mores than the series’s n.)
Total Sum of triangular series
(n^2 + n)/2 1+2+3 = 6 (9 + 3)/2 = 6
Memoization
ensures that a function doesn’t run for the same inputs more than once by keeping a record of the results for the given inputs (usually in an object).
Bottom up
a bottom-up algorithm “starts from the beginning,” while a recursive algorithm often “starts from the end and works backwards.”
Filter
var words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];
const result = words.filter(word => word.length > 6);
console.log(result); // expected output: Array ["exuberant", "destruction", "present"]