From 11c0f5464c6dcf481a62689f7b94e45c66dc379c Mon Sep 17 00:00:00 2001 From: Anilkumar9553625395 <98652664+Anilkumar9553625395@users.noreply.github.com> Date: Fri, 14 Nov 2025 19:42:37 -0500 Subject: [PATCH] Design-2 --- Sample.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/Sample.java b/Sample.java index 1739a9cb..69654d61 100644 --- a/Sample.java +++ b/Sample.java @@ -1,7 +1,60 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : +// Time Complexity : O(1) amortized for push, pop, peek +// Space Complexity : O(n) where n is the number of elements in the queue +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : No // Your code here along with comments explaining your approach + +I created two stacks and +used one staack for pushing and other for poping and peeking. +When pop or peek is called, I checked if the outStack is empty.If it is empty, I transferred all elements from inStack to outStack. + +class MyQueue { + private Stack inStack; + private Stack outStack; + + public MyQueue() { + inStack= new Stack(); + outStack= new Stack(); + } + + public void push(int x) { + inStack.push(x); + + } + + public int pop() { + if(outStack.isEmpty()){ + while(!inStack.isEmpty()){ + outStack.push(inStack.pop()); + } + } + return outStack.pop(); + } + + public int peek() { + if(outStack.isEmpty()){ + while(!inStack.isEmpty()){ + outStack.push(inStack.pop()); + } + } + return outStack.peek(); + } + + public boolean empty() { + if(outStack.isEmpty()&&inStack.isEmpty()){ + return true; + } + return false; + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */