Skip to content
advanced

Review: the minimum that survives nothing

This is recall. The code looks finished and is wrong. Find the defect and fix it. You are graded on tests you cannot see.

A telemetry widget wants the smallest value seen recently, so someone added a `min()` to a stack. It tracks the minimum in a single field, updated on every push. Its tests pass — push values, read the minimum, pop a few, read it again, all correct.

/**
 * A stack of numbers that can also report its smallest value in
 * constant time.
 */
export class MinStack {
  #values: number[] = []
  #min: number | undefined = undefined

  push(value: number): void {
    this.#values.push(value)
    if (this.#min === undefined || value < this.#min) {
      this.#min = value
    }
  }

  pop(): number | undefined {
    return this.#values.pop()
  }

  peek(): number | undefined {
    return this.#values.at(-1)
  }

  min(): number | undefined {
    return this.#min
  }
}
review — find the defectCtrl+↵ submits · Ctrl+Shift+↵ runsstarter code