Created
July 30, 2018 15:58
-
-
Save asethia/f9292b45504dd8fbc8c0186d104ad085 to your computer and use it in GitHub Desktop.
Design a stack which, in addition to push and pop, has a function min which returns the minimum element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Design a stack which, in addition to push and pop, has a function min which returns the minimum element. | |
* Push, pop and min should all operate in 0(1) time. | |
* Created by Arun Sethia on 7/29/18. | |
*/ | |
case class MinStack(data: List[Int], min: Int) { | |
/** | |
* | |
* @param elem | |
* @return | |
*/ | |
def push(elem: Int) = { | |
val (dataAdd, minimum) = findMinimumAndData(elem, min) | |
MinStack(dataAdd :: data, minimum) | |
} | |
/** | |
* find new data and minimum | |
* | |
* @param newData | |
* @param currentMin | |
* @return | |
*/ | |
def findMinimumAndData(newData: Int, currentMin: Int): (Int, Int) = { | |
if (min == 0) (newData, newData) | |
else if (newData > min) (newData, currentMin) | |
else ((newData - currentMin), newData) | |
} | |
/** | |
* | |
* @return | |
*/ | |
def pop() = data match { | |
case h :: _ => { | |
val (poppedItem, newMin) = if (h < min) (min, (min - h)) else (h, min) | |
println(s"pop:: ${poppedItem} and new minimum:${newMin}") | |
MinStack(data.tail, newMin) | |
} | |
case Nil => throw new UnsupportedOperationException("stack is empty") | |
} | |
override def toString() = s"Minimum:${min}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment