• + 0 comments

    Optimal pseudocode, if you resolved it but couple tests giving timout exception then, rewrite this to your preffered programming language:

    enQStack = new Stack()
    deQStack = new Stack()
    
    enqueue(num):
    	# push all new elements to enqueue stack O(1)
    	enQStack.push(num)
    
    dequeue():
    	# if dequeue stack has elements pop from it O(1)
    	# else fill dequeue stack with elements from enqueue stack O(n), then pop from it
    	if deQStack is empty:
    		fillDeQStack()
    	deQStack.pop()
    
    peek():
    	# if dequeue stack has elements peek from it O(1)
    	# else fill dequeue stack with elements from enqueue stack O(n), then peek from it
    	if deQStack is empty:
    		fillDeQStack()
    	deQStack.peek()
    
    fillDeQStack():
    	# fill dequeue stack with elements from enqueue stack O(n), dequeue = reversed enqueue
    	while enQStack is not empty:
    		deQStack.push(enQStack.pop())