Chapter 16 - Greedy

Take the best choice right now and never come back to it. Simple to code, harder to trust.

Coding Interview Patterns book cover with the Rust logo and a CHAP 16 label, the chapter on greedy

This page is the entry point of chapter 16 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

A greedy algorithm makes the locally optimal choice at each step: jump as far as possible, start after the station where the tank went negative, give one more candy than the neighbor. The code is short and usually \(O(n)\). The difficulty is elsewhere: a greedy choice is only correct when we can argue that it never prevents the optimal solution. When no such argument exists, dynamic programming is often the safer route.

When to reach for it

  • A single pass seems enough, and earlier choices never need to be revised.
  • Reachability or minimum number of steps (jump game).
  • Constraints with neighbors that can be satisfied in two passes, left to right then right to left.

In Rust

  • iter().enumerate() gives index and value together; .rev() makes the second pass trivial.
  • Keep running values in plain variables: greedy algorithms rarely need more than a few of them.
  • Write a brute force version first on small inputs and compare: it is the cheapest way to catch a wrong greedy idea.

Problems in this chapter

  • p354 - Jump to the End: Jump to the End (Greedy) solved in Rust: each number is the maximum jump from its index. Can we reach the end of the array from index 0?
  • p358 - Gas Stations: Gas Stations (Greedy) solved in Rust: on a circular route, find the gas station to start from to complete the circuit without running out of gas.
  • p364 - Candies: Candies (Greedy), solved in Rust. Children sitting in a row. Distribute candies while abiding the rules. Determine the minimum number of candies needed.

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude