DSA
Master Greedy Patterns: 6 templates for Coding Interviews
Master 6 greedy patterns techniques used in Google, Amazon, and Meta interviews.

You've spent hours grinding LeetCode. You’ve memorized all the solutions to Buy/Sell Stock, Merge Intervals, and Jump Game. But then, in your Google onsite, the interviewer throws a new interval scheduling problem your way. The scenario feels familiar, but you’re suddenly second-guessing every move.
Sound familiar?
Here’s the real problem: Most engineers try to brute-force or memorize their way through “greedy” problems—hoping they’ll spot the trick in time. But FAANG interviewers aren’t looking for memorization; they want to see that “aha!” moment when you identify the right pattern and apply it confidently. Pattern mastery, not rote solutions, is what gets you the offer.
What You'll Learn
By the end of this guide, you’ll master:
✅ The 6 greedy sub-patterns: Buy/Sell Stock, Gas Station Circuit, Interval Merging/Scheduling, Jump Game Reachability/Minimization, Sorting Based, Task Scheduling (Frequency Based)
✅ Pattern recognition skills: Learn to spot greedy problems instantly, even in disguise
✅ 16 curated practice problems: Handpicked, real FAANG questions with company tags
✅ When to use each pattern: Clear mental models and recognition triggers
✅ Common pitfalls: The subtle traps and how to dodge them
✅ A practice roadmap: 2-3 weeks of daily tasks for total mastery
What is Greedy Patterns?
Imagine you’re navigating a maze with coins scattered along the path. At each fork, you’re allowed to grab the biggest pile in sight—no looking back, no second guessing. That’s the essence of greedy algorithms: make the best local choice at every step, hoping it leads to a global optimum.
Greedy patterns are the “shortcuts” of the algorithm world. When applied correctly, they transform problems that seem to require exhaustive search into slick, efficient solutions. The trick is knowing when the greedy choice really guarantees the best result—a skill that separates the average candidate from the hired engineer.
Why This Pattern Matters
- Time Efficiency: Greedy approaches often compress O(n²) brute force into O(n) or O(n log n) solutions—a must for interview performance.
- Ubiquity in Interviews: Over 1 in 7 FAANG coding interviews feature a greedy pattern—sometimes hidden behind clever disguises.
- Real-World Impact: From scheduling servers (Google) to optimizing ad revenue (Meta), greedy strategies drive critical systems.
- Signals Problem-Solving: Interviewers use greedy problems to assess your ability to think critically and avoid “overengineering.”
Companies that frequently ask greedy questions: Google, Amazon, Meta (Facebook), Apple, Microsoft, Bloomberg, Uber, DoorDash, Pinterest, Oracle.
The 6 Greedy Patterns Sub-Patterns
Let’s dive deep into the six core templates every engineer must master. For each, you’ll get a plain-English definition, the “why” behind the method, top problems, code templates, and expert tips.
1. Buy/Sell Stock
What it is:
The Buy/Sell Stock pattern focuses on maximizing (or sometimes minimizing) your gain by making one or more transactions over a sequence of prices. It’s all about picking the right days to buy and sell to optimize profit—often with constraints like one transaction or unlimited transactions.
Key insight:
Always chase the lowest price to buy and sell at the highest price after—never look back. If multiple transactions are allowed, grab every upward price swing. The greedy choice at each step—buy low, sell high—leads to global optimality because prices are independent from each other.
How it works:
- Track the minimum price seen so far (for single buy/sell).
- For each day, decide whether to buy, sell, or hold.
- For multiple transactions, sum up all local gains (price[i] > price[i-1]).
When to use:
- Problems mention “stock prices”, “buy/sell”, or “maximize profit”.
- You’re allowed to make one or multiple transactions.
- There’s a daily sequence or time series of values.
- The problem asks for the optimum gain/loss with minimal constraints.
Recognition triggers:
- “Maximize profit” given an array of prices.
- “You can buy and sell once/twice/as many times as you want.”
- “At most one transaction” or “unlimited transactions”.
Essential Problems:
Easy:
- Best Time to Buy and Sell Stock – Amazon, Microsoft, Facebook, Apple, Adobe
Context: Classic “buy low, sell high once” problem. ⭐
Medium:
- Best Time to Buy and Sell Stock II – Amazon, Apple, TCS, Microsoft, Facebook
Context: Multiple transactions allowed. How do you maximize profit by capturing every upward trend? ⭐
💡 Pro Tip:
Always ask the interviewer if multiple transactions are allowed. For unlimited transactions, simply sum up every positive price difference.
⚠️ Common Mistake:
Mistaking local maxima/minima for global ones—e.g., selling too early or buying too late. Avoid by tracking both the current minimum and calculating profit at each step.
Example Code Pattern:
PYTHON
For multiple transactions:
PYTHON
Time/Space Complexity:
O(n) time, O(1) space for both single and multiple transaction variants.
2. Gas Station Circuit
What it is:
Given a circular route with gas stations, each with a certain amount of gas, and a cost to travel to the next station, the task is to determine if you can complete the circuit starting from any station—and if so, find the correct starting index.
Key insight:
If the total gas is less than the total cost, it’s impossible. Otherwise, the greedy rule is: Whenever your tank goes negative, the only potential starting points are after that station (since you can’t “make up” for a deficit before then).
How it works:
- Track your current tank and total deficit.
- Whenever your tank becomes negative, reset the starting index to the next station and set tank to zero.
- If the total gas accumulated is at least the total cost, you can complete the circuit from the found index.
When to use:
- The problem involves a circular array or wrap-around.
- There’s a “can you complete the circuit?” type question.
- Each node provides a “resource” and “cost” to reach the next.
- You’re finding a starting point for a cycle.
Recognition triggers:
- “Circular route”, “complete the circuit”, “start at a station and return”.
- Arrays of “gas” and “cost”.
- “Find the starting index” or “can you finish the loop?”
Essential Problems:
Medium:
- Gas Station – Amazon, Microsoft, Apple, Hotstar, Google ⭐
Context: Classic circular gas/cost problem. Key: reset start whenever tank < 0.
💡 Pro Tip:
Don’t simulate the journey from every station—use the cumulative deficit approach for O(n) time.
⚠️ Common Mistake:
Trying all possible starting points (O(n²)). Instead, realize you can skip stations where the tank goes negative, as no solution can start there.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(n) time, O(1) space.
3. Interval Merging/Scheduling
What it is:
Given a collection of intervals (start/end times), the problem typically asks you to merge overlapping intervals, insert new intervals, find intersections, or schedule resources to minimize overlap. Greedy techniques prioritize earliest end times or process intervals by sorted order.
Key insight:
Sorting by start or end time lets you greedily merge or schedule intervals without missing any optimal grouping. Always process intervals in a way that minimizes conflicts or maximizes resource usage.
How it works:
- Sort intervals by start or end.
- For merging: Combine intervals if they overlap.
- For scheduling: Always pick the interval that ends earliest (to leave room for more intervals).
- For groupings: Use a min-heap to track current interval ends.
When to use:
- Overlap, merge, or scheduling of time/intervals.
- “Minimize rooms/resources”, “merge overlapping”, or “find free/busy times”.
- Insert or find intersection among intervals.
Recognition triggers:
- Inputs are pairs/ranges (start, end).
- Questions about overlapping, merging, or scheduling.
- “Minimum number of groups/rooms”, “insert interval”, “find intersections”.
Essential Problems:
Medium:
- Merge Intervals – Facebook, JPMorgan, Amazon, Bloomberg, Apple ⭐
Context: Merge all overlapping intervals into one. - Insert Interval – Google, Twitter, Amazon, Apple, Facebook ⭐
Context: Insert a new interval and merge if necessary. - Interval List Intersections – Facebook, Uber, Apple, Google, Amazon
Context: Find intersections between two interval lists. - Divide Intervals Into Minimum Number of Groups
Hard:
- Employee Free Time – DoorDash, Pinterest, Amazon, Intuit, Oracle
Context: Find free time slots for multiple employees’ schedules.
💡 Pro Tip:
When merging or scheduling intervals, sort by start or end, and use a heap if you need to track current overlaps (e.g., for “minimum rooms needed”).
⚠️ Common Mistake:
Forgetting to sort the intervals—leads to missed overlaps or incorrect merges. Always sort before processing.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(n log n) time (due to sorting), O(n) space.
4. Jump Game Reachability/Minimization
What it is:
Given an array where each element represents your max jump length from that position, determine if you can reach the end (reachability), or find the minimum number of jumps to get there (minimization).
Key insight:
Always jump as far as possible at each step—greedily maximize your reach. Track the farthest point you can reach at each index, and only jump when you must (i.e., when you exhaust the current jump range).
How it works:
- Keep track of the farthest index reachable.
- For minimization, update the jump count when reaching the end of the current range.
- Stop early if you reach the end.
When to use:
- Problems with “can reach the end”, “minimum jumps”, or “maximum reach”.
- Each array element is a “jump length” or “steps allowed”.
- The goal is to reach the end as fast as possible.
Recognition triggers:
- “Jump Game”, “minimum number of jumps”, “reach last index”.
- Array values represent possible jumps.
Essential Problems:
Medium:
- Jump Game – Amazon, Apple, Facebook ⭐
Context: Can you reach the end of the array? - Jump Game II – Amazon, Apple
Context: What’s the minimum number of jumps needed?
💡 Pro Tip:
For Jump Game II, only increment the jump counter when you exhaust your current maximal reach.
⚠️ Common Mistake:
Updating the jump counter or range too early or too late—always check if you’ve reached the end of the current jump’s range before incrementing.
Example Code Pattern:
PYTHON
PYTHON
Time/Space Complexity:
O(n) time, O(1) space.
5. Sorting Based
What it is:
These problems ask you to make optimal assignments or arrangements—often by sorting input arrays to prioritize the greedy choice at each step. Think of distributing cookies to children, reconstructing queues, or scheduling trips to minimize cost.
Key insight:
Sort to bring the “best” or “most needy” elements to the front, then assign or match greedily. Sorting unlocks the optimal sequence for greedy assignment.
How it works:
- Sort arrays by need, size, profit, height, cost, etc.
- Use pointers or iterate to match up elements efficiently.
- For some problems, sort by one key and process in reverse or with additional rules.
When to use:
- Assignment, distribution, or arrangement problems.
- The goal is to maximize/minimize based on sorted criteria.
- Matching two lists (e.g., children and cookies, cities and costs).
Recognition triggers:
- “Assign”, “distribute”, “schedule”, “reconstruct queue”, “minimum/maximum cost”.
- Two lists/arrays to match up.
Essential Problems:
Easy:
- Assign Cookies – Amazon
Context: Greedily assign smallest sufficient cookie to each child. ⭐
Medium:
- Queue Reconstruction by Height – Google, Facebook ⭐
Context: Arrange people in a queue based on height and order. - Two City Scheduling – Bloomberg
Context: Minimize total cost by sending people to two cities.
Hard:
- Candy – Amazon
Context: Distribute candies to children based on ratings, minimizing total candies.
💡 Pro Tip:
When matching two arrays, sort both (one ascending, one ascending/descending as needed) and use pointers to pair up greedily.
⚠️ Common Mistake:
Not sorting or misunderstanding which attribute to sort by—always clarify sorting criteria in the problem.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(n log n) for sorting, O(1) or O(n) space.
6. Task Scheduling (Frequency Based)
What it is:
Given a set of tasks (often with cooldowns, constraints, or frequencies), the goal is to schedule or rearrange tasks in a way that minimizes total time or avoids conflicts. Greedy approaches prioritize the most frequent or most constrained tasks first.
Key insight:
Always handle the most frequent or difficult tasks first, since they’re the hardest to “fit in” around others. Greedily allocate slots to high-frequency tasks, then backfill with the rest.
How it works:
- Use a frequency counter to track task appearances.
- Use a max heap (priority queue) to always pick the most frequent task.
- Schedule tasks, insert idle times as needed to meet constraints (like cooldowns).
When to use:
- Scheduling tasks with constraints (e.g., cooldowns, grouping).
- Minimize total time or rearrange to avoid consecutive duplicates.
- Frequency-based selection is required.
Recognition triggers:
- “Tasks”, “intervals”, “cooldown”, “no two adjacent”.
- “Minimize total time”, “group similar tasks”.
Essential Problems:
Medium:
- Task Scheduler – Facebook, Rubrik, Amazon, Pinterest, Google ⭐
Context: Given tasks and cooldown, find minimum intervals needed. - Distant Barcodes – Bloomberg
Context: Arrange numbers so no two adjacent are the same.
💡 Pro Tip:
When tasks have cooldowns, fill cycles with as many different tasks as possible; use a max heap for efficient selection.
⚠️ Common Mistake:
Forgetting to account for idle slots or leftover tasks in Task Scheduler.
Solution: Use the formula: (max_freq - 1) * (n + 1) + tasks_with_max_freq.
Example Code Pattern:
PYTHON
Time/Space Complexity:
O(n) time (n = total tasks), O(1) or O(k) space (k = unique tasks).
How to Master Greedy Patterns on Thita.ai
Thita.ai is engineered to take you from “I kinda get it” to “I can ace any greedy pattern, any day.” Here’s how:
- Pattern-Based Problem Sets: Tackle the complete Greedy Patterns Sheet—problems organized by subpattern, difficulty, and company frequency.
- AI Hints & Instant Feedback: Stuck on a problem? Use Best Ways to Use AI for DSA and Coding Interview Preparation to get tailored hints, bug explanations, and step-by-step guidance.
- Real Interview Simulation: Practice with AI Interview Practice: Free Mock Interview Simulator with Real-Time Feedback for Technical Interviews for real-time, FAANG-style behavioral and technical rounds.
- Track Your Progress: Monitor mastery, spot weak areas, and celebrate streaks on your Dashboard.
- Technical Coaching: Chat with your AI Coach for personalized learning plans, deep dives, and on-demand debugging.
Your Greedy Patterns Learning Roadmap
Here’s a proven 2-3 week plan to go from basics to FAANG-level mastery. Estimated daily time: 45-75 minutes.
Week 1: Foundations
-
Day 1:
- Best Time to Buy and Sell Stock
- Assign Cookies
Goal: Grasp basic greedy “local optimum” moves.
-
Day 2:
- Best Time to Buy and Sell Stock II
- Jump Game
Goal: Multiple transactions and greedy reachability.
-
Day 3:
- Merge Intervals
- Insert Interval
Goal: Interval merging and insertion.
-
Day 4:
- Interval List Intersections
- Two City Scheduling
Goal: Interval intersection and cost-based assignment.
Week 2: Intermediate
-
Day 5:
- Queue Reconstruction by Height
- Jump Game II
Goal: Complex greedy assignments and jump minimization.
-
Day 6:
- Gas Station
- Task Scheduler
Goal: Circular problems and frequency-based scheduling.
-
Day 7:
- Divide Intervals Into Minimum Number of Groups
- Distant Barcodes
Goal: Grouping and rearrangement by constraints.
-
Day 8:
- Employee Free Time
Goal: Hard interval scheduling.
- Employee Free Time
-
Day 9:
- Mixed practice: Randomly pick 3-4 previously solved problems and attempt them without looking at solutions.
Goal: Reinforce recognition and recall.
- Mixed practice: Randomly pick 3-4 previously solved problems and attempt them without looking at solutions.
Week 3: Mastery
-
Day 10:
- Candy
Goal: Advanced sorting-based assignment.
- Candy
-
Day 11:
- Timed challenge: Merge Intervals, Task Scheduler, Gas Station
Goal: Speed under pressure.
- Timed challenge: Merge Intervals, Task Scheduler, Gas Station
-
Day 12:
- Mixed hard problems: Employee Free Time, Candy
Goal: Synthesize multiple greedy techniques.
- Mixed hard problems: Employee Free Time, Candy
-
Day 13:
- Take a Mock Interview with greedy focus.
Goal: Real interview simulation.
- Take a Mock Interview with greedy focus.
-
Day 14:
- Review all mistakes using AI Coach.
- Re-attempt any problem you found tricky.
Goal: Solidify mastery and fill final gaps.
Common Greedy Patterns Pitfalls
Let’s break down the traps that even advanced engineers fall into—and how to sidestep them.
⚠️ 1. Assuming Greedy Always Works
Problem: You blindly apply a greedy solution without proving it leads to a global optimum.
Solution: Always check the “greedy choice property” and “optimal substructure.” For example, in coin change (with non-standard denominations), greedy doesn’t always yield the fewest coins.
⚠️ 2. Forgetting to Sort Intervals
Problem: You merge or schedule intervals without sorting, leading to missed overlaps.
Solution: Always sort intervals by start or end before processing.
PYTHON
⚠️ 3. Mishandling Ties in Sorting
Problem: Sorting by one attribute when two are needed (e.g., height and position in Queue Reconstruction).
Solution: Use a tuple sort:
PYTHON
⚠️ 4. Not Handling Edge Cases (e.g., Empty Input)
Problem: Missing checks for empty lists or single-element cases.
Solution: Add guard clauses at the start of your function.
⚠️ 5. Overcounting/Undercounting in Frequency Scheduling
Problem: Not properly accounting for idle slots or leftover tasks in Task Scheduler.
Solution: Use the formula: (max_freq - 1) * (n + 1) + tasks_with_max_freq.
⚠️ 6. Modifying Data In-Place Without Copying
Problem: Accidentally modifying input arrays (e.g., intervals) when you should work on a copy.
Solution: Use intervals = sorted(intervals) or create a new list.
⚠️ 7. Not Resetting State in Circular Problems
Problem: In Gas Station, failing to reset the tank and start index when tank < 0.
Solution: Always reset tank and move the start pointer.
Why Greedy Patterns Beat Brute Force
Let’s take Best Time to Buy and Sell Stock as the example.
Brute Force Approach:
Try every possible pair of buy/sell days; O(n²) time.
PYTHON
Greedy Pattern Approach:
Track min price so far, compute max profit in one pass; O(n) time.
PYTHON
Complexity Comparison:
- Brute force: O(n²), fails for n > 10,000.
- Greedy: O(n), handles n = 10⁵+ instantly.
Key Insight:
By tracking the minimum price and calculating profit at each step, we never need to revisit earlier days. The greedy property holds because each price is independent.
When Greedy Wins:
- When local optimal choices guarantee the global optimum.
- When constraints or problem guarantees allow for one-pass, forward-only processing.
Beyond LeetCode: Real-World Applications
Let’s see how greedy patterns power production systems at top tech companies.
-
Resource Scheduling (Google Cloud)
- How: Greedy interval scheduling algorithms allocate VMs to physical servers, minimizing overlap and maximizing utilization. This is similar to the interval merging and scheduling pattern used in interviews.
- Benefit: Scales to millions of intervals daily, avoids O(n²) checks.
-
Ad Slot Assignment (Meta/Facebook)
- How: Greedy matching algorithms assign the highest-bidding ad to the next available slot, maximizing revenue in real time.
- Benefit: Instant, scalable, and revenue-optimal assignments.
-
Ride Allocation (Uber, Lyft)
- How: Greedy algorithms match drivers to nearest riders in real time, minimizing wait and idle time.
- Benefit: Improves rider/driver experience, reduces cost.
-
Workflow Scheduling (Amazon, AWS Lambda)
- How: Greedy frequency-based task scheduling ensures high-priority functions run first, respecting cooldowns and dependencies. This approach is closely related to the task scheduling (frequency based) pattern.
- Benefit: Reduces latency, prevents resource starvation.
-
Media Streaming (Netflix, YouTube)
- How: Greedy bandwidth allocation algorithms ensure high-priority streams (e.g., live events) get allocated first, then backfill with lower-tier streams.
- Benefit: Ensures smooth playback, prioritizes critical content.
Conclusion: From Memorization to Mastery
Key takeaways:
- Greedy patterns save time, eliminate brute force, and unlock top-tier interview performance.
- Pattern recognition—spotting the right subpattern—matters more than memorizing solutions.
- Practice, review, and simulation turn “aha moments” into muscle memory.
Next Steps:
- Start the Greedy Patterns Sheet for daily mastery.
- Get AI-Powered Feedback to debug and accelerate learning.
- Simulate Real Interviews and track your progress on your dashboard.
- Chat with an AI Coach to fill any gaps and build your customized roadmap.
Don’t just memorize solutions—master the patterns, and you’ll see every “tricky” interview problem with new eyes. The shortcut to FAANG isn’t more grinding. It’s smarter, pattern-driven prep.
Related Articles
External Resources
Ready to Master Greedy Patterns?
Thita.ai is the fastest, most efficient way to level up your interview skills—with AI-powered hints, curated problem sets, and real FAANG simulation. Join thousands of engineers who’ve landed offers at Google, Amazon, Meta, and more.