Greedy Template: Pattern, Code & Cheat Sheet
The Greedy pattern is one of the most frequently tested coding interview patterns. Make locally optimal choices for globally optimal solutions. This template gives you a reusable code skeleton, pseudocode, and implementation in multiple languages so you can solve 13+ problems using this single mental model.
Difficulty: Medium | Time Complexity: O(n log n) | Space Complexity: O(1)
When to Use This Template
Use the Greedy template when you see these signals in a problem:
Prerequisites: Sorting, Arrays
Problem count on W Code: 13 problems across Easy, Medium, and Hard difficulty levels.
If the problem does not match these signals, consider alternative patterns.
Pseudocode Template
function greedySolve(input):
// Initialize data structures
result = initial_value
// Core logic for Greedy
for each element in input:
process(element)
update(result)
return resultPython Implementation
pythondef solve(input_data): """Greedy solution template.""" result = [] # Implement greedy logic here for item in input_data: # Process each item result.append(item) return result
Java Implementation
javapublic Object solve(Object[] input) { // Greedy template // Implement core logic here return null; }
C++ Implementation
cppauto solve(vector<int>& input) { // Greedy template // Implement core logic return result; }
Variations & Adaptations
The Greedy pattern has several variations you should master:
Variation 1: Activity Selection
This variation is useful when the problem specifically requires activity selection. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 2: Fractional Knapsack
This variation is useful when the problem specifically requires fractional knapsack. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 3: Job Scheduling
This variation is useful when the problem specifically requires job scheduling. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 4: Huffman Coding
This variation is useful when the problem specifically requires huffman coding. Adapt the main template by modifying the core loop/recursion logic accordingly.
Common Mistakes & Edge Cases
When implementing Greedy, watch out for:
Edge cases to always test:
Step-by-Step Problem Solving Guide
Frequently Asked Questions
What problems can I solve with the Greedy template?
What is the time complexity of Greedy?
What should I learn before Greedy?
How do I recognize a Greedy problem in an interview?
Practice 13+ Greedy problems on W Code with instant feedback and AI-powered hints. Start your free practice now!
Start Learning Free