All puzzles › Greedy Algorithms
Greedy Algorithms Practice Problems
42 puzzles (5 easy, 22 medium, 15 hard), 10 free, in Python, JavaScript and C++.
A greedy algorithm makes the choice that looks best right now and never revisits it. When that works it gives the shortest, fastest solutions there are. The hard part is not the code, it is knowing that the local choice really is safe, and being able to say why in a sentence.
How to spot a greedy algorithms problem
Greedy fits when taking the best available option can never leave you worse off later: the meeting that ends earliest, the largest coin that fits, the furthest reach from here. Sorting first is very often the opening move. If you can find a small input where the obvious choice loses, it is dynamic programming instead.
New to it? Read the lesson first: Greedy.
The puzzles, easiest first
- Best Time to Buy & Sell Stock (Easy): Given a list of daily prices, return the most money you can make by buying on one day and selling on a later day.
- Content Children (Easy): Given each child's minimum cookie size and the sizes of the cookies, return the most children you can make happy, one cookie each.
- Context Window Budget (Easy): Given the token count of each chat message, oldest first, and a token budget, return how many messages you can keep.
- Greedy Action (Easy): Given a list of action values, return the index of the best one.
- What Falls Off the End (Easy): Given the cache's keys in order of use, oldest first, and how many it can hold, return the keys that have to go, oldest first.
- Fill the Order, Cheapest First (Medium, free): A stock exchange keeps an order book of sell offers, each one a price and a number of shares, sorted from cheapest to dearest.
- How Many Layers Deep (Medium, free): A qubit loses its state within moments, so what matters about a quantum circuit is not how many gates it has but how many layers.
- Pay What the Next Bidder Offered (Medium, free): When you search, an auction decides which ads appear, and it finishes before the page loads.
- Save Up for a Burst (Medium, free): A token bucket allows short bursts while holding the long-run rate steady.
- Spread the Seeds (Medium, free): k-means gives bad clusters when its starting centers land close together.
- Try the Arm You Know Least About (Medium, free): A bandit algorithm has to choose between options it has tried a lot and options it has barely tried.
- Which Route Wins (Medium, free): The internet's routers often learn several routes to the same place, and BGP breaks the tie with a fixed list of rules.
- Beat the Deadlines (Medium): Given job deadlines, where each job takes one time slot and must finish by its deadline, return the most jobs you can finish.
- Burst Every Balloon (Medium): Given balloons as [start, end] spans on a line, return the fewest arrows to pop them all.
- Can You Reach the End? (Medium): Given an array where each value is the farthest you can jump from that spot, return true if you can get from the first index to the last.
- Fewest Coins (Medium): Given coin values from biggest to smallest and an amount, return how many coins the greedy approach uses, or -1 if it can't make the amount exactly.
- Fewest Jumps to the Flag (Medium): Platforms sit in a row and reach[i] is how many platforms ahead you can jump from platform i.
- Fewest Towers on the Lane (Medium): Enemies spawn at the given spots along a straight lane, in no particular order.
- Fit the Most In (Medium): Given a list of [start, end] events, return the most you can attend without any overlap.
- How Many Rooms? (Medium): Given meetings as [start, end], return the fewest rooms needed to hold them all.
- Load the Truck (Medium): Given box types as [count, unitsPerBox] and how many boxes the truck holds, return the most units you can load.
- Longest Zigzag (Medium): Given a list of numbers, return the length of the longest zigzag you can pick out of it, where the steps go up, down, up, down (or the other way).
- Making Change (Medium): Given a line of customers each paying 5, 10, or 20 for a 5 drink, and starting with no change, return true if you can give everyone the right change.
- Old Is Not the Same as Unused (Medium): Given when each entry was built, when it was last used, and how many can be kept, return the positions to evict, lowest first.
- Short Jobs First (Medium): Given how long each job takes, return the total time all jobs spend waiting if you always run the shortest job first.
- Two to a Boat (Medium): Given people's weights and a boat's weight limit, where a boat holds at most two people, return the fewest boats needed.
- Vary It, But Do Not Break It (Medium): Given piece sizes, a list of moves, and a max size, apply the moves and return the new sizes.
- One Box per Object (Hard, free): A detector proposes many overlapping boxes for the same object, and non-maximum suppression keeps the best one.
- Relevant, Not Repetitive (Hard, free): The five most relevant passages for a question are often the same paragraph five times.
- Stop Calling What Is Down (Hard, free): A service that keeps calling a broken dependency makes an outage worse.
- Biggest Number (Hard): Given a list of numbers, arrange them so that joining them together makes the biggest possible number, and return it as a string.
- Can Everyone Finish (Hard): Given how many units of a resource are free, what each process still needs, and what each one already holds, return true if every process can finish in some order.
- Cut the String (Hard): Given a string, cut it into as many pieces as you can so no letter shows up in more than one piece, and return the piece lengths.
- Fewest Jumps (Hard): Given an array where each value is the farthest you can jump from that spot, return the FEWEST jumps to reach the last index.
- First Hole That Fits (Hard): Given the sizes of free memory holes, in address order, and a list of requests, place each request in the FIRST hole big enough to hold it, and shrink that hole by the request.
- Handing Out Sweets (Hard): Given kids' ratings in a row, give each kid at least one candy, and give any kid rated higher than a neighbor more candy than that neighbor.
- Max Campaigns in Budget (Hard): Given campaign costs and a budget, return the most campaigns you can afford.
- Never Decreasing (Hard): Given n, return the biggest number no larger than n whose digits never go down from left to right.
- Round the Loop (Hard): Given the gas at each station around a loop and the cost to drive to the next one, return the station you can start from to make it all the way around, or -1.
- Shrink the Number (Hard): Given a number as a string and k, remove k digits to make the smallest possible number, with no leading zeros, and return it.
- Split the Loot (Hard): Given item weights, item values, and a capacity, return the most value you can carry when you can take part of an item, rounded to 2 decimals.
- Split the Trip (Hard): Given each person's cost to fly to city A or city B, send exactly half to each and return the smallest total.
Practice another pattern
Or browse by subject
Browse all 676 puzzles