Skip to main content
LeetCode Prep
CHAPTER 16 Beginner

Greedy Algorithms and Intervals

Updated: May 18, 2026
5 min read

# CHAPTER 16

Greedy Algorithms and Intervals

1. Chapter Introduction

Dynamic Programming requires you to evaluate *every possible choice* to find the global maximum. However, for a specific subset of problems, evaluating every choice is massive overkill. A Greedy Algorithm builds up a solution piece by piece, always choosing the next piece that offers the most immediate (local) benefit, with the assumption that this will naturally lead to the global optimal solution. This chapter covers Greedy strategies and the notoriously tricky "Interval" problems.

2. What makes an Algorithm "Greedy"?

Imagine you are a cashier giving change for $0.65 using quarters (25), dimes (10), and nickels (5). *Greedy approach:* You want to use the fewest coins. So, you take the biggest coin possible first.
  • Take 25c (Remainder: 40c).
  • Take 25c (Remainder: 15c).
  • Take 10c (Remainder: 5c).
  • Take 5c (Remainder: 0c).
Result: 4 coins. The Greedy strategy works perfectly for US currency! *(Note: If the coin denominations were 1, 3, and 4, and you needed 6, Greedy would pick 4, 1, 1 (3 coins). But the optimal answer is 3, 3 (2 coins). Greedy fails here; DP is required).*

3. Pattern 1: Activity Selection / Scheduling

*Prompt:* You have an array of meetings [[start_time, end_time]]. Find the maximum number of meetings a single person can attend without overlapping. *The Greedy Strategy:* Sort by End Time. Why? If you want to attend the maximum number of meetings, you should always attend the meeting that finishes the *earliest*, freeing up your schedule as quickly as possible for the next meeting.
python
123456789101112131415
def maxMeetings(meetings):
    # Sort meetings by their END time: x[1]
    meetings.sort(key=lambda x: x[1])
    
    count = 0
    last_end_time = -1
    
    for start, end in meetings:
        if start >= last_end_time:
            # We can attend this meeting!
            count += 1
            last_end_time = end # Update schedule
            
    return count
# Time: O(N log N) due to sorting, Space: O(1)

4. Pattern 2: Merge Intervals

This is a high-frequency interview question (LeetCode 56). *Prompt:* Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals. *Example:* [[1,3], [2,6], [8,10]] becomes [[1,6], [8,10]] because [1,3] and [2,6] overlap.

*The Strategy:* Sort by Start Time.

  1. 1. Sort the array based on the start value of each interval.
  1. 2. Initialize a merged list with the first interval.
  1. 3. Iterate through the remaining intervals.
  1. 4. If the start of the current interval is LESS THAN OR EQUAL TO the end of the last interval in merged, they overlap!
  1. 5. Update the end of the last interval in merged to be the max() of both ends.

java
123456789101112131415161718192021222324252627
public int[][] merge(int[][] intervals) {
    if (intervals.length <= 1) return intervals;
    
    // Sort by ascending starting point
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    
    List<int[]> merged = new ArrayList<>();
    int[] currentInterval = intervals[0];
    merged.add(currentInterval);
    
    for (int[] interval : intervals) {
        int currentEnd = currentInterval[1];
        int nextStart = interval[0];
        int nextEnd = interval[1];
        
        if (currentEnd >= nextStart) {
            // Overlapping intervals, update the end if needed
            currentInterval[1] = Math.max(currentEnd, nextEnd);
        } else {
            // Disjoint interval, add it to the list and reassign current
            currentInterval = interval;
            merged.add(currentInterval);
        }
    }
    return merged.toArray(new int[merged.size()][]);
}
// Time: O(N log N)

5. Pattern 3: Insert Interval

*Prompt:* You are given a sorted list of non-overlapping intervals. Insert a newInterval into the correct position and merge if necessary. *Logic:*
  1. 1. Iterate. While current interval ends *before* the new interval starts, append it to the result.
  1. 2. While current interval overlaps with the new interval, merge them by updating newInterval's start/end with the min() and max().
  1. 3. Append the final merged newInterval.
  1. 4. Append any remaining intervals.

6. The "Sorting" Prerequisite

Almost every single Greedy and Interval problem begins with sorting the input array. Because sorting is O(N log N), this will dictate your final Time Complexity.

7. Real-World Scenario: CPU Task Scheduling

Operating systems use Greedy algorithms to determine which process the CPU should execute next (e.g., Shortest Job First). By prioritizing the quickest tasks, the OS minimizes the average waiting time for all applications.

8. Mini Project: Jump Game

*Prompt:* You are given an integer array nums. Each element represents your maximum jump length at that position. Return true if you can reach the last index. [2,3,1,1,4] *Greedy Logic:* Iterate backwards! Keep track of the goal post (initially the last index). Look at the index right before the goal. Can it reach the goal? If yes, move the goal post to that index. If the goal reaches index 0, return True.

9. Common Mistakes

  • Assuming Greedy Always Works: Greedy algorithms are fast, but they don't look ahead. If a problem has complex interconnected constraints (like the Knapsack problem), a local optimal choice might trap you in a global sub-optimal result. Before writing code, mentally verify that the greedy choice holds true for edge cases.

10. Best Practices

  • Sorting Syntax: Be fluent in writing custom comparators for 2D arrays in your chosen language.
  • Python: intervals.sort(key=lambda x: x[0])
  • Java: Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

11. Exercises

  1. 1. Trace the Merge Intervals logic for [[1,4], [4,5]]. Do they overlap?
  1. 2. In the maxMeetings problem, why do we sort by *end* time rather than *start* time?

12. MCQs

Question 1

What is the fundamental philosophy of a Greedy Algorithm?

Question 2

What is the standard Time Complexity for most Greedy and Interval problems?

Question 3

When solving an "Activity Selection" or "Meeting Room Scheduling" problem to maximize the number of non-overlapping meetings attended, how should you sort the input?

Question 4

When solving the classic "Merge Overlapping Intervals" problem, how should you sort the input?

Question 5

In the "Merge Intervals" problem, how do you mathematically determine if the current interval overlaps with the next interval (assuming they are sorted by start time)?

Question 6

When merging two overlapping intervals (e.g., [1, 5] and [2, 7]), how is the new merged interval constructed?

Question 7

Why can a Greedy Algorithm fail on the 0/1 Knapsack Problem?

Question 8

In Python, how do you sort a 2D array (list of lists) intervals based specifically on the first element (start time) of each inner list?

Question 9

In the "Jump Game" array problem, what is an elegant Greedy approach to determine if you can reach the end?

Question 10

Do Interval problems usually require extra auxiliary Space (O(N))?

14. Interview Questions

  • Q: "Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required." (LeetCode 253. Hint: Use a Min-Heap to track room end times).

15. FAQs

  • Q: How do I know if I should use Greedy or DP?
A: It is hard. Try to find a counter-example where the greedy choice fails. If you can easily find a counter-example, use DP. If sorting the input naturally solves the problem, it's Greedy.

16. Summary

Interval and Scheduling problems are guaranteed to show up in interviews. The foundation of almost every Greedy algorithm is Sorting the input. Sort by Start Time when merging intervals; sort by End Time when maximizing scheduled activities. Master the array-overlap logic (end >= next_start) and be fluent in your language's custom sorting syntax.

17. Next Chapter Recommendation

We have covered all the fundamental data structures. In Chapter 17: Advanced Interview Patterns, we will touch upon the rare but terrifying concepts that appear in FAANG "Hard" interviews, including Tries, Union Find, and Bit Manipulation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·