NeetCode 150, stage 15: Greedy

← 2-D Dynamic Programming · All 150 problems · Intervals →

A greedy algorithm makes the best local choice at each step and never goes back. This stage trains you to find that choice and to say why it is safe. Most answers are one pass with one or two variables, so the proof is the hard part, not the code.

Problems on this page

#ProblemLevelPatternTemplate
153. Maximum SubarrayMediumKadane’s running sumA: Running sum with a reset
255. Jump GameMediumGreedy farthest reachB: Farthest reach
345. Jump Game IIMediumGreedy levels, as in BFSB: Farthest reach
4134. Gas StationMediumGreedy running total with a resetA: Running sum with a reset
5846. Hand of StraightsMediumSort, then take the smallest firstC: Sort, then take the smallest first
61899. Merge Triplets to Form Target TripletMediumGreedy filter, then combineD: Filter, then combine
7763. Partition LabelsMediumLast index, then extend the endE: Last index, then extend the end
8678. Valid Parenthesis StringMediumGreedy range of open countsF: Range of possible counts

Templates to memorize

Template A: Running sum with a reset

Signal

The problem asks for the best contiguous sum, or for a start point on a circle. A running total that goes below zero is of no use to the items after it.

// TEMPLATE A: running sum with a reset. A sum below zero cannot help the
// items after it.
func bestRunSum(nums []int) int {
    // not 0: the answer is negative when all the items are negative
    best := nums[0]
    sum := 0
    for _, x := range nums {
        if sum < 0 { // 1. RESET: drop a prefix that makes the sum smaller
            sum = 0
        }
        sum += x              // 2. ADD the item
        best = max(best, sum) // 3. KEEP the best sum
    }
    return best
}
 
// The same shape with a start index. When the sum goes below zero at i,
// no start from the old start to i can work, so the next candidate is i+1.
func firstGoodStart(gain []int) int {
    start, sum := 0, 0
    for i, g := range gain {
        sum += g
        if sum < 0 {
            start, sum = i+1, 0 // RESET the sum and move the start
        }
    }
    return start
}

The moves are RESET, ADD, then KEEP. Start best with the first item and not with 0. If all the items are negative, the answer is negative too. For a circle, the reset also moves the start to i+1.

Say it

“A negative running sum can only hurt what comes next, so I drop it and start again. One pass, O(n) time and O(1) space.”

Template B: Farthest reach

Signal

Each item tells you how far you can go from its index. The problem asks “can you reach the end” or “in how few jumps”.

// TEMPLATE B: farthest reach. Do not build the path. Keep the farthest
// index in reach.
func canReachEnd(jumps []int) bool {
    farthest := 0
    for i := 0; i < len(jumps); i++ {
        if i > farthest { // 1. CHECK: index i is out of reach
            return false
        }
        farthest = max(farthest, i+jumps[i]) // 2. EXTEND the reach
    }
    return true
}
 
// To count the jumps, read the indexes as BFS levels. The level ends at
// end.
func fewestJumps(jumps []int) int {
    count, end, farthest := 0, 0, 0
    for i := 0; i < len(jumps)-1; i++ { // stop before the last index
        farthest = max(farthest, i+jumps[i]) // EXTEND the next level
        // LEVEL DONE: jump, and start the next level
        if i == end {
            count++
            end = farthest
        }
    }
    return count
}

The moves are CHECK, then EXTEND. To count the jumps, add LEVEL DONE: when the scan reaches the end of the level, count one jump. Stop that loop before the last index. If you do not, the code counts one jump too many.

Say it

“I don’t need the path, only the farthest index I can reach. For the minimum jumps I treat the indexes as BFS levels. It’s O(n) time and O(1) space.”

Template C: Sort, then take the smallest first

Signal

The problem asks you to split the items into groups of consecutive values. The smallest item that is left has only one possible role.

// TEMPLATE C: sort, then take the smallest item first. A count map shows
// what is left.
func canSplitIntoRuns(nums []int, size int) bool {
    if len(nums)%size != 0 {
        return false
    }
    count := make(map[int]int, len(nums))
    for _, x := range nums { // 1. COUNT
        count[x]++
    }
    // 2. SORT: the smallest value that is left must start a run
    sort.Ints(nums)
    for _, x := range nums {
        if count[x] == 0 { // earlier runs used all the copies of x
            continue
        }
        // 3. TAKE the run x, x+1, ... x+size-1
        for v := x; v < x+size; v++ {
            if count[v] == 0 {
                return false
            }
            count[v]--
        }
    }
    return true
}

