Skip to content

Commit

Permalink
CTCI 3.2: MinStack.groovy
Browse files Browse the repository at this point in the history
  • Loading branch information
Pap Lőrinc committed Feb 10, 2016
1 parent 0840091 commit c519e63
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/main/groovy/Ch03_StacksAndQueues/_3_2_MinStack.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package Ch03_StacksAndQueues

import Ch03_StacksAndQueues.utils.Stack

/** Create stack with O(1) minimum */
class MinStack<T> extends Stack<T> {
private final mins = new Stack<T>()

@Override void push(T value) {
(mins.empty || (value <= peekMin())) && mins.push(value) /* equal elements have to be repeated */
super.push(value)
}
@Override T pop() {
(peek() == peekMin()) && mins.pop()
super.pop()
}
T peekMin() { mins.peek() }
}
28 changes: 28 additions & 0 deletions src/test/groovy/Ch03_StacksAndQueues/_3_2_MinStackTest.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package Ch03_StacksAndQueues

import spock.lang.Specification

import static java.lang.Math.*

class _3_2_MinStackTest extends Specification {
/*@formatter:off*/
def 'minStack?'() {
given: def source = "$PI$E".toList()

when: 'a new stack is empty'
def stack = new MinStack()
then: stack.empty

when: 'consuming a stack yields the correct value and min'
source.reverseEach {
stack.push(it)
assert !stack.empty
}
then: source.eachWithIndex { value, i ->
assert stack.peekMin() == source[i..<source.size()].min()
assert stack.pop() == value
}
stack.empty
}
/*@formatter:on*/
}

0 comments on commit c519e63

Please sign in to comment.