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.
Use a LinkedList instead of an ArrayList when adding/removing items often since it will be faster (ArrayList often needs to shift O(n) elements after an add or remove, which is slow).
importjava.util.Scanner;importjava.util.LinkedList;publicclassSolution{publicstaticvoidmain(String[]args){/* Create and fill Linked List of Integers */Scannerscan=newScanner(System.in);intN=scan.nextInt();LinkedList<Integer>list=newLinkedList<>();for(inti=0;i<N;i++){intvalue=scan.nextInt();list.add(value);}/* Perfrom queries on Linked List */intQ=scan.nextInt();for(inti=0;i<Q;i++){Stringaction=scan.next();if(action.equals("Insert")){intindex=scan.nextInt();intvalue=scan.nextInt();list.add(index,value);}else{// "Delete"intindex=scan.nextInt();list.remove(index);}}scan.close();/* Print our updated Linked List */for(Integernum:list){System.out.print(num+" ");}}}
Java List
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
Use a LinkedList instead of an ArrayList when adding/removing items often since it will be faster (ArrayList often needs to shift O(n) elements after an add or remove, which is slow).
From my HackerRank solutions.
Let me know if you have any questions.