Hao's Blog

Software Engineer

Min_stack

| Comments

This is a typical interview question which is going to ask you to implement a stack which can track the max/min value for the current stack. The solution posted here will only show how min-stack is implemented, and max-stack can be developed similarly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require 'pry'
require 'pp'

class Stack
  attr_reader :stack

  def initialize
    @stack = []
  end

  def pop
    @stack.pop
  end

  def push(element)
    @stack.push(element)
  end

  def peek
    @stack[-1]
  end
end

class MinStack
  attr_reader :min_stack, :stack

  def initialize
    @min_stack = Stack.new
    @stack = Stack.new
  end

  def push(element)
    if @stack.peek && @stack.peek < element
      @min_stack.push(@stack.peek)
    else
      @min_stack.push(element)
    end
    @stack.push(element)
  end

  def pop
    @stack.pop
    puts "The minimun is #{@min_stack.pop}"
  end
end

min_stack = MinStack.new
min_stack.push(2)
min_stack.push(5)

Comments