Greedy & Intervals 101
Intermediate · 4 chapters · 8 min read · Make the locally best choice, and learn how to prove it is also globally best.
Practise this in the app All guides
What greedy means
Commit and never look back
A greedy algorithm builds the answer one step at a time, always taking the choice that looks best right now, and never undoing it. When it works, it is usually the shortest and fastest solution: often a sort followed by one pass. When it does not work, it gives confidently wrong answers, which is why interviewers care as much about why your greedy choice is safe as about the code.
Signals in a problem statement
- "Minimum number of" arrows, platforms, jumps, coins (in standard denominations), or intervals to remove.
- "Maximum number of" non-overlapping meetings, satisfied children, tasks done.
- Intervals: start and end times, merging, overlapping, scheduling.
- "Can you reach the end?" with jump lengths.
- Distributing items with neighbour constraints ("each child with a higher rating gets more candy").
- Sorting the input seems to make the problem easy.
Greedy versus dynamic programming
Both make a sequence of decisions. Greedy commits to one choice per step; DP tries every choice and remembers the best. If you can find a small counter-example where the obvious greedy choice fails (coins [1, 3, 4] making 6: greedy takes 4 + 1 + 1, but 3 + 3 is better), switch to DP.
How to justify a greedy choice
Use the exchange argument: take any optimal solution that differs from yours at the first step, swap in your greedy choice, and show the result is no worse. For interval scheduling: among all meetings, the one that ends earliest leaves the most room for the rest, so an optimal schedule can always be rearranged to start with it. One or two sentences like this are enough in an interview, and they show you are not just guessing.
Core patterns with templates
1. Sort by end, keep what fits
The maximum number of non-overlapping intervals; the number to remove is n - kept.
def erase_overlap(intervals):
intervals.sort(key=lambda x: x[1])
kept, end = 0, float("-inf")
for s, e in intervals:
if s >= end:
kept += 1
end = e
return len(intervals) - kept
Shooting balloons with arrows is the same idea: one arrow at the end of the earliest-ending balloon bursts every balloon that starts at or before it.
2. Merge overlapping intervals (sort by start)
def merge(intervals):
intervals.sort()
out = []
for s, e in intervals:
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return out
3. Farthest reach
def can_jump(nums):
reach = 0
for i, x in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + x)
return True
Example: [3, 2, 1, 0, 4] gets stuck at index 4 because the reach never passes 3.
4. Match smallest with smallest
def content_children(greed, cookies):
greed.sort()
cookies.sort()
i = 0
for c in cookies:
if i < len(greed) and c >= greed[i]:
i += 1
return i
5. Two passes for neighbour constraints
def candy(ratings):
n = len(ratings)
c = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
c[i] = c[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
c[i] = max(c[i], c[i + 1] + 1)
return sum(c)
The left pass satisfies left neighbours, the right pass satisfies right neighbours, and max keeps both.
Complexity, mistakes and edge cases
Complexity
Most greedy solutions are O(n log n) because of the initial sort, followed by an O(n) scan. Those without sorting (jump game, candy) are O(n). Extra space is usually O(1) beyond the sort, or O(n) for an auxiliary array like the candy counts.
Common mistakes
- Sorting by the wrong key. For "maximum non-overlapping" or "minimum arrows", sort by end. For "merge", sort by start. Sorting non-overlap problems by start fails on
[[1, 10], [2, 3], [4, 5]]. - Touching endpoints. Is
[1, 2]overlapping[2, 3]? For non-overlapping intervals usually no; for balloons usually yes (an arrow at 2 bursts both). Read the statement and ask. The difference is>=versus>. - Mutating the input when the caller still needs it; copy if unsure.
- Using a greedy with no argument. Always test a small counter-example in your head. If the greedy fails, say so and move to DP; interviewers appreciate that honesty.
- Initialising
end = 0when interval coordinates can be negative; use negative infinity. - One-pass candy. A single left-to-right pass cannot see a decreasing run coming; you need the second pass (or a slope-counting trick).
Edge cases
An empty list of intervals, a single interval, intervals that are all identical, intervals nested inside each other, negative coordinates, [0] for jump game (already at the end), and ratings that are all equal (everyone gets one candy).
Checking a greedy quickly
Write a tiny brute force (try every subset) for inputs of size four or five, and compare it with your greedy on a few random cases. You will not do this in a live interview, but doing it during practice builds the intuition for which greedy choices are safe.
Variations and practise
How interviewers twist it
- Insert an interval into a sorted, non-overlapping list: copy the ones that end before it, merge the ones that overlap, copy the rest.
- Meeting rooms. Can one person attend everything? Sort by start and check neighbours. How many rooms? Sort starts and ends separately and sweep, or use a min-heap of end times.
- Minimum jumps. Treat each jump as a BFS level: track the current level's end and the farthest reach; when you pass the end, take a jump.
- Gas station. If total gas is at least total cost, a solution exists; start just after the point where the running tank last went negative.
- Partition labels. Record the last index of each character, then extend the current part until you reach the furthest last index seen.
- Plant flowers, assign seats. Scan once and place greedily where the rule allows.
- Weighted interval scheduling. Once intervals carry profits, greedy fails; use DP with binary search over end times.
How to explain it
Say the rule and the reason together: "I sort by end time and take each interval that starts after the last one I kept, because finishing earliest leaves the most room." That sentence covers both the code and the proof.
Practise
The problems below cover reachability with jumps, matching smallest to smallest, two-pass neighbour constraints, and the two classic interval problems (removing overlaps and bursting balloons). For each, write the sort key and the comparison (> or >=) before you write the loop.
Practise
Easy
- 2528. Assign Cookies
- 2529. Lemonade Change
- 2535. Fewest Coins from a Standard Till
- 2540. Most Souvenirs on a Budget
- 2541. Triangle Fence from Planks
- 2542. Exactly K Sign Flips
- 2543. Most Balanced Segments
- 2544. Gather Tokens on One Square
- 2545. Pair Up for the Best Minimums
- 2546. Loading the Cargo Van
- 2547. Third Item Free Checkout
- 2548. Can You Attend Every Class
- 2549. Who Is Busy at Moment T
- 2550. Compress Ticket IDs into Ranges
- 2551. Unsold Seats in a Row
- 2552. Turn One Six Upside Down
- 2553. Two Numbers from One Set of Digits
- 2554. Build a Rising Staircase
- 2555. Longest Mirror Word from Tiles
- 2556. Typing on a Letter Ring
- 2557. Return Empties for Refills
- 2558. Desks for Every Student
- 2559. Patch the Brackets
- 2560. Halve or Subtract to Zero
- 2561. Shared Cuts to Zero
- 2562. Alternate the Lights
- 2563. Smallest Palindrome with Fewest Edits
- 2564. Largest Odd Bit Arrangement
- 2565. Fewest Crates for the Harvest
- 2566. Pack Orders into Bags in Order
- 2567. Erase Marks Three at a Time
- 2568. Peak Lobby Occupancy
- 2569. Year with the Most Members
- 2570. Do Two Time Slots Clash
- 2571. Drop One Digit for the Biggest Number
- 2572. Most Positive Running Totals
- 2573. Refuel Stops with a Fixed Tank
- 2574. Drone Waypoint Tour
- 2575. Remap the Keypad for Fewest Presses
- 2576. Meetings That Clash with Mine
- 2577. Breaks Between Meetings
- 2578. Shared Hours of Two Friends
- 2579. Is Every Mile Patrolled
- 2580. Days Two Visits Overlap
- 2581. Most Passed Checkpoint on a Loop
- 2582. Watering Can Trips
- 2583. Do Two Posters Overlap
- 2584. Collect Every Upswing
- 2585. Longest Free Stretch of Floors
- 2586. Cover the Holes with Boards
- 2587. Break Up Long Runs
- 2588. One Parity Swap for the Smallest
- 2589. First-Come Room Bookings
- 2590. Fewest 0/1-Digit Numbers
- 2591. Keep the K Largest in Order
- 2592. Farthest Differently Painted Houses
- 2593. Pick the Max and Grow It
- 2594. Fewest Clock Adjustments
- 2595. Clip Bookings to a Window
- 2596. First Gap Long Enough
- 2597. Average Wait at the Food Truck
- 2598. Add One Rest Stop
- 2599. Largest Even from the Digits
- 2600. Rising Share Handout
- 2601. Booked Minutes in a Window
- 2726. Longest Pick per Budget
Medium
- 2530. Jump Game
- 2531. Non-overlapping Intervals
- 2532. Minimum Number of Arrows to Burst Balloons
- 2536. Slot In a New Booking
- 2537. Shared Free Windows
- 2538. Free Days on the Calendar
- 2602. Drop Nested Shifts
- 2603. Fewest Recording Studios
- 2604. Shuttle Seat Check
- 2605. Seat Reservations Ledger
- 2606. Cut a String into Closed Chunks
- 2607. Carve Out a Maintenance Window
- 2608. Next Session to Join
- 2609. Crowd at Each Query Time
- 2610. Most Festival Shows Attended
- 2611. Two Gigs, Best Pay
- 2612. Earliest Joint Slot
- 2613. Mixed Paint Segments
- 2614. Keep the Running Balance Afloat
- 2615. Widen to Match
- 2616. Splitting Ranges into Two Teams
- 2617. Accept Unless Triple Booked
- 2618. Fewest Hops to the Dock
- 2619. Hop Across Stepping Stones
- 2620. Starting Depot on a Loop Route
- 2621. Job Runner with Cooldown
- 2622. Rearrange with No Twin Neighbours
- 2623. Longest String Without Triples
- 2624. Trim K Digits to the Smallest
- 2625. Smallest Sequence of Unique Letters
- 2626. Largest Number with Rising Digits
- 2627. One Swap for the Biggest Number
- 2628. Restore the Photo Line
- 2629. Split Hires Across Two Offices
- 2630. Tandem Kayak Pairing
- 2631. Deal Cards into Consecutive Runs
- 2632. Flow Values Leftward
- 2633. Extend or Start a Run
- 2634. Outpace the Rival Lineup
- 2635. Fewest Fibonacci Pieces
- 2636. Favours for Reputation
- 2637. Letters Dominate After Sorting
- 2638. Unique Badge Numbers
- 2639. Cash In AB and BA Pairs
- 2640. Flip Rows and Columns for the Biggest Total
- 2641. Sell from Shrinking Stock
- 2642. Longest Zigzag Picks
- 2643. Largest Total Divisible by Three
- 2644. Brackets with Wildcards
- 2645. Group Riders into Four-Seat Cabs
- 2646. Fewest Swaps to Balance Brackets
- 2647. Make Every Letter Count Different
- 2648. Ropes and Ramps
- 2649. Convoys at the Finish
- 2651. Roof the Lots with K Awnings
- 2653. Halve or Nudge to One
- 2655. Uniform Tile Row
- 2656. Alternating Council Vote
- 2657. Fewest Kinds After Removals
- 2658. Halve the Crowd by Kinds
- 2659. Trios Within Tolerance
- 2660. Top Up the Sacks
- 2661. Unbraid Same-Color Beads
- 2662. Every A Before Every B
- 2663. Rounds of Pairs and Triples
- 2664. Outrun the Advancing Robots
- 2665. Paint Then Dry
- 2666. Pick from Two of Three Piles
- 2667. Cheapest Tree from Leaves
- 2668. Cost of Joining Ropes
- 2669. Lift Team Win Rates
- 2670. Single-Core Job Order
- 2671. Match Workers to Their Best Jobs
- 2672. Balanced Duo Workloads
- 2673. Smooth Steps Peak
- 2674. Double or Step to the Target
- 2675. Smallest Word of a Given Weight
- 2676. Insert a Digit for the Maximum
- 2677. Suffix Flips to Target Bits
- 2678. Back-and-Forth Walk to a Target
- 2679. P Pairs with the Tightest Gap
- 2680. Spread the Sensors
- 2681. Pair Off Unequal Neighbours
- 2682. Growing Group Tiers
- 2683. Pieces with No Repeated Letter
- 2684. Digit Chunks Under a Cap
- 2685. Most Disjoint Runs with Target Sum
- 2686. Swap Letters to Match
- 2687. K Boosts for the Biggest Product
- 2688. Locker for the Swimmer
- 2689. Nudge Heights Closer
- 2690. Flip Ends to a Uniform String
- 2691. Bench Blocks for Teams
- 2692. Sortable Chunks of a Permutation
- 2693. Longest Tarp over Planted Plots
- 2694. Combined Area of Two Posters
- 2695. Least Late by Deadline Order
- 2696. One-Day Jobs Before Deadlines
- 2697. Order Jobs by Weight Ratio
- 2698. Fractional Cargo Value
- 2699. Upswings with a Broker Fee
- 2700. Append to Embed a Word
- 2701. Fewest Copies to Spell the Target
- 2702. Smallest Up-Down Permutation
- 2703. Binary Down to One
- 2704. Guessing Group Sizes
- 2705. Four-Slot Ovens
- 2706. Reservoir Release Plan
- 2707. Shrink Gaps with K Moves
- 2708. Equal-Weight Rowing Pairs
- 2709. Ordered Jobs with Cooldown
- 2710. Fill Blanks for Least Repeats
- 2711. Cover Points with Given Strips
- 2712. Move One Meeting for a Longer Break
- 2713. Shift K Meetings for a Longer Break
- 2714. Corridor Lamps at Allowed Spots
- 2715. Largest String with a Repeat Cap
- 2716. Cut a Length for the Biggest Product
- 2717. Bubble Rows to a Lower Triangle
- 2718. Mentors at Least Double
- 2719. Smallest Word Within a Budget
- 2720. Number the Busiest Stations
- 2721. Largest Merge of Two Words
- 2722. Smallest Number with Digit Product N
- 2723. Settle Stones Consecutively
- 2724. Merge Neighbours into a Mirror
- 2725. Smoothest Circle of Heights
- 2727. Fading Gift Picks
- 2728. Dispatch Shuttles with a Wait Limit
- 2729. Drop One Guard Shift
- 2730. Most Conflicted Meeting
- 2731. Bridge Gaps with Short Shifts
- 2732. Time with at Least K Overlaps
- 2733. Spread Labels to Be Distinct
- 2734. Two-Tone Alternating Array
- 2735. Middle Share of Coin Trios
- 2736. Hire from Both Ends
- 2737. Shift One Run for the Smallest
- 2738. Last Cart Off the Rail
- 2739. Shift Letters Within K Moves
- 2740. Mirror Chain of Two-Letter Words
- 2741. Alternate Projects Weekly
- 2742. Team-Wide Free Slots
- 2773. Layered Paint Strokes
- 2781. Move a Front Letter to the Back
- 2797. Match Visitors to Time Slots
- 2804. Complementary Pair Sums
Hard
- 2533. Candy
- 2534. Minimum Number of Taps to Open to Water a Garden
- 2539. Fresh Paint Each Day
- 2650. Tightest Window per Query
- 2652. Best-Paid Non-Clashing Contracts
- 2654. Two Checkpoints per Route
- 2743. Fewest Powered-On Seconds
- 2744. Narrowest Window Hitting Every List
- 2745. Total Area of Overlapping Posters
- 2746. City Silhouette Outline
- 2747. Stacked Crates Heights
- 2748. Peak Overlap After Each Booking
- 2749. Fewest Fuel Stops with Variable Pumps
- 2750. Biggest Number from Two Rows
- 2751. Throughput of a Picking Team
- 2752. Most Repairs Before Cutoffs
- 2753. Proportional Fee Panel
- 2754. Adjacent Swaps to a Mirror
- 2755. Shelve Books in K Sections
- 2756. Patch Sums to Cover a Range
- 2757. Enough Stamina for Every Task
- 2758. Boost the Weakest District
- 2759. Smallest Pick with a Required Letter
- 2760. Tiered Groups with Usage Caps
- 2761. Most Self-Contained Substrings
- 2762. Busiest Conference Room
- 2763. Cheapest Cover of a Road
- 2764. Lifters, Crates and Energy Drinks
- 2765. Equalize Two Card Hands
- 2766. Best Window Around an Index
- 2767. Flip K-Windows to All Ones
- 2768. Grow a Pair to the Target
- 2769. Even Out the Bakery Trays
- 2770. Seat Partners Together
- 2771. Print a Banner with a Roller
- 2772. Rebuild from Ones by Sums
- 2774. Tighten the Spread by Halving
- 2775. Power N Devices the Longest
- 2776. Gather K Beacons Together
- 2777. Late Jobs with Prerequisites
- 2778. Cover Ring Points with Arcs
- 2779. K-Way File Merge Cost
- 2780. Most Sortable Chunks with Duplicates
- 2782. Tallest Tower Under Height Caps
- 2783. Tiles Form an Exact Rectangle
- 2784. Two-Station Assembly Order
- 2785. Cheapest Fuel Road Trip
- 2786. Cheapest Common Height
- 2787. K Crews, Most Jobs
- 2788. Cap Overlap at K
- 2789. Unit Tasks with Release and Deadline
- 2790. Trading with Regret
- 2791. Spread Repeats K Apart
- 2792. Deadline Jobs with Rewards
- 2793. Shortest Remaining Work First
- 2794. Outline Length of a Poster Wall
- 2795. Where Greedy Change Fails
- 2796. Separate Bookings with Least Shifting
- 2798. K Picks with No Neighbours in a Ring
- 2799. People, Keys and the Office
- 2800. Split into a Non-Decreasing List
- 2801. Rent Machines for Shows
- 2802. Smallest Number with K Adjacent Swaps
- 2803. Reverse One Span for Max Variation
- 2805. Relay Hops Between Points