Skip to lesson

Practice: greedy and intervals

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Synthesize greedy patterns across intervals, heaps, and two-pass arrays to solve complex interview problems.

Selecting the optimal greedy strategy

Greedy interview questions divide into distinct structural archetypes. Matching problems sort demands and resources for two-pointer scans. Interval selection sorts by finish time to discard overlapping conflicts.

Interval merging sorts by start time to combine adjacent ranges. Capacity problems track concurrent peaks using priority queues or sweep lines. Reachability problems maintain a single running maximum index.

Step by step

Step 1 of 4

Array: 9.
segment
1
length
9
String 'ababcbacadefegdehijhklij'. Record last occurrence of each character.

Two-pass algorithms resolve bidirectional constraints across linear arrays. Always match problem constraints to the appropriate archetype before writing code. Test small counter-examples to ensure discrete constraints do not require dynamic programming.

Reward distribution and two-pass greedy propagation

In reward distribution, each employee must receive at least one reward. An employee with a higher rating than their neighbour must receive more rewards. A single pass fails because ratings oscillate in both directions.

Example 1 · Two-Pass Reward Distribution

RewardDistributionDemo.javaJava
import java.util.Arrays;
public class RewardDistributionDemo {    public static int reward(int[] ratings) {        int n = ratings.length;        int[] rewards = new int[n];        Arrays.fill(rewards, 1);
        // Left to right: satisfy left neighbor constraint        for (int i = 1; i < n; i++) {            if (ratings[i] > ratings[i - 1]) {                rewards[i] = rewards[i - 1] + 1;            }        }
        // Right to left: satisfy right neighbor constraint        for (int i = n - 2; i >= 0; i--) {            if (ratings[i] > ratings[i + 1]) {                rewards[i] = Math.max(rewards[i], rewards[i + 1] + 1);            }        }
        int sum = 0;        for (int c : rewards) sum += c;        return sum;    }
    public static void main(String[] args) {        int[] r1 = {1, 0, 2};        int[] r2 = {1, 2, 2};        System.out.println("Rewards for r1: " + reward(r1));        System.out.println("Rewards for r2: " + reward(r2));    }}
Output
Rewards for r1: 5
Rewards for r2: 4

What this code does

  • For r1, left pass gives [1, 1, 2] and right pass gives [2, 1, 2] with sum 5.
  • For r2, left pass gives [1, 2, 1] and right pass leaves [1, 2, 1] with sum 4.
  • Satisfies all local conditions in O(n) time and O(n) space.

A two-pass greedy algorithm resolves constraints from both directions. First, scan left to right. If an employee has a higher rating than their left neighbour, increment their rewards. Second, scan right to left. If an employee has a higher rating than their right neighbour, update using Math.max. This satisfies both neighbour constraints while minimising total rewards allocated. The entire two-pass procedure executes in linear time and space.

Partition labels and queue reconstruction

Partition labels splits a string so characters appear in at most one part. Precompute the last occurrence index for every lowercase letter. Maintain a running boundary equal to the farthest last index seen. When current index matches this boundary, a complete partition is found.

Example 2 · Partition Labels by Last Occurrence

PartitionLabelsDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class PartitionLabelsDemo {    public static List<Integer> partitionLabels(String s) {        int[] last = new int[26];        for (int i = 0; i < s.length(); i++) {            last[s.charAt(i) - 'a'] = i;        }
        List<Integer> partitions = new ArrayList<>();        int start = 0;        int end = 0;
        for (int i = 0; i < s.length(); i++) {            end = Math.max(end, last[s.charAt(i) - 'a']);            if (i == end) {                partitions.add(end - start + 1);                start = i + 1;            }        }        return partitions;    }
    public static void main(String[] args) {        String s = "ababcbacadefegdehijhklij";        System.out.println("Partition lengths: " + partitionLabels(s));    }}
Output
Partition lengths: [9, 7, 8]

What this code does

  • Tracks last index for each character 'a' through 'z'.
  • First slice extends to index 8 ('a'), giving length 9.
  • Produces [9, 7, 8] in single pass linear time O(n).

Example 3 · Queue Reconstruction by Height

QueueReconstructionDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class QueueReconstructionDemo {    public static int[][] reconstructQueue(int[][] people) {        Arrays.sort(people, (a, b) -> {            if (a[0] != b[0]) return Integer.compare(b[0], a[0]); // Height descending            return Integer.compare(a[1], b[1]); // k ascending        });
        List<int[]> list = new ArrayList<>();        for (int[] p : people) {            list.add(p[1], p); // Insert at index k        }        return list.toArray(new int[people.length][]);    }
    public static void main(String[] args) {        int[][] people = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}};        int[][] res = reconstructQueue(people);        System.out.println("Reconstructed: " + Arrays.deepToString(res));    }}
Output
Reconstructed: [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]

What this code does

  • Sorts people with tallest first: [7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4].
  • Inserts each person at index p[1] in the list.
  • Shorter people inserted later do not disrupt counts of taller people.

Queue reconstruction orders people by height and count of taller predecessors. Sort people by height descending, resolving ties by count ascending. Insert each person into a list at their required count index. Because subsequent people are shorter, inserting them never alters counts of earlier taller people. This greedy invariant builds the reconstructed queue cleanly in quadratic time.

Finish up

Mark complete & continue

Next: What dynamic programming is