The moves are COUNT, SORT, then TAKE. The smallest value that is left has no smaller neighbor. So it must be the first item of a group, and the choice is forced. Skip a value when its count is already zero.

Say it

“The smallest card left must start a group, so I sort and build each run from there. The sort makes it O(n log n).”

Template D: Filter, then combine

Signal

An operation such as max only moves values in one direction. Some items can never be in a good answer, and the other items do no harm.

// TEMPLATE D: filter, then combine. Drop the items that can never be in a
// good
// answer. The items that stay are safe to use together.
func canBuild(items [][]int, target []int) bool {
    found := make([]bool, len(target))
    for _, item := range items {
        safe := true
        // 1. FILTER: one bad value drops the item
        for k := 0; k < len(target); k++ {
            if item[k] > target[k] {
                safe = false
            }
        }
        if !safe {
            continue
        }
        // 2. COMBINE: record what the item gives
        for k := 0; k < len(target); k++ {
            if item[k] == target[k] {
                found[k] = true
            }
        }
    }
    for _, ok := range found { // 3. CHECK that each position has a source
        if !ok {
            return false
        }
    }
    return true
}

The moves are FILTER, COMBINE, then CHECK. The filter removes each item that breaks the goal. After the filter, it is safe to use all the other items together. So you do not search for the best subset.

Say it

“A max never goes down, so any triplet above the target is out. I merge all the rest and check that each target value appears.”

Template E: Last index, then extend the end

Signal

Each letter or value must stay in one part. The problem asks for as many parts as possible.

// TEMPLATE E: last index, then extend the end. Cut when the scan reaches
// the end.
func partSizes(s string) []int {
    var last [26]int
    for i := 0; i < len(s); i++ { // 1. LAST INDEX of each letter
        last[s[i]-'a'] = i
    }
    var sizes []int
    start, end := 0, 0
    for i := 0; i < len(s); i++ {
        end = max(end, last[s[i]-'a']) // 2. EXTEND the end of the part
        // 3. CUT: nothing in the part appears later
        if i == end {
            sizes = append(sizes, end-start+1)
            start = i + 1
        }
    }
    return sizes
}

The moves are LAST INDEX, EXTEND, then CUT. The end of the part is the farthest last index of the letters that the scan saw. When the index i is equal to the end, cut. This is the interval merge idea with no interval slice.

Say it

“A part has to hold the last occurrence of every letter in it. I push the end out as I scan and cut when I catch up with it.”

Template F: Range of possible counts

Signal

A wildcard can have more than one meaning, and a brute-force answer tries each meaning. You only need to know if one valid choice exists.

// TEMPLATE F: range of counts. A wildcard makes the count a range from low
// to high.
func validWithWildcard(s string) bool {
    low, high := 0, 0 // the smallest and the largest possible open count
    for i := 0; i < len(s); i++ {
        switch s[i] {
        case '(':
            low, high = low+1, high+1
        case ')':
            low, high = low-1, high-1
        default: // 1. WIDEN: the wildcard is '(' or ')' or nothing
            low, high = low-1, high+1
        }
        if high < 0 { // 2. FAIL: too many ')' in the best case
            return false
        }
        low = max(low, 0) // 3. CLAMP: a count is never negative
    }
    return low == 0
}

The moves are WIDEN, FAIL, then CLAMP. Keep the smallest and the largest possible count, not one count. Fail when high goes below zero. Clamp low at zero, because a negative count is not a valid choice.

Say it

“With a star the open count is a range, so I track its low and high ends. It’s valid if high never drops below zero and low can end at zero.”

Mistakes in this stage

  • best := 0 is wrong for Kadane when all the items are negative. Start with nums[0].
  • sort.Ints sorts the slice in place, so the caller sees the new order. Copy the slice first if the caller needs the old order.
  • In Jump Game II, the loop condition is i < len(nums)-1. With i < len(nums), the code can count one more jump.
  • A greedy choice needs a reason. Say why the local choice is safe before you write the code.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

53. Maximum Subarray

LeetCode 53 · Medium

55. Jump Game

LeetCode 55 · Medium

45. Jump Game II

LeetCode 45 · Medium

134. Gas Station

LeetCode 134 · Medium

846. Hand of Straights

LeetCode 846 · Medium

1899. Merge Triplets to Form Target Triplet

LeetCode 1899 · Medium

763. Partition Labels

LeetCode 763 · Medium

678. Valid Parenthesis String

LeetCode 678 · Medium


← 2-D Dynamic Programming · All 150 problems · Intervals →