We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
WHATS WRONG with this codecc
> i have insertion as O(n), how can i make it O(1)
importjava.io.*;importjava.util.*;publicclassSolution{staticStack<Integer>stack_S=newStack<>();staticStack<Integer>stack_Q=newStack<>();publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));Stringline;intchoice,data;intquery=Integer.parseInt(br.readLine());for(inti=0;i<query;i++){line=br.readLine();String[]values=line.split("\\s+");choice=Integer.parseInt(values[0]);if(choice==1){data=Integer.parseInt(values[1]);enqueue(data);}else{doTask(choice);}}}publicstaticvoidenqueue(intdata){//enqueat the end of the stack_Sif(stack_S.size()==0){stack_S.push(data);return;}inttopOfStack_S=stack_S.pop();stack_Q.push(topOfStack_S);enqueue(data);//now recursion's turn// now put back in stack_Swhile(stack_Q.size()!=0){stack_S.push(stack_Q.pop());}}publicstaticvoiddoTask(intchoice){if(choice==2){stack_S.pop();}else{System.out.println(stack_S.peek());}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
WHATS WRONG with this codecc
> i have insertion as O(n), how can i make it O(1)