given the right language and libraries this would probably be a one liner :- https://github.com/careercup/CtCI-6th-Edition-Haskell/blob/master/src/chapter-3/Questions/MinStack.hs