text: Radhekrsna + 15 comments
  ***C++:-
  int N; cin>>N; stack<string>stk; string st; while(N--){ int n; cin>>n; if(n==1){ string str; cin>>str; stk.push(st); st+=str; } else if(n==2){ int k;cin>>k; stk.push(st); st.erase(st.size()-k); } else if(n==3){ int k;cin>>k; cout<<st[k-1]<<endl; } else{ st = stk.top(); stk.pop(); } }
  Dhruv_94 + 1 comment
  If you dont mind me asking you, could you explain why you do this:
  if(n==1){ string str; cin>>str; stk.push(st); // why push the string onto the stack when its //empty? why not after (st+=str) cause then this would append to the string? st+=str; }
  Saisuchith + 4 comments
  here we pushing the before appending a new one because when there will be a undo we can directly take the previous string from stack annd assign this value to present string.
  hope it helps
  badal_bokaro + 1 comment
  if(n==1) { st+=str; stk.push(st); } else if(n==1) { st.erase(st.size()-k); stk.push(st); } else if(n==4) { stk.pop(); st=stk.top(); } just reversing the order of changing the string and pushing it on stack is giving segmentation fault in last few cases..please explain
  grdaukiya1996 + 1 comment
  @adi7tya & @badal_bokaro if u add st in stk before the while it will work correctlly (means adding empty string in stack) or u can add in case 4;;======= else if(x==4) { s.pop(); if(s.empty()) st=""; else {st=s.top();}}
  i think u will understood the reason of segma. fault
  shivamskumar89 + 1 comment
  but the string st is empty.why to push empty string in the stack?
  geethanjali26 + 0 comments
  in case 4 we should undo right..so inorder to do that we should push empty string..then we can add it to the string and make it when we need to undo..even i got the same doubt initially..once u pls trace it u will get that...
  jainhimani1999 + 0 comments
  I think it should give atleast an error as you are inserting completely empty(Not even NULL) string in the stack.
  yudodisdie + 2 comments
  Storing the entire string after every alteration seems redunant, wouldn't it be better to store just the altered part with a flag variable denoting the type of operation last performed?
  Here is my accepted code in python3.
  n = int(input()) stack = [] stri = '' for i in range(n): l = list(input().split()) if(int(l[0]) == 1): stri += str(l[1]) stack.append(len(str(l[1]))) if(int(l[0]) == 2): stack.append(stri[-int(l[1]):]) stri = stri[:-int(l[1])] if(int(l[0]) == 3): print(stri[int(l[1]) - 1]) if(int(l[0]) == 4): x = stack.pop() if(type(x) is int): stri = stri[:-x] else: stri+=x
  jessevsilverman + 0 comments
  I was SO used to requiring optimum solutions or else running out of resources, I only made a comment about storing the whole string for undo. I was totally sure the test cases would add and remove and add and remove 10000 chars repeatedly so we'd die if we weren't smart about it.
  aishik_swarez + 4 comments
  import java.io.; import java.util.;
  public class Solution {
  public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String outputString = ""; Stack<String> stack = new Stack<>(); stack.push(outputString); List<Character> result = new ArrayList<>(); for (int i = 0; i < n; i++) { String append = null; int show = 0; int del = 0; String inp = br.readLine(); String arr[] = inp.split(" "); int opt = Integer.parseInt(arr[0]); switch (opt) { case 1: append = arr[1]; outputString += append; stack.push(outputString); break; case 2: del = Integer.parseInt(arr[1]); outputString = outputString.substring(0, outputString.length() - del); stack.push(outputString); break; case 3: show = Integer.parseInt(arr[1]); result.add(outputString.charAt(show - 1)); break; case 4: stack.pop(); outputString = stack.peek(); } } try { for(Character j:result) System.out.println(j); } catch (Exception e) { } }
  }
  bharath390 + 0 comments
  /*Can some one suggest whats the mistake I made */
  import java.io.; import java.util.;
  public class Solution {
  private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ int q = scanner.nextInt(); StringBuilder sb = new StringBuilder(); Stack st = new Stack(); for(int i=0; i< q; i++){ int oprn = scanner.nextInt(); switch(oprn){ case 1 : { String W = scanner.next(); st.push(sb.toString()); sb.append(W); break; }case 2 : { st.push(sb.toString()); int k = scanner.nextInt(); st.push(sb.toString()); sb.delete(sb.length() - k, k); break; }case 3 :{ int p = scanner.nextInt(); System.out.println(sb.toString().charAt(p-1)); break; }case 4 :{ sb.delete(0, sb.length()); sb.append(st.pop()); break; } } } }
  }
  mali_karabulut + 0 comments
  An improved version is below: 1. StringBuilder is used instead of creating many immutable strings (provides both space and performance improvements) 2. Instead of storing whole string in the stack , only the last update is stored: for additions: +(appended string length), for deletions: (deleted string). This drastically reduces total space used (although adding some extra processing).
  import java.io.; import java.util.; public class Solution {
  public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); Stack<String> stack = new Stack<>(); List<Character> result = new ArrayList<>(); for (int i = 0; i < n; i++) { String append = null; int show = 0; int del = 0; String inp = br.readLine(); String arr[] = inp.split(" "); int opt = Integer.parseInt(arr[0]); switch (opt) { case 1: append = arr[1]; sb.append(append); stack.push("+" + append.length()); // '+' is used to differentiate between append or delete operation break; case 2: del = Integer.parseInt(arr[1]); String delStr = sb.substring(sb.length() - del, sb.length()); sb.delete(sb.length() - del, sb.length()); stack.push(delStr); break; case 3: show = Integer.parseInt(arr[1]); result.add(sb.charAt(show - 1)); break; case 4: String lastOp = stack.pop(); if(lastOp.charAt(0) == '+') { // undo addition sb.delete(sb.length() - Integer.parseInt(lastOp.substring(1)), sb.length()); // omit first character, since it is just append operation marker (+) } else { // undo deletion sb.append(lastOp); } } } try { for(Character j:result) System.out.println(j); } catch (Exception e) { } }
  }
  Imvishalsr + 0 comments
  Good Solution but Is this a preferrable solution for space complexity? I dont think so.
  Ram_Babu93 + 1 comment
  This is Wonderful and Elegant!!!
  I tried using hell a lot of stacks to make the 'Undo' operation work and made it very complex. Thank you! :)
  divya7shahi + 0 comments
  how this last case can help to undo an delete operation I am unable to understand , please clear it. i.e. this part else{ st = stk.top();
  stk.pop(); }
  Lurch_M + 3 comments
  Problem text has two more errors: 1. A typo: instead of "Erase the last k character [...]" it should say "Erase the last k characters [...]" (as in plural) 2. The maximum stated value of Q is 10^5, but that's incorrect, since I had to buy testcase 9 and saw that it has a million queries! So it should say 10^6.
  Freak_1231 + 4 comments
  can't get any shorter i guess
  dic={0:''};order=0;s='' for i in range(int(input())): t=[_ for _ in input().strip().split()] if t[0]=='1':order+=1;s+=t[1];dic[order]=s elif t[0]=='3':print(s[int(t[1])-1]) elif t[0]=='2':s=s[:len(s)-int(t[1])];order+=1;dic[order]=s elif t[0]=='4':order-=1;s=dic[order]
  chaitreyahegde + 1 comment
  What a code! What is that _ for _?Just for is not enough?
  Freak_1231 + 0 comments
  oops...hahah acutally i should'nt have used list comprehension ( i used because i thought i need to convert input list into 'int') should have used t=input().strip().split()...no need of for loops or list comprehension...... nice catch :D .
  kostyanych + 1 comment
  So, istead of just storing increments, you store the whole resulting string on every step, wasting memory space? And you completely miss the "Stack" theme in your code? So what's the use of your code being short then?
  Freak_1231 + 2 comments
  well..wasting memory space???dude space/memory is what you pay for time...if you want your code to give quick and efficient response you use memory rather than cpu computation..also i totally agree i completely miss the stack concept...this is because i want my code to be most efficient and fast..using stack operations like push and pop takes time and cpu (trust me i've sumitted codes using stack that were accurate but it resulted it timeout )...if you're a python programmer timeit my code against yours..i can bet my code will give you quick and efficient result than yours....good day.
  MaheshwariPiyush + 1 comment
  Agree..there is always trade-off between time and space
  kostyanych + 2 comments
  Oh yeah, "simple text editor" is exactly the place to trade time for space - your average "imaginary editor user" requests 100 undos per millisecond and has petabytes of RAM. Really, guys, some common sense is as important as your readiness to time your python code. So is the ability to pay attention to the requirements - while there is no explicit requirement to use stacks, the problem still is in "Data Structures > Stacks" category - shouldn't the solution reflect that?
  Freak_1231 + 1 comment
  i just want to say..you should respect other's thinking...just like 2+2=4 so does 2+1+1... ^_^ and yes i'm a noob coder,i should have used stacks.
  kostyanych + 1 comment
  There's absolutely no problem with being noob, neither is with making mistakes etc.
  But addressing a stranger by "dude" and "babe" and talking about "respect", hmmm...
  Well, to not waste our time any further I will conclude: I never intended to critisize your code or you personally, just wanted you and those who liked your code to notice that it lacks a certaing something, and to notice that shortness of code is not the absolute virtue, but rather the opposite of it, at least if you're doing commercial, not competitive, programming, where many people will have to read your code and will want to understand it with the smallest effort possible - in most applications "wtf per minute" is much more important than the size of the code.
  Good luck to you.
  erbo_xu + 1 comment
  If they had included a test case in which they appended 1 character 10^6 times (which falls within the problem constraints), you would have had to store around 10^12 bytes (1TB) in memory, far larger than is allowed on here. Apparently they didn't push the test cases to the limit.
  That being said, I think your solution is pretty cool, and I would say that it absolutely does use the stack concept.
  Freak_1231 + 0 comments mk9440 + 4 comments
  Simple java Solution : - :D
  public class Solution { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); String s = ""; Stack<String> st =new Stack<String>(); st.push(s); for(int i=0;i<n;i++){ int t=in.nextInt(); if(t==1){ s = s+in.next();st.push(s); } else if(t==2){s=s.substring(0,s.length()-in.nextInt());st.push(s);} else if(t==3){System.out.println(s.charAt(in.nextInt()-1)); } else{st.pop();s=st.peek();}}}}
  Dipak_Prajapati + 1 comment
  thanks man, you solve my problem.
  miguelblcfiguei1 + 0 comments
  nice! But to be even simpler I would have written it with a switch instead of many "else if"s
  Kill_Switch + 1 comment
  Can u just explain what this is doing? else{st.pop();s=st.peek();}}}
  mk9440 + 1 comment
  In this problem,by using stack,the basic idea is to store each modified string after the append or delete operation performed on them. Now the fourth option is to undo last step on string and as the previous modified(last modified) string must be on the top of stack so here we have to pop it(st.pop()).After poping,the top of stack will now point that string which it was before performing the last modification operation (append or delete) on it and we will now store its present top element in s ie s=st.peek()
  tarabahadur_tha1 + 1 comment
  wouldn't it be better to use StringBuffer ?
  juicygranpa + 1 comment
  python3 solution
  n = int(input()) mystring = "" history = [] for i in range(n): myinput = input().strip().split(' ') if myinput[0] == '1': history.append(mystring) mystring = mystring + myinput[1] elif myinput[0] == '2': history.append(mystring) delpos = int(myinput[1]) mypos = len(mystring) - delpos mystring = mystring[0:mypos] elif myinput[0] == '3': mypos = int(myinput[1]) - 1 print(mystring[mypos]) else: mystring = history.pop()
  tusharkailash29 + 1 comment
  hi. what is the use of "history.append(mystring)" ?
  edgard_rodrigo + 0 comments
  It works fine, but I'm getting timeout in tests 8, 9, 10
  public static void main(String[] args) { Scanner s = new Scanner(System.in); Stack<String> history = new Stack<>(); StringBuilder current = new StringBuilder(); int count = s.nextInt(); for (int i = 0; i < count; i++) { int operation = s.nextInt(); switch (operation) { case 1: history.push(current.toString()); current.append(s.next()); break; case 2: history.push(current.toString()); current = new StringBuilder(current.substring(0, current.length() - s.nextInt())); break; case 3: System.out.println(current.charAt(s.nextInt() - 1)); break; case 4: current = new StringBuilder(history.pop()); break; } } }
  How can I make it better?
  miere00 + 0 comments
  I tryied to make a readable one, not actually that short, but still very efficient:
  public class Solution { /* utilities */ static Scanner in = new Scanner(System.in); static void println( String msg, Object...params ){ System.out.println( String.format( msg, params ) ); } static void println( char ch ){ System.out.println( ch ); } /* main */ static final int ADD = 1, DEL = 2, PRINT = 3, UNDO = 4; static final Deque<String> lastStates = new ArrayDeque<>(); static String content = ""; public static void main(String[] args) { int q = in.nextInt(); for ( int i=0; i<q; i++ ) { switch( in.nextInt() ) { case ADD: add(); break; case DEL: del(); break; case PRINT: print(); break; case UNDO: undo(); break; } } } static void add(){ lastStates.push( content ); content+= in.next(); } static void del(){ lastStates.push( content ); int n = in.nextInt(); content = content.substring( 0, content.length() - n ); } static void print(){ int n = in.nextInt(); println( content.charAt(n-1) ); } static void undo(){ content = lastStates.poll(); } }
  Python0222 + 1 comment
  class Stack: def __init__(self): self.name='' self.items=[''] def push(self, char): self.items.append(self.name+char) return self.name+char def delete(self, k): self.name=self.name[:-k] self.items.append(self.name) def undo(self): self.items.pop() self.name=self.items[-1] def is_empty(self): return self.name == '' Q=int(input().strip()) string = Stack() for _ in range(Q): x= input().split() if x[0]=='1': string.name=string.push(x[1]) elif x[0]=='2': string.delete(int(x[1])) elif x[0]=='3': print(string.name[int(x[1])-1]) elif x[0]=='4': string.undo()
  ssjgz + 0 comments
  Fairly weak testcases - a spot-check of the Leaderboard shows that quite a few AC solutions fail the following (constraints-obeying) testcase:
  (Bear in mind that solutions should take up no more than e.g. 512MB RAM for C++ :))
  Sort 264 Discussions, By:
  Please Login in order to post a comment