How to Master Greedy Algorithms and Interval Problems in Tech Interviews
Greedy algorithm questions are a staple of technical interviews at every level. From entry-level coding screens to staff engineer deep dives, interviewers use greedy problems to test whether you can identify locally optimal choices that lead to globally optimal solutions. The tricky part is not the code itself—it is recognizing that a greedy approach works and proving why. With an AI Interview Copilot reinforcing your pattern recognition, you can walk into any coding round confident that you will spot the greedy signal immediately.
Why Greedy Algorithms Appear So Often in Interviews
Greedy algorithms are deceptively simple. The code is usually short, but the reasoning behind correctness is what separates strong candidates from average ones. Interviewers love greedy problems because they test three things simultaneously: pattern recognition (is greedy even applicable?), proof intuition (why does the local choice lead to a global optimum?), and edge case awareness (what happens when multiple elements tie or the input is empty?).
Unlike dynamic programming, which explores all subproblems, a greedy algorithm commits to one choice at each step and never looks back. This makes greedy solutions highly efficient—often O(n log n) due to sorting—but also fragile. A greedy approach that works for one variation of a problem may completely fail for a slight twist. That tension between simplicity and correctness is exactly what makes these questions powerful interview signals.
When Does Greedy Work?
Before diving into patterns, you need a mental framework for deciding when greedy is applicable. Two properties must hold:
Greedy Choice Property
A globally optimal solution can be arrived at by making a locally optimal choice at each step. You do not need to reconsider past decisions.
Optimal Substructure
After making the greedy choice, the remaining subproblem has the same structure as the original problem. The optimal solution to the subproblem, combined with the greedy choice, yields the optimal solution to the whole problem.
If both properties hold, greedy works. If either is missing, you likely need dynamic programming or another technique. In interviews, a quick way to test this is to construct a small counterexample. If you cannot find one after a few attempts, greedy is probably safe.
The Six Essential Greedy Patterns
Pattern 1: Interval Scheduling and Activity Selection
This is the most classic greedy pattern. Given a set of intervals (activities, meetings, tasks), select the maximum number of non-overlapping intervals.
The key insight: sort intervals by their end time, then greedily select the earliest-ending interval that does not overlap with the previously selected one.
Why sort by end time and not start time? Because choosing the interval that finishes earliest leaves the maximum room for subsequent intervals. Sorting by start time may cause you to pick a long interval that blocks many shorter ones.
Time complexity: O(n log n) for sorting, O(n) for the greedy scan.
Common variations:
- Maximum number of non-overlapping meetings a person can attend
- Minimum number of conference rooms required (this variation uses a different technique—more on that in Pattern 2)
- Minimum number of arrows to burst overlapping balloons
Pattern 2: Merge Intervals
Given a collection of intervals, merge all overlapping intervals and return the resulting list of non-overlapping intervals.
The approach: sort intervals by start time. Initialize your result with the first interval. For each subsequent interval, check if it overlaps with the last interval in your result (its start is less than or equal to the previous end). If it does, extend the previous end to the maximum of both ends. If it does not, add the new interval to the result.
Why this works: sorting by start time guarantees that if interval B overlaps with interval A, B will appear immediately after A (or within the same merged group). No interval that comes later in the sorted order can overlap with A without also overlapping with B.
Time complexity: O(n log n) for sorting, O(n) for the merge scan.
Common variations:
- Insert a new interval into a sorted list of non-overlapping intervals
- Find the minimum number of meeting rooms (use a min-heap to track end times, or sweep-line with +1/-1 events)
- Determine if a person can attend all meetings (just check for any overlap after sorting)
Pattern 3: Jump Game and Reachability
Given an array where each element represents the maximum jump length from that position, determine whether you can reach the last index (or find the minimum number of jumps).
The greedy insight for reachability: maintain a variable maxReach that tracks the farthest index you can reach so far. Iterate through the array: at each index i, update maxReach = max(maxReach, i + nums[i]). If at any point i > maxReach, you are stuck and cannot proceed. If maxReach reaches or exceeds the last index, return true.
The greedy insight for minimum jumps: use a BFS-like level expansion. Track the current level’s farthest reach and the next level’s farthest reach. Each time you exhaust the current level, increment the jump count and move to the next level.
Time complexity: O(n) for both variants—no sorting needed.
Common variations:
- Jump Game I (can you reach the end?)
- Jump Game II (minimum jumps to reach the end)
- Video stitching (minimum number of clips to cover a time range)
Pattern 4: Task Scheduling with Cooldown
Given a list of tasks and a cooldown period n, find the minimum number of time units needed to execute all tasks. The same task must have at least n units of cooldown between consecutive executions.
The greedy insight: the most frequent task dictates the schedule. Count task frequencies. The most frequent task (frequency f) creates (f - 1) gaps of size n between its executions. Fill those gaps with other tasks in frequency order. If there are not enough distinct tasks to fill the gaps, idle slots remain.
The formula: result = max(totalTasks, (maxFreq - 1) * (n + 1) + countOfMaxFreqTasks).
Why does this formula work? The first term handles the case where there are enough tasks to fill all gaps. The second term handles the case where idle slots are unavoidable because one or more tasks dominate the frequency distribution.
Time complexity: O(n) where n is the number of tasks (counting sort on 26 uppercase letters).
Pattern 5: Fractional Knapsack and Greedy Selection
Given items with weights and values and a knapsack with a weight capacity, maximize the total value. Unlike the 0/1 knapsack (which requires DP), the fractional variant allows you to take a fraction of an item.
The greedy insight: sort items by value-to-weight ratio in descending order. Greedily take as much of the highest-ratio item as possible, then move to the next.
Why does greedy work here but not for 0/1 knapsack? Because fractional items can be split, so the greedy choice of the best ratio never “wastes” capacity. In 0/1 knapsack, taking a high-ratio item might consume too much weight and exclude a combination of smaller items with greater total value.
Time complexity: O(n log n) for sorting.
Common variations:
- Assign cookies to children (sort both greed factors and cookie sizes)
- Boats to save people (two-pointer after sorting)
- Partition labels (greedy interval merging variant)
Pattern 6: Huffman Coding and Greedy Construction
Build an optimal prefix-free encoding tree by repeatedly merging the two lowest-frequency nodes. This pattern appears less frequently in coding rounds but is common in system design discussions about data compression.
The greedy insight: merging the two least frequent symbols first ensures they get the longest codes, which minimizes the total encoded length.
Time complexity: O(n log n) using a min-heap.
Where this appears in interviews: questions about designing a compression system, optimal merge patterns (merge K sorted files with minimum total I/O), and sometimes as a direct coding question.
How to Prove Greedy Correctness in an Interview
Interviewers often follow up a greedy solution with “how do you know this is optimal?” You do not need a formal mathematical proof, but you should have a structured argument:
Exchange argument: assume an optimal solution that differs from the greedy solution. Show that you can swap one element of the optimal solution with the greedy choice without making the solution worse. Repeat this swap until the optimal solution matches the greedy one.
Stays-ahead argument: show that after each step, the greedy solution is at least as good as any other solution. If greedy stays ahead at every step, it must be ahead at the end.
In practice, a clear sentence like “sorting by end time ensures we always leave the maximum room for future intervals, so any other choice can only be equal or worse” is sufficient for most interview settings. An AI interview assistant can help you rehearse these justifications until they feel natural.
Common Mistakes and How to Avoid Them
Mistake 1: Applying Greedy When DP Is Required
The classic trap: 0/1 knapsack looks similar to fractional knapsack, but greedy fails. Always ask yourself, “can I construct a counterexample where the greedy choice leads to a suboptimal result?” If you find one, switch to DP.
Mistake 2: Sorting by the Wrong Key
In interval scheduling, sorting by start time instead of end time gives the wrong answer. In task scheduling, sorting by deadline instead of frequency leads to suboptimal schedules. The sorting key is the core of the greedy strategy—get it wrong and everything falls apart.
Mistake 3: Forgetting Edge Cases
Empty input, single-element input, all intervals overlapping, all intervals disjoint, duplicate values—these edge cases trip up even experienced candidates. Always walk through at least two edge cases before declaring your solution complete.
Mistake 4: Not Communicating the Greedy Intuition
Many candidates jump straight to code without explaining why greedy works. This is a missed opportunity. The proof sketch is often more important than the implementation because it demonstrates depth of understanding.
A Practice Roadmap
If you are preparing for interviews and want to build greedy algorithm fluency, follow this progression:
Week 1: Foundation — Solve activity selection, merge intervals, and meeting rooms. Focus on understanding the sorting key and the proof for each.
Week 2: Array Greedy — Tackle jump game variants, gas station (circular route), and candy distribution. These problems train you to track running state variables.
Week 3: Advanced Patterns — Work on task scheduler, partition labels, and reorganize string. These combine frequency counting with greedy placement.
Week 4: Mixed Practice — Solve problems without being told the category. The real interview will not label a problem as “greedy.” Your job is to recognize the signal. Using a smart interview tool for mock sessions can accelerate this recognition process dramatically.
Greedy vs. Dynamic Programming: A Quick Decision Framework
When you encounter a new optimization problem, run through this checklist:
- Can I find a counterexample for greedy? If yes, use DP.
- Does the problem have overlapping subproblems? If yes, use DP.
- Can I sort and make one pass? If yes, greedy is likely correct.
- Does taking a fraction make the problem easier? If the fractional version is easy but the whole-item version is hard, the whole-item version probably needs DP.
This framework will not cover every case, but it handles the vast majority of interview questions. Practicing with timed mock interviews is the best way to internalize these decision points until they become second nature.
Final Thoughts
Greedy algorithms reward clarity of thought. The code is almost always short—often under 20 lines—but the reasoning must be airtight. In your next interview, resist the urge to jump into code. Spend the first two minutes articulating the sorting key, the greedy choice, and a brief proof sketch. This structured approach signals to the interviewer that you think like a senior engineer, not just a coder.
Take Control of Your Career Path:
- Official Site: www.offerbull.net
- iOS App: Download for iPhone/iPad
- Android App: Download for Android