Uber | Phone Screen | Sr Software Engineer
Company: Uber
Role: Senior Software Engineer
Interview Stage: Phone Screen
Location: unknown
Year: unknown
Original Post Content:
MinStack:pop()popMin(): pop (i.e. remove) the minimum integer within the stackpush(): return false if an integer is already present in the stack, return true if integer did not exist previously and push the integer on top of the stack.
Answer:
I did this in Java, so used a Custom Doubly Linked List and a TreeMap
The DLL had a head and tail, elements were inserted removed from it.
The TreeMap maintained the <Key : value, Value: Reference to the item in DLL>
The DLL helps us maintain the stack order.
The Map helps us get the minimum in a cheaper way.
Please let me know if the solution could be any better.
class Solution { static Node head, tail; static TreeMap<Integer, Node> map; public Solution () { head = new Node(); tail = new Node(); head.next = tail; tail.prev = head; map = new TreeMap<>(); } public static boolean push(int value) { if (map.containsKey(value)) { return false; } Node newNode = new Node(value); newNode.prev = tail.prev; newNode.prev.next = newNode; newNode.next = tail; tail.prev = newNode; map.put(value, newNode); return true; } public static int popMin() throws Exception { if (map.size() == 0) throw new Exception("no items in stack"); int min = map.firstKey(); Node minNode = map.get(min); minNode.prev.next = minNode.next; minNode.next.prev = minNode.prev; map.remove(min); minNode = null; return min; } public static int pop() throws Exception { if (map.size() == 0) throw new Exception("no items in stack"); Node popNode = head.next; int item = popNode.val; head.next = popNode.next; popNode.next.prev = head; map.remove(item); popNode = null; return item; }}class Node { int val; Node next; Node prev; public Node() { } public Node(int val) { this.val = val; this.next = null; this.prev = null; }}