---
title: "Greedy algorithm problems, worked"
url: "https://georgeliinternships.com/interview-prep/coding/greedy-algorithms.md"
canonical_url: "https://georgeliinternships.com/interview-prep/coding/greedy-algorithms"
last_updated: "2026-12-01"
type: "guide"
summary: "Greedy algorithms for coding interviews: how they work, how they compare with other methods, a complexity cheat sheet, problems by level and four checked ones."
related: ["https://georgeliinternships.com/interview-prep.md", "https://georgeliinternships.com/methodology.md", "https://georgeliinternships.com/roles.md"]
---

# Greedy algorithms in coding interviews: how they work and problems by difficulty

> **For AI agents:** the complete index of George Li Internships pages is [llms.txt](https://georgeliinternships.com/llms.txt). Every page is also served as markdown at its URL plus .md.

Greedy algorithms for coding interviews: how they work, how they compare with other methods, a complexity cheat sheet, problems by level and four checked ones.

Greedy algorithms solve optimization problems by picking the strongest immediate option at every step instead of exploring every path. Because they are fast to code and built on clear heuristics, interviewers test them in phone screens and onsite rounds, though a greedy rule is not certain to find the global optimum unless the problem supports it.

## How greedy algorithms work

When you face an optimization prompt, a greedy algorithm breaks the work into sequential choices and locks in the best local option at each stage without looking back. That simplicity keeps code concise and fast, provided the problem satisfies two structural conditions.

- Optimal substructure: You can build the overall best solution from the best solutions to smaller remaining subproblems.
- Greedy choice property: Picking the strongest local choice leads directly to a globally optimal solution without weighing future tradeoffs first.

Activity scheduling illustrates both properties. Suppose you have tasks with start and end times and want to fit the most non-overlapping tasks into one day. Choosing the task that ends earliest, such as Activity A finishing at 9:30 AM, narrows the open window to 9:30 AM through 2:00 PM. Conflicting tasks like Activity B drop out, leaving Activity C as the next earliest finisher and yielding two completed tasks.

Your heuristic makes or breaks the result. If you instead pick the shortest-duration task first when that short task straddles two longer ones, it blocks both neighbors and leaves only one task instead of two. Greedy methods can therefore return suboptimal outputs whenever a rule violates the greedy choice property, and proving correctness requires proving that property holds.

### Common use cases in computer science

Greedy rules show up across standard interview and systems problems:

- Activity and interval scheduling
- Shortest and longest path routing
- Decision tree split selection
- Huffman prefix coding
- Minimum spanning trees
- Fractional knapsack allocation
- Operating system job scheduling
- Traveling salesperson heuristics
- K-center clustering
- Graph vertex coloring

### Walking through an implementation

A greedy implementation resembles depth-first search except that it expands only the single best branch at each step instead of exploring every child node.

1. Define a task object with a comparator that orders tasks by finish time.
2. Copy the input list before sorting so you do not mutate the caller’s data, then sort earliest-finish first.
3. Initialize a result list and loop once through the sorted candidates, adding each task whose start is not before the previous end time.

Because the loop visits each element once, the selection pass takes O(n) time plus the sorting cost.

## Comparing greedy algorithms with other paradigms

Knowing how greedy methods compare to neighboring techniques helps you justify your design when an interviewer probes alternatives.

| Paradigm | Structural requirement | Revisits past choices | Speed and memory tradeoff |
| --- | --- | --- | --- |
| Greedy | Optimal substructure and greedy choice property | No, commits permanently at each step | Fast O(n) or O(n log n) runtime with minimal memory |
| Brute force | None, checks every valid combination | Enumerates all subsets or permutations | Often O(n!) on scheduling tasks |
| Divide and conquer | Optimal substructure across splits | Merges solved subproblems upward | More complex control flow than single-choice greedy steps |
| Dynamic programming | Optimal substructure across overlapping states | Evaluates every subproblem transition | Uses more memory, easier to prove optimal, can return all optimal answers |
| Backtracking | State constraint satisfaction | Yes, rewinds at every dead end | Corrects bad branches at exponential worst-case cost |
*How greedy algorithms compare against alternative paradigms*

> **When to pick greedy.** Use a greedy rule when you can prove it yields the best answer, or when speed and simplicity matter and a strong approximation suffices. Switch to dynamic programming or backtracking as soon as a small counterexample breaks your local rule.

## Complexity cheat sheet and supporting data structures

Do not simply memorize Big-O tables. Be ready to connect runtime and memory costs to the sorting step or priority queue powering your local selection.

| Algorithm | Time complexity | Space complexity | Supporting structure |
| --- | --- | --- | --- |
| Activity selection | O(n log n) | O(n) | Sorted list copy |
| Huffman encoding | O(n log n) | O(|S|) for |S| unique symbols | Min-heap |
| Prim’s MST | O((|V| + |E|) log |V|) | O(|V|) for |V| vertices | Min-heap |
*Complexity summary for standard greedy algorithms*

### Time complexity patterns

Most greedy solutions run in O(n log n) time, either by sorting the input once before a linear scan or by calling O(log n) heap operations inside an n-step loop.

Huffman coding puts symbol weights into a min-heap to derive binary prefix codes. Processing n symbols while updating the heap at O(log n) per step gives O(n log n) time. Prim’s algorithm finds a minimum spanning tree (MST) by keeping candidate vertices in a min-heap at O(log |V|) per insert, update, or pop while scanning incident edges O(|E|) and pushing unvisited vertices O(|V|), totaling O((|V| + |E|) log |V|) time.

### Space complexity patterns

Copying an input array of size n and holding up to n outputs takes O(n) extra space, matching the linear memory needed for an auxiliary heap or sorted list. In Huffman coding over |S| distinct symbols, all unique symbols form |S| leaves and up to 2|S| minus 1 heap nodes for O(|S|) space. In Prim’s algorithm, the finished tree holds |V| vertices and the heap holds at most |V| minus 1 entries at peak expansion, requiring O(|V|) space.

### Sorting algorithms and heaps

Sorting algorithms expose the local optimum in O(n log n) average time, though poor pivot selection in Quicksort can degrade sorting to O(n^2). When candidates change dynamically mid-pass, binary heaps support O(log n) updates inside a loop, giving the same O(n log n) overall bound as upfront sorting.

## Five classic greedy interview prompts

These five prompts capture the most frequent greedy patterns across software engineering interviews:

1. Bursting horizontal targets: Given target intervals [start, end], find the fewest vertical shots needed to pierce every interval. Sort by right edge and shoot at each unpierced end.
2. Jump reachability: Given maximum step sizes at each array position starting from index zero, determine whether you can arrive at the final slot. Track the farthest reachable index in one pass.
3. Shortest combined superstring: Given words, find a minimum-length string holding every word as a contiguous slice. Greedily merge maximum suffix-prefix overlaps or solve small inputs exactly.
4. Circular fuel circuit: Given station fuel supply and hop cost arrays around a loop, return the valid starting station index or -1. Reset your candidate start whenever running fuel drops below zero.
5. Maximum non-conflicting sessions: Given start and finish times for n tasks, pick the largest conflict-free set for one worker. Sort earliest-finish first and accept compatible tasks.

## Warmup greedy problems for phone screens

These seven introductory questions frequently show up in early phone screens where you explain your approach aloud or code without complex helpers:

1. Assigning cookies: Sort child greed factors and cookie sizes ascending, then give each child the smallest cookie that satisfies them.
2. Planting non-adjacent flowers: Scan a binary garden array left to right and plant whenever an empty slot has empty left and right neighbors.
3. Making lemonade change: Track 5 and 10 bills from drink sales and hand back 10 plus 5 before three 5s when breaking a 20.
4. Three-way equal-sum array split: Verify the array sum divides by three, then cut greedily at one-third and two-thirds running totals.
5. Splitting balanced strings: Walk an L/R string with a balance counter and increment the split count every time balance hits zero.
6. Maximizing truck units: Sort box types descending by units per box and load full counts until reaching the truck’s box limit.
7. Clearing X characters in moves: Scan left to right; at each X, apply a three-character clear to O and advance your index by three.

## Core medium greedy problems for coding rounds

Video screens and onsite rounds rely heavily on medium-level problems where you write full code and defend your greedy invariant. Grouping these 30 problems by mechanism makes practice structured.

### Intervals, scheduling, and reachability

1. Jump reachability check: Maintain the farthest index reachable as you iterate left to right and stop if you hit an unreachable spot.
2. Minimum jump count: Expand BFS-like reachability windows in one linear pass, incrementing jumps whenever you reach the current window edge.
3. Circular fuel station loop: Check total supply covers total cost, then reset your start index whenever cumulative gas turns negative.
4. Removing overlapping intervals: Sort intervals by end point and drop any subsequent interval whose start overlaps the kept end.
5. Minimum arrows for overlapping balloons: Sort spans by right endpoint and count how many non-overlapping shots cover all targets.
6. Task cooldown scheduling: Prioritize the highest-frequency remaining tasks in each cooldown cycle using counts or a max-heap.
7. Longest non-overlapping pair chain: Sort pairs by their second coordinate and greedily attach every pair starting strictly higher.
8. Label partitioning on strings: Track each letter’s last index and cut a partition once your scan reaches the current window’s max last index.

### Monotonic stacks and lexicographic ordering

1. Deduplicating letters lexicographically: Use a monotonic stack and last-seen positions to pop larger characters that appear again later.
2. Removing K digits for minimum value: Pop preceding digits larger than the current digit from a stack while removals remain.
3. Single swap for maximum number: Swap the leftmost digit having a larger trailing digit with the rightmost occurrence of that max digit.
4. Monotone increasing digits: Find the first decreasing adjacent pair, decrement the left digit, and set all trailing digits to 9.
5. Rebuilding a queue by height: Sort tallest people first (tie-break by smaller ahead-count) and insert each person at their ahead-count index.
6. Deleting columns for lexicographic row order: Scan columns left to right, dropping any column that breaks an unresolved row pair’s order.
7. Building strings without triple repeats: Emit two copies of the more common letter followed by one of the scarcer letter until balanced.

### Sorting, two pointers, and pairing

1. Two-person rescue boats: Sort weights and use two pointers to pair the heaviest person with the lightest whenever capacity allows.
2. Advantage card shuffle: Sort both arrays; beat B’s largest value with A’s largest if possible, otherwise sacrifice A’s smallest value.
3. Bag of tokens score maximization: Buy points with power using the cheapest token, or sell one point for the largest power token.
4. Array of doubled pairs: Sort numbers by absolute value and match each smaller magnitude x with its remaining 2x partner.
5. Minimum increments for unique elements: Sort the array and raise each element to at least one above the prior assigned value.
6. Shrinking range after K shifts: Sort values and test shifting left elements by +K and right elements by -K at every split.
7. Grouping cards into straights: Sort distinct card values and greedily subtract W-length consecutive runs starting from the lowest key.
8. Splitting into consecutive runs: Append each sorted integer to an existing length-3+ sequence ending at x minus 1 before starting a new triplet.

### Sequences, grids, and balancing

1. Wiggle alternating subsequence: Count sign reversals between adjacent differences, ignoring zero-difference flat segments.
2. Increasing triplet subsequence: Track the lowest first value and lowest valid second value; finding a third larger value returns true.
3. Dota2 senate round simulation: Maintain two index queues for each faction so earlier voters ban opponents and re-queue with offset n.
4. Reorganizing string without repeats: Pull the most frequent character from a max-heap and park it one turn before re-inserting.
5. Raising buildings under skyline limits: Cap every grid cell at the minimum of its row maximum and column maximum.
6. Score after flipping matrix: Flip rows starting with 0 to 1, then flip any column where zeros outnumber ones.
7. Minimum insertions to balance parentheses: Track unmatched opening brackets and count stray closing brackets needing an opener.

## Hard greedy problems for senior and onsite rounds

Extended onsite rounds use hard greedy prompts that pair local rules with two-pass scans, heaps, or backward reconstruction:

1. Neighbor candy distribution: Sweep left-to-right for rising ratings, then right-to-left for falling ratings, keeping the max at each child.
2. Maximum k-digit merge: Extract optimal single-array subsequences via monotonic stacks across valid split lengths and merge lexicographically.
3. Patching reachable sums to N: Maintain the smallest missing sum; double covered range by adding miss whenever the next coin exceeds it.
4. Smallest range across K lists: Advance the minimum pointer in a K-element min-heap while tracking the current maximum element.
5. Lowest-cost K workers: Sort by wage-to-quality ratio and keep a max-heap of the K smallest quality scores seen so far.
6. Maximizing capital across K projects: Unlock affordable projects into a profit max-heap and always pick the highest profit.
7. Hitting every interval twice: Sort intervals by right endpoint ascending and add rightmost points whenever fewer than two chosen points lie inside.
8. Maximizing courses before deadlines: Sort by deadline and swap out the longest prior course from a max-heap whenever total time overflows.
9. Minimum swaps for seated pairs: Walk seats in pairs and swap each mismatched partner directly into the adjacent seat using a position map.
10. Fewest highway refueling stops: Push passed station fuel into a max-heap and pop the largest tank whenever fuel hits zero.
11. Longest chunked palindrome split: Match the shortest equal prefix and suffix from both ends inward to maximize symmetric chunks.
12. Reverse-stamping a target string: Work backward from the target by turning matched stamp windows into wildcards until blank.
13. Minimum garden watering taps: Map each tap to interval [i - r, i + r] and greedily cover [0, n] using farthest-reach jumps.

## Four practice problems, in order of difficulty

These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from the most events to a case where the greedy rule loses.

**Problem 1.** Nine events have start times 1, 3, 0, 5, 8, 5, 12, 2, 9 and end times 4, 5, 6, 7, 9, 10, 14, 13, 11, in the same order. An event occupies its start up to but not including its end, so an event that ends at 9 and one that starts at 9 do not clash. What is the most events that can be attended with no two clashing? Give an integer.

**Answer:** 5

1. Sort the events by end time. Take the first one, then repeatedly take the next event whose start is at or after the end of the last one taken.
2. Sorted by end: (1, 4), (3, 5), (0, 6), (5, 7), (8, 9), (5, 10), (9, 11), (2, 13), (12, 14).
3. Take (1, 4). (3, 5) and (0, 6) start before 4, so skip them. Take (5, 7). Take (8, 9). (5, 10) starts before 9, so skip it. Take (9, 11). (2, 13) is skipped. Take (12, 14).
4. That is 5 events. Choosing the earliest end leaves the most room for what follows, which is why this rule is correct. Choosing the earliest start, or the shortest event, can go wrong. The sort costs O(n log n).

**Problem 2.** Eight closed intervals have starts 1, 2, 4, 6, 7, 10, 11, 15 and ends 5, 4, 7, 9, 12, 13, 16, 19, in the same order. A point touches an interval if it lies in it, including at an endpoint. What is the fewest points that touch every interval? Give an integer.

**Answer:** 4

1. Sort the intervals by end. Place a point at the end of the first interval, since the earliest end is the furthest right a point can go while still touching it. Then skip every interval that point touches, and repeat with the next interval left.
2. Sorted by end: (2, 4), (1, 5), (4, 7), (6, 9), (7, 12), (10, 13), (11, 16), (15, 19).
3. Place a point at 4. It touches (2, 4), (1, 5) and (4, 7). The next untouched interval is (6, 9), so place a point at 9, which also touches (7, 12). The next is (10, 13), so place a point at 13, which also touches (11, 16). The next is (15, 19), so place a point at 19.
4. That is 4 points: 4, 9, 13 and 19. The sort dominates, so the cost is O(n log n).

**Problem 3.** A row of 13 cells is numbered 0 to 12. A token on cell i can jump forward by any number of cells from 1 up to r(i). The values r(0) to r(12) are 2, 3, 1, 1, 4, 2, 1, 5, 1, 2, 1, 1, 3. What is the fewest jumps to get from cell 0 to cell 12? Give an integer.

**Answer:** 4

1. Think in layers. After 1 jump you can be on any cell up to the furthest reach so far. The next jump starts from any cell in the current layer and reaches as far as the best of them can.
2. Layer 1 is cells 1 to 2, since r(0) = 2. The furthest from cells 1 and 2 is 1 + 3 = 4, so layer 2 is cells 3 to 4. The furthest from cells 3 and 4 is 4 + 4 = 8, so layer 3 is cells 5 to 8.
3. The furthest from cells 5 to 8 is 7 + 5 = 12, so layer 4 reaches cell 12.
4. It takes 4 jumps. One pass tracking the end of the current layer and the furthest reach is O(n), whereas trying every jump length from every cell is O(n^2).

**Problem 4.** Coins come in values 1, 3 and 4. The largest-coin-first method pays an amount by taking as many 4s as fit, then as many 3s, then 1s. For how many of the amounts from 1 to 20 does it use more coins than the fewest possible? Give an integer.

**Answer:** 4

1. Test the amount 6. Largest first gives 4, 1, 1, which is 3 coins. But 3 + 3 is 2 coins, so the rule is not optimal for 6.
2. The same happens for each amount that is 2 more than a multiple of 4 and at least 6: 6, 10, 14 and 18. For example 10 gives 4, 4, 1, 1 (4 coins) against 4, 3, 3 (3 coins).
3. Every other amount from 1 to 20 is paid with the fewest coins by the rule, so the answer is 4.
4. A rule that always takes the biggest piece is only right when a proof says so, as with the earliest-end rule for events. A single failing amount, here 6, is enough to rule the greedy choice out, and then a table of fewest coins per amount is the safe method.

Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read [how the problems are checked](https://georgeliinternships.com/methodology.md).

These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

## How to build a greedy interview prep plan

Memorizing all 50 answers fails as soon as an interviewer modifies a constraint. Use this list to train pattern recognition, counterexample testing, and clean implementation under time limits.

### Solo practice routine and core fundamentals

Make sure your broader coding foundation covers the supporting data structures and algorithms before drilling greedy variants. Interviewers expect fluency across these core building blocks as well as general problem-solving patterns:

- Arrays, sliding windows, and two-pointer scans
- Strings and character-frequency counting
- Linked lists and in-place pointer updates
- Stacks, queues, and monotonic structures
- Trees and graph traversals, including shortest paths and spanning trees
- Hash maps and sets for fast lookup
- Heaps and priority queues for dynamic ordering
- General algorithm patterns and Big-O complexity analysis

1. Replicate real whiteboard or shared-editor pressure by solving each prompt under a timer on paper or in a plain document without syntax hints, autocomplete, or outside notes.
2. Write down your greedy rule and test two small edge cases by hand before coding to make sure no counterexample breaks your assumption.
3. If you stall after time expires, read one reference solution to spot the missing invariant, then close it and solve the next prompt unassisted so you do not get trapped reading editorial after editorial.

### Practicing with peers or experienced engineers

Solo drills build pattern fluency, yet live interviews also test how you reason aloud, defend your complexity bounds, and respond cleanly when an interviewer introduces a new constraint. Run timed mock interviews with peers or experienced software engineers who have led technical hiring panels. Practice stating why your greedy choice works, walking through sorting or heap complexities, and tracing sample inputs line by line before finishing.

## Questions

### What is a greedy algorithm?

It is an algorithm that always takes the best immediate, or local, choice while building an answer, which is how the NIST dictionary defines it. It finds the best overall answer for some problems and a worse one for others.

### How do I know a greedy choice is correct?

Argue that any best answer can be changed to start with your greedy choice without getting worse. If you cannot make that argument, look for a small counterexample, and use dynamic programming when you find one.

### Is greedy faster than dynamic programming?

Usually, because it never weighs the alternatives, which is the reason the NIST dictionary gives. A greedy method often costs one sort plus one pass, O(n log n), where a table costs more.

## How a session helps

A session with George is a place to code a problem aloud and have the reasoning questioned: what the choice is, why it is safe and what input would break it. You write all the code yourself. Next, read the [data structures checklist](https://georgeliinternships.com/interview-prep/data-structures-checklist.md) and the [coding and complexity practice](https://georgeliinternships.com/interview-prep/coding-and-complexity-practice.md), and use the [coding prep schedule](https://georgeliinternships.com/tools/coding-prep-schedule.md) to put the topics on a calendar. See the [packages page](https://georgeliinternships.com/packages.md) for the sessions, or [book a session](https://georgeliinternships.com/book.md).

## Related

- [Internship interview prep](https://georgeliinternships.com/interview-prep.md)
- [Methodology and sources](https://georgeliinternships.com/methodology.md)
- [Internship role guides](https://georgeliinternships.com/roles.md)
