├── Arrays ├── Runner.java ├── module-info.java ├── reverse.java ├── runner1.java └── runner2.java ├── BigInteger ├── BigDecimal.java └── bigInteger.java ├── DP-1 ├── FibonacciDp.java ├── MinStepToOneRecursive.java ├── MinStepstoOneusingDP.java ├── MinStepstoOneusingMemoization.java ├── MinimumCountofSquaresDP.java ├── NumberofBalancedBTsRecursion.java ├── NumberofBalancedBTsUsingDP.java ├── StaircaseMemoization.java └── Staircasedp.java ├── DP-2 ├── EditDistanceDP.java ├── EditDistanceMemoization.java ├── EditDistanceRecurtion.java ├── KnapsackRecurtion.java ├── LongestCommonSubsequenceDP.java ├── LongestCommonSubsequenceMemoization.java ├── LongestCommonSubsequenceRecurtion.java ├── LootHousesDP.java ├── LootHousesMemoization.java ├── LootHousesRecursion.java ├── MatrixChainMultiplicationRecurtion.java ├── MaximumSquareMatrixWithAllZeros.java ├── MinimumCostPathDP.java ├── MinimumCostPathMemoiaztion.java ├── MinimumCostPathRecursion.java └── ShortestSubsequenceRecurtion.java ├── Graphs ├── AllconnectedcomponentsDFS.java ├── GetPathBFS.java ├── GetPathDFS.java ├── HasPath.java ├── IsConnectedDfs.java └── bfsTraversal.java ├── HashMaps └── src │ ├── Map.java │ ├── MapNode.java │ ├── MapUse.java │ ├── MaximumFrequencyNumber.java │ ├── MaximumFrequencyNumberUsingLinkedHashMap.java │ ├── OurMapUse.java │ ├── hashmapVVhashtable.java │ ├── important.java │ ├── linkedhashmap.java │ └── removeDuplicates.java ├── Library └── BufferedReader.java ├── Linked List └── src │ ├── ArrayListDemo.java │ ├── LinkedListUse.java │ └── Node.java ├── Methods └── ArrayList.java ├── Priority Queues ├── BuyTheTicket.java ├── CheckMaxHeap.java ├── InPlaceHeapSort.java ├── KlargestElements.java ├── MaxPriorityQueueImplementation.java ├── MinPriorityQueueImplementation.java ├── PriorityQueueUse.java ├── PriorityQueueUse_Comparator.java ├── Runningmedian.java ├── SortKsorted.java ├── important.java └── kthLargest.java ├── README.md ├── Stack and Queue ├── bin │ ├── BalancedParenthesis.class │ ├── Node.class │ ├── QueueEmptyException.class │ ├── QueueFullException.class │ ├── QueueUse.class │ ├── QueueUsingArray.class │ ├── Queueusell.class │ ├── StackFullException.class │ ├── StackUse.class │ ├── StackUseLinkedlist.class │ ├── StackUsingArray.class │ ├── StackUsingLL.class │ └── queueusingll.class └── src │ ├── BalancedParenthesis.java │ ├── MinimumbracketReversal.java │ ├── Node.java │ ├── QueueEmptyException.java │ ├── QueueFullException.java │ ├── QueueUse.java │ ├── QueueUsingArray.java │ ├── Queueusell.java │ ├── ReverseStack.java │ ├── StackEmptyException.java │ ├── StackFullException.java │ ├── StackUse.java │ ├── StackUseLinkedlist.java │ ├── StackUsingArray.java │ ├── StackUsingLL.java │ ├── checkRedundantBrackets.java │ ├── queue important.java │ ├── queueusingll.java │ ├── reversequeue.java │ ├── stack important.java │ └── stockSpan.java ├── TEST 2 ├── Deletealternatenodes.java ├── Dequeue.java └── NextNumber.java ├── Trees └── src │ ├── BinaryTrees │ ├── BinaryTreeNode.java │ ├── BinaryTrees.java │ ├── ConstructTreefromPostorderandInorder.java │ ├── ConstructTreefromPreorderAndInorder.java │ ├── Levelwiselinkedlist.java │ ├── Node.java │ ├── Pair.java │ ├── QueueEmptyException.java │ └── QueueUsingLL.java │ ├── Node.java │ ├── QueueEmptyException.java │ ├── QueueUsingLL.java │ ├── TreeNode.java │ ├── TreeUse.java │ └── binarysearchtree │ ├── BinarySearchTree.java │ ├── BinaryTreeNode.java │ ├── BinaryTreeUse.java │ ├── Pair.java │ └── PathSumRoottoLeaf.java ├── Tries and Huffman Coding ├── Autocomplete.java ├── PalindromePair.java ├── PatternMatching.java └── SearchWordsInTries.java ├── codechef └── src │ └── codechef │ ├── EVENT.java │ ├── MDL.java │ ├── Main.java │ ├── Strch.java │ ├── Test.java │ ├── atm.java │ ├── bstops.java │ ├── chnum.java │ ├── jj.java │ └── modulo.java ├── objectoriented └── src │ ├── objectoriented │ ├── ComplexNumbers.java │ ├── DynamicArray.java │ ├── DynamicArrayUse.java │ ├── Fraction.java │ ├── FractionUse.java │ ├── Polynomial.java │ ├── PolynomialUse.java │ ├── Runner.java │ ├── Student.java │ └── StudentUse.java │ ├── readme.java │ └── access Modifiers │ └── vehicle │ ├── Car.java │ ├── Vehicle.java │ └── VehicleUse.java ├── read ├── Break.java ├── arraylist,java ├── long.java └── queue important.java ├── recursion ├── Binarysearch.java ├── CheckSorted.java ├── PrintSubsequences.java ├── Printkeypadcode.java ├── Returnkeypadcode.java ├── Returnsubsetonarray.java ├── Subsequences.java └── check.java ├── sorting └── src │ └── sorting │ ├── Bubble_Sorting.java │ ├── Heapsort.java │ ├── Insertion_sorting.java │ ├── Quicksort.java │ ├── Selection_Sorting.java │ └── mergsort.java ├── strings └── src │ └── strings │ ├── reverseeach.java │ ├── solution1.java │ └── spiral.java └── testing └── src ├── Runner.java ├── Solution.java ├── a.java ├── sss.java └── sw.java /Arrays/Runner.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Runner { 4 | public static void main(String[] args) { 5 | Scanner s = new Scanner(System.in); 6 | String input = s.next(); 7 | System.out.println(removeConsecutiveDuplicates(input)); 8 | } 9 | 10 | 11 | public static String removeConsecutiveDuplicates(String input) { 12 | char a=input.charAt(0); 13 | String ans =""+input.charAt(0); 14 | for(int i=0;iinput[j]?input[j]:input[i]; 31 | min1=min>input[k]?input[j]:input[i]; 32 | System.out.println(); 33 | } 34 | 35 | } 36 | 37 | } 38 | } 39 | }} -------------------------------------------------------------------------------- /Arrays/runner2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.Scanner; 3 | 4 | public class runner2 { 5 | 6 | public static int[] takeInput() { 7 | Scanner s = new Scanner(System.in); 8 | int size = s.nextInt(); 9 | int arr[] = new int[size]; 10 | for (int i = 0; i < size; i++) { 11 | arr[i] = s.nextInt(); 12 | } 13 | return arr; 14 | } 15 | 16 | public static void main(String[] args) { 17 | int[] arr = takeInput(); 18 | System.out.print(secondLargestElement(arr)); 19 | } 20 | 21 | 22 | public static int secondLargestElement(int[] arr) { 23 | int i,j,k=0,max=0; 24 | if(arr.length<=1){ 25 | return -2147483648; 26 | } 27 | 28 | 29 | for(i=0;i0) 8 | storage[1]=1; 9 | if(n>1) 10 | storage[2]=2; 11 | if(n>2) 12 | storage[3]=3; 13 | for(int i=4;i<=n;i++){ 14 | int num=(int)Math.sqrt(i); 15 | int ans=Integer.MAX_VALUE; 16 | while(num>0){ 17 | int remaning=i-(num*num); 18 | int sum=1+storage[remaning]; 19 | num--; 20 | if(ans>sum){ 21 | ans=sum; 22 | } 23 | storage[i]=ans; 24 | } 25 | } 26 | return storage[n]; 27 | } 28 | } 29 | // below is the solution 30 | // public class Solution { 31 | // public static int minCount(int n) { 32 | // // count[i] - represents minimum count of squares for integer n 33 | // if(n <= 3) { 34 | // return n; 35 | // } 36 | // int count[]=new int[n + 1]; 37 | // count[0] = 0; 38 | // count[1] = 1; 39 | // count[2] = 2; 40 | // count[3] = 3; 41 | // for(int i = 4; i <= n; i++) { 42 | // int ans = i; 43 | // for(int j = 1; j <= i/2; j++) { 44 | // int k = i - (j * j); 45 | // if(k >= 0) 46 | // ans = Math.min(ans, count[k] + 1); 47 | // } 48 | // count[i] = ans; 49 | // } 50 | // return count[n]; 51 | // } 52 | // } 53 | -------------------------------------------------------------------------------- /DP-1/NumberofBalancedBTsRecursion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int countBalancedBTs(int h){ 3 | int mod = (int)Math.pow(10, 9) + 7; 4 | return countBalancedBTs(h, mod); 5 | } 6 | 7 | public static int countBalancedBTs(int h, int mod){ 8 | 9 | if(h == 0 || h == 1){ 10 | return 1; 11 | } 12 | 13 | int x = countBalancedBTs( h - 1); 14 | int y = countBalancedBTs(h - 2); 15 | long res1 = (long)x * x; 16 | long res2 = (long)x * y * 2; 17 | int value1 = (int)(res1 % mod); 18 | int value2 = (int)(res2 % mod); 19 | return (value1 + value2) % mod; 20 | } 21 | 22 | public static int balancedTreesOfHeightH(int height){ 23 | 24 | int ans = countBalancedBTs(height); 25 | return ans; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /DP-1/NumberofBalancedBTsUsingDP.java: -------------------------------------------------------------------------------- 1 | // below is my code 2 | // public class Solution { 3 | 4 | // public static int countBalancedBTs(int h){ 5 | // int mod = (int)Math.pow(10, 9) + 7; 6 | // return help(h, mod); 7 | // } 8 | 9 | // public static int help(int height,int mod){ 10 | // if(height==1||height==0){ 11 | // return 1; 12 | // } 13 | // int storage[]=new int[height+1]; 14 | // storage[0]=1; 15 | // storage[1]=1; 16 | // // int x=balancedTreesOfHeightH(height-1); 17 | // // int y=balancedTreesOfHeightH(height-2); 18 | // for(int i=2;i<=height;i++){ 19 | // int x=storage[i-1]; 20 | // int y=storage[i-2]; 21 | // long res1 = (long)x * x; 22 | // long res2 = (long)x * y * 2; 23 | // int value1 = (int)(res1 % mod); 24 | // int value2 = (int)(res2 % mod); 25 | // int total = (value1 + value2) % mod; 26 | // storage[i]=total; 27 | // } 28 | // return storage[height]; 29 | 30 | // } 31 | // public static int balancedTreesOfHeightH(int height){ 32 | // if(height==1||height==0){ 33 | // return 1; 34 | // } 35 | // int mod=countBalancedBTs(height); 36 | // return mod; 37 | 38 | // } 39 | // } 40 | // below is the solution 41 | public class Solution { 42 | public static int balancedTreesOfHeightH(int height){ 43 | if(height == 0){ 44 | return 1; 45 | } 46 | int storage[] = new int[height + 1]; 47 | storage[0] = storage[1] = 1; 48 | int mod = (int) Math.pow(10, 9) + 7; 49 | for(int i = 2; i <= height; i++){ 50 | // Cast to long 51 | long temp1 = (long) (storage[i- 1]) * storage[ i - 1]; 52 | temp1 = temp1 % mod; 53 | // Cast to long 54 | long temp2 = 2 * (long) (storage[i - 1]) * storage[ i - 2]; 55 | temp2 = temp2 % mod; 56 | storage[i] = (int) (temp1 + temp2) % mod; 57 | } 58 | return storage[height]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /DP-1/StaircaseMemoization.java: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | public static long ans(int n){ 3 | long storage[] = new long[n+1]; 4 | for(int i = 0; i <= n; i++){ 5 | storage[i] = -1; 6 | } 7 | return ans(n,storage); 8 | } 9 | public static long ans(int n,long storage[]){ 10 | if(n==0){ 11 | storage[n]=0; 12 | return storage[n]; 13 | }if(n==1){ 14 | storage[1]=1; 15 | return storage[n]; 16 | }if(n==2){ 17 | storage[n]=2; 18 | return storage[n]; 19 | }if(n==3){ 20 | storage[n]=4; 21 | return storage[n]; 22 | } 23 | if(storage[n]!=-1){ 24 | return storage[n]; 25 | } 26 | long opt1=0; 27 | long opt2=0; 28 | long opt3=0; 29 | opt1=ans(n-1); 30 | opt2=ans(n-2); 31 | opt3=ans(n-3); 32 | long answer=opt1+opt2+opt3; 33 | storage[n]=answer; 34 | return storage[n]; 35 | } 36 | public static long staircase(int n){ 37 | return ans(n); 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /DP-1/Staircasedp.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static long staircase(int n){ 3 | long steps[] = new long[n + 1]; 4 | steps[0]=1; 5 | if(n>0) 6 | steps[1]=1; 7 | if(n>1) 8 | steps[2]=2; 9 | if(n>2) 10 | steps[3]=4; 11 | for(int i=4;i<=n;i++){ 12 | long count1,count2 = 0, count3 = 0; 13 | count1 = steps[i-1]; 14 | count2 = steps[i-2]; 15 | count3 = steps[i-3]; 16 | steps[i] = count1+count2+count3; 17 | } 18 | return steps[n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /DP-2/EditDistanceDP.java: -------------------------------------------------------------------------------- 1 | public class EditDistance { 2 | public static int editDistanceDP(String s, String t){ 3 | int m = s.length(); 4 | int n = t.length(); 5 | int storage[][] = new int[ m + 1][n + 1]; 6 | for(int j = 0; j <= n; j++){ 7 | storage[0][j] = j; 8 | } 9 | for(int i = 0; i <= m; i++){ 10 | storage[i][0] = i; 11 | } 12 | 13 | for(int i = 1; i <= m; i++){ 14 | for(int j = 1; j <= n; j++){ 15 | if(s.charAt(m - i) == t.charAt(n - j)){ 16 | // last m-i character and n-j th character 17 | storage[i][j] = storage[i - 1][j - 1]; 18 | }else{ 19 | storage[i][j] = 1 + Math.min(storage[i][j - 1], Math.min(storage[i - 1][j], storage[i - 1][j - 1])); 20 | } 21 | } 22 | } 23 | return storage[m][n]; 24 | } 25 | -------------------------------------------------------------------------------- /DP-2/EditDistanceMemoization.java: -------------------------------------------------------------------------------- 1 | public class EditDistance { 2 | public static int editDistanceM(String s, String t){ 3 | int m = s.length(); 4 | int n = t.length(); 5 | int storage[][] = new int[ m + 1][n + 1]; 6 | for(int i = 0; i <= m; i++){ 7 | for(int j = 0; j <= n; j++){ 8 | storage[i][j] = -1; 9 | } 10 | } 11 | return editDistanceM(s,t,storage); 12 | } 13 | 14 | 15 | private static int editDistanceM(String s, String t, int[][] storage) { 16 | int m = s.length(); 17 | int n = t.length(); 18 | if(storage[m][n] != -1){ 19 | return storage[m][n]; 20 | } 21 | 22 | if(m == 0){ 23 | storage[m][n] = n; 24 | return storage[m][n]; 25 | } 26 | if(n == 0){ 27 | storage[m][n] = m; 28 | return storage[m][n]; 29 | } 30 | if(s.charAt(0) == t.charAt(0)){ 31 | storage[m][n] = editDistanceM(s.substring(1), t.substring(1), storage); 32 | }else{ 33 | // insert 34 | int op1 = editDistanceM(s, t.substring(1), storage); 35 | // delete 36 | int op2 = editDistanceM(s.substring(1), t, storage); 37 | //substitute 38 | int op3 = editDistanceM(s.substring(1), t.substring(1), storage); 39 | storage[m][n] = 1 + Math.min(op1, Math.min(op2, op3)); 40 | } 41 | return storage[m][n]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /DP-2/EditDistanceRecurtion.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public static int help(String s1, String s2){ 4 | if(s1.length() == 0){ 5 | return s2.length(); 6 | } 7 | if(s2.length() == 0){ 8 | return s1.length(); 9 | } 10 | // abs and empty then other length 11 | if(s1.charAt(0)==s2.charAt(0)){ 12 | return help(s1.substring(1),s2.substring(1)); 13 | } 14 | //insertion 15 | int opt1=help(s1,s1.charAt(0)+s2); 16 | //delition 17 | int opt2=help(s1,s2.substring(1)); 18 | //substitution 19 | int opt3=help(s1,s1.charAt(0)+s2.substring(1)); 20 | 21 | int answer=1+Math.min(opt1,Math.min(opt3,opt2)); 22 | return answer; 23 | 24 | } 25 | // both the method are same just the above method is same 26 | // public static int editDistances(String s, String t){ 27 | // if(s.length() == 0){ 28 | // return t.length(); 29 | // } 30 | // if(t.length() == 0){ 31 | // return s.length(); 32 | // } 33 | 34 | // if(s.charAt(0) == t.charAt(0)){ 35 | // return editDistance(s.substring(1), t.substring(1)); 36 | // }else{ 37 | // // insert 38 | // int op1 = editDistance(s, t.substring(1)); 39 | // // delete 40 | // int op2 = editDistance(s.substring(1), t); 41 | // //substitute 42 | // int op3 = editDistance(s.substring(1), t.substring(1)); 43 | // return 1 + Math.min(op1, Math.min(op2, op3)); 44 | // } 45 | // } 46 | public static int editDistance(String s1, String s2){ 47 | return help(s1,s2); 48 | // return editDistances(s1,s2); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /DP-2/KnapsackRecurtion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int help(int[] weight,int value[],int index,int maxweight, int n){ 3 | if(maxweight==0||n<=index){ 4 | return 0; 5 | } 6 | 7 | if(weight[index]>maxweight){ 8 | return help(weight,value,1+index,maxweight,n); 9 | } 10 | int opt1 = value[index]+help(weight,value,++index,maxweight-weight[index],n); 11 | int opt2 = help(weight,value,++index,maxweight,n); 12 | return Math.max(opt1,opt2); 13 | 14 | } 15 | public static int knapsack(int[] weight,int value[],int maxWeight, int n){ 16 | return help(weight,value,0,maxWeight,n); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /DP-2/LongestCommonSubsequenceDP.java: -------------------------------------------------------------------------------- 1 | public class LCS { 2 | public static int lcsM(String s, String t, int[][] storage) { 3 | int m = s.length(); 4 | int n = t.length(); 5 | int storage[][] = new int[s.length() + 1][t.length() + 1]; 6 | for(int i=0;i<=m;i++){ 7 | storage[i][0]=0; 8 | } 9 | for(int i=0;i<=n;i++){ 10 | storage[0][i]=0; 11 | } 12 | for(int i=1;i<=m;i++){ 13 | for(int j=1;j<=n;j++){ 14 | if(s.charAt(m-i)==t.charAt(n-j)){ 15 | storage[i][j]=1+storage[i-1][j-1]; 16 | }else{ 17 | storage[i][j]=Math.max(storage[i][j-1],storage[i-1][j]); 18 | } 19 | } 20 | } 21 | return storage[m][n]; 22 | } 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /DP-2/LongestCommonSubsequenceMemoization.java: -------------------------------------------------------------------------------- 1 | public class LCS { 2 | 3 | public static int lcsM(String s, String t){ 4 | int storage[][] = new int[s.length() + 1][t.length() + 1]; 5 | for(int i = 0; i < s.length() + 1; i++){ 6 | for(int j = 0; j < t.length() + 1; j++){ 7 | storage[i][j] = -1; 8 | } 9 | } 10 | return lcsM(s, t, storage); 11 | } 12 | 13 | private static int lcsM(String s, String t, int[][] storage) { 14 | int m = s.length(); 15 | int n = t.length(); 16 | 17 | if(storage[m][n] != -1){ 18 | return storage[m][n]; 19 | } 20 | if(m == 0 || n == 0){ 21 | storage[m][n] = 0; 22 | return storage[m][n]; 23 | } 24 | if(s.charAt(0) == t.charAt(0)){ 25 | storage[m][n] = 1 + lcsM(s.substring(1), t.substring(1), storage); 26 | }else{ 27 | int op1 = lcsM(s, t.substring(1), storage); 28 | int op2 = lcsM(s.substring(1), t, storage); 29 | storage[m][n] = Math.max(op1, op2); 30 | } 31 | return storage[m][n]; 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /DP-2/LongestCommonSubsequenceRecurtion.java: -------------------------------------------------------------------------------- 1 | public class LCS { 2 | public static int lcs(String s, String t){ 3 | if(s.length() == 0 || t.length() == 0){ 4 | return 0; 5 | } 6 | if(s.charAt(0) == t.charAt(0)){ 7 | return 1 + lcs(s.substring(1), t.substring(1)); 8 | } 9 | else{ 10 | int op1 = lcs(s, t.substring(1)); 11 | int op2 = lcs(s.substring(1), t); 12 | return Math.max(op1, op2); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /DP-2/LootHousesDP.java: -------------------------------------------------------------------------------- 1 | // in this approach we will go from last element to first 2 | // example 3 | // 5 2 6 3 4 5 4 | // first we add 3+5 and add it to storage at 3 place 5 | // now we add and repate 6 | public class Solution { 7 | public static int help(int arr[], int n,int i){ 8 | int storage[]=new int[arr.length]; 9 | storage[i]=arr[arr.length-1]; 10 | storage[i-1]=arr[arr.length-2]; 11 | storage[i-2]=arr[arr.length-3]+storage[i]; 12 | i=i-3; 13 | while(i>-1){ 14 | storage[i]=arr[i]+Math.max(storage[i+2],storage[i+3]); 15 | i--; 16 | } 17 | return Math.max(storage[0],storage[1]); 18 | } 19 | public static int getMaxMoney(int arr[], int n){ 20 | return help(arr,n,arr.length-1); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DP-2/LootHousesMemoization.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public static int helpp(int arr[], int n,int i){ 4 | int storage[]=new int[arr.length+1]; 5 | 6 | for(int j=0;j=n){ 13 | return 0; 14 | } 15 | if(storage[i]!=-1){ 16 | return storage[i]; 17 | } 18 | int opt1=arr[i]+help(arr,n,i+2,storage); 19 | int opt2=0; 20 | if(!(i+1>=n)){ 21 | opt2=arr[i+1]+help(arr,n,i+3,storage); 22 | } 23 | storage[i]=Math.max(opt1,opt2); 24 | return storage[i]; 25 | } 26 | public static int getMaxMoney(int arr[], int n){ 27 | return helpp(arr,n,0); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /DP-2/LootHousesRecursion.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public static int help(int arr[], int n,int i){ 4 | if(i>=n){ 5 | return 0; 6 | } 7 | int opt1=arr[i]+help(arr,n,i+2); 8 | int opt2=0; 9 | if(!(i+1>=n)){ 10 | opt2=arr[i+1]+help(arr,n,i+3); 11 | } 12 | return Math.max(opt1,opt2); 13 | } 14 | public static int getMaxMoney(int arr[], int n){ 15 | return help(arr,n,0); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DP-2/MatrixChainMultiplicationRecurtion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int help(int[] p,int s,int e){ 3 | if(s>=e||s+1==e){ 4 | return 0; 5 | } 6 | // take the first matrix and all other 7 | int opt1=help(p,s,s+1)+help(p,s+1,e)+(p[s]*p[s+1]*p[e]); 8 | // take the full matrix-last matrix and take the last matrix 9 | int opt2=help(p,s,e-1)+help(p,e-1,e)+(p[s]*p[e-1]*p[e]); 10 | return Math.min(opt1,opt2); 11 | } 12 | 13 | public static int mcm(int[] p){ 14 | return help(p,0,p.length-1); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DP-2/MaximumSquareMatrixWithAllZeros.java: -------------------------------------------------------------------------------- 1 | // find tht largest 2 | import java.util.*; 3 | public class Solution { 4 | public static int findMaxSquareWithAllZeros(int[][] input){ 5 | int storage[][]=new int[input.length][input[0].length]; 6 | int ans=0; 7 | // first fill the rows 8 | // if in input array ,at that place if it is 1 then put 0 in storage array because there is no matrix required for zeros 9 | for(int i=0;i= 0; j--){ 9 | storage[m - 1][j] = storage[m - 1][j + 1] + arr[m - 1][j]; 10 | } 11 | // Last Column 12 | for(int i = m - 2; i >= 0; i--){ 13 | storage[i][n - 1] = storage[i + 1][n - 1] + arr[i][n - 1]; 14 | } 15 | 16 | for(int i = m - 2; i >= 0; i--){ 17 | for(int j = n - 2; j >= 0; j--){ 18 | storage[i][j] = arr[i][j] + Math.min(storage[i][j + 1],Math.min(storage[i + 1][j + 1], storage[i + 1][j])); 19 | } 20 | } 21 | return storage[0][0]; 22 | } 23 | -------------------------------------------------------------------------------- /DP-2/MinimumCostPathMemoiaztion.java: -------------------------------------------------------------------------------- 1 | //memeoization 2 | public class Solution { 3 | public static int minCostPath(int arr[][]){ 4 | int m = arr.length; 5 | int n = arr[0].length; 6 | int storage[][] = new int[m][n]; 7 | for(int i = 0; i < m ; i++){ 8 | for(int j = 0; j < n; j++){ 9 | storage[i][j] = -1; 10 | } 11 | } 12 | return minCostPathM(arr, 0, 0, storage); 13 | } 14 | 15 | private static int minCostPathM(int[][] arr, int i, int j, int[][] storage) { 16 | int m = arr.length; 17 | int n = arr[0].length; 18 | 19 | if(i >= m || j >= n){ 20 | return Integer.MAX_VALUE; 21 | } 22 | 23 | if(i == m - 1 && j == n - 1){ 24 | storage[m - 1][n - 1] = arr[i][j]; 25 | return storage[i][j]; 26 | } 27 | 28 | if(storage[i][j] != -1){ 29 | return storage[i][j]; 30 | } 31 | 32 | int op1 = minCostPathM(arr, i , j + 1, storage); 33 | int op2 = minCostPathM(arr, i + 1 , j + 1, storage); 34 | int op3 = minCostPathM(arr, i + 1, j, storage ); 35 | storage[i][j] = arr[i][j] + Math.min(op1, Math.min(op2, op3)); 36 | return storage[i][j]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /DP-2/MinimumCostPathRecursion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public static int cost(int input[][],int row,int col) { 3 | if(row==input.length-1&&col==input[0].length-1){ 4 | int ans=input[row][col]; 5 | return ans; 6 | } 7 | 8 | int total=input[row][col]; 9 | int opt1=Integer.MAX_VALUE; 10 | int opt2=Integer.MAX_VALUE; 11 | int opt3=Integer.MAX_VALUE; 12 | if(row+1 arr,int start){ 8 | visited[start]=true; 9 | arr.add(start); 10 | int n=edges.length; 11 | for(int j=0;j arrans= new ArrayList(); 23 | help(edges,visited,arrans,i); 24 | Collections.sort(arrans); 25 | for(int j=0;j map){ 4 | Queue q = new LinkedList<>(); 5 | q.add(start); 6 | int n=edges.length; 7 | int e=0; 8 | while(q.size()!=0) 9 | { 10 | int nekal=q.remove(); 11 | visited[nekal]=true; 12 | // 13 | for(int i=0;i max = new HashMap<>(); 67 | boolean visited[]= new boolean[edges[0].length]; 68 | getpath(edges,start,end,visited,max); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Graphs/GetPathDFS.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | public class Solution{ 4 | public static void help(int edges[][],boolean visited[],String ans,int start,int end){ 5 | if(start==end){ 6 | ans=start+" "+ans; 7 | System.out.print(ans); 8 | System.exit(0); 9 | } 10 | visited[start]=true; 11 | ans=start+" "+ans; 12 | int n=edges.length; 13 | for(int j=0;j q = new LinkedList<>(); 7 | q.add(v1); 8 | int n=edges.length; 9 | while(q.size()!=0){ 10 | int nekal=q.remove(); 11 | visited[nekal]=true; 12 | if(nekal==v2){ 13 | System.out.print("true"); 14 | return; 15 | } 16 | for(int i=0;i q = new LinkedList<>(); 9 | q.add(sv); 10 | while(q.size()!=0){ 11 | int firstelem = q.remove(); 12 | System.out.print(firstelem+" "); 13 | visited[sv] = true; 14 | for(int i=0; i { 4 | ArrayList> buckets; 5 | int size; 6 | int numBuckets; 7 | public Map() { 8 | numBuckets = 5; 9 | buckets = new ArrayList<>(); 10 | for (int i = 0; i < numBuckets; i++) { 11 | buckets.add(null); 12 | } 13 | } 14 | 15 | private int getBucketIndex(K key) { 16 | int hashCode = key.hashCode(); 17 | return hashCode % numBuckets; 18 | } 19 | 20 | public int size() { 21 | return size; 22 | } 23 | 24 | public V removeKey(K key) { 25 | int bucketIndex = getBucketIndex(key); 26 | MapNode head = buckets.get(bucketIndex); 27 | MapNode prev = null; 28 | while (head != null) { 29 | if (head.key.equals(key)) { 30 | size--; 31 | if (prev == null) { 32 | buckets.set(bucketIndex, head.next); 33 | } else { 34 | prev.next = head.next; 35 | } 36 | return head.value; 37 | } 38 | prev = head; 39 | head = head.next; 40 | } 41 | return null; 42 | } 43 | 44 | public V getValue(K key) { 45 | int bucketIndex = getBucketIndex(key); 46 | MapNode head = buckets.get(bucketIndex); 47 | while (head != null) { 48 | if (head.key.equals(key)) { 49 | return head.value; 50 | } 51 | head = head.next; 52 | } 53 | return null; 54 | } 55 | 56 | public double loadFactor() { 57 | return (1.0 * size)/numBuckets; 58 | } 59 | 60 | private void rehash() { 61 | System.out.println("Rehashing: buckets" + numBuckets + " size " + size); 62 | ArrayList> temp = buckets; 63 | buckets = new ArrayList<>(); 64 | for (int i = 0; i < 2*numBuckets; i++) { 65 | buckets.add(null); 66 | } 67 | size = 0; 68 | numBuckets *= 2; 69 | for (int i = 0; i < temp.size(); i++) { 70 | MapNode head = temp.get(i); 71 | while (head != null) { 72 | K key = head.key; 73 | V value = head.value; 74 | insert(key, value); 75 | head = head.next; 76 | } 77 | } 78 | } 79 | 80 | public void insert(K key, V value) { 81 | int bucketIndex = getBucketIndex(key); 82 | MapNode head = buckets.get(bucketIndex); 83 | while (head != null) { 84 | if (head.key.equals(key)) { 85 | head.value = value; 86 | return; 87 | } 88 | head = head.next; 89 | } 90 | head = buckets.get(bucketIndex); 91 | MapNode newElementNode = new MapNode(key , value); 92 | size++; 93 | newElementNode.next = head; 94 | buckets.set(bucketIndex, newElementNode); 95 | double loadFactor = (1.0*size)/numBuckets; 96 | if (loadFactor > 0.7) { 97 | rehash(); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /HashMaps/src/MapNode.java: -------------------------------------------------------------------------------- 1 | 2 | public class MapNode { 3 | K key; 4 | V value; 5 | MapNode next; 6 | 7 | public MapNode(K key, V value) { 8 | this.key = key; 9 | this.value = value; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /HashMaps/src/MapUse.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Set; 3 | //basic use of maps 4 | public class MapUse { 5 | 6 | public static void main(String[] args) { 7 | HashMap map = new HashMap<>(); 8 | // insert 9 | map.put("abc",1); 10 | map.put("def", 2); 11 | map.put("abc1",1); 12 | map.put("def1", 2); 13 | 14 | System.out.println("size: " + map.size()); 15 | 16 | // check Presence 17 | if (map.containsKey("abc")) { 18 | System.out.println("Has abc"); 19 | } 20 | 21 | if (map.containsKey("abc1")) { 22 | System.out.println("Has abc1"); 23 | } 24 | 25 | if (map.containsValue(2)) { 26 | System.out.println("has 2 as value"); 27 | } 28 | 29 | // get Value 30 | int v = 0; 31 | if (map.containsKey("abc1")) { 32 | v = map.get("abc1"); 33 | } 34 | System.out.println(v); 35 | 36 | 37 | // remove 38 | int s = map.remove("abc"); 39 | System.out.println(s); 40 | 41 | // iterate 42 | Set keys = map.keySet(); 43 | for (String str : keys) { 44 | System.out.println(str); 45 | } 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /HashMaps/src/MaximumFrequencyNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public static int maxFrequencyNumber(int[] arr){ 4 | HashMap max = new HashMap<>(); 5 | for(int i=0;i ma) { 17 | ma = max.get(i); 18 | ans = i; 19 | } 20 | } 21 | return ans; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /HashMaps/src/MaximumFrequencyNumberUsingLinkedHashMap.java: -------------------------------------------------------------------------------- 1 | // below is the linkedhashmap implementation 2 | // in your hashmap numbers are in general way thus they wont return the number with 3 | // maximum frequency and occur first , u better be use Linked 4 | // hashmap which actually stored the elements as per the required order 5 | import java.util.*; 6 | public class Solution { 7 | public static int maxFrequencyNumber(int[] arr){ 8 | LinkedHashMap max = new LinkedHashMap<>(); 9 | for(int i=0;i it=max.keySet().iterator(); 20 | while(it.hasNext()){ 21 | int i=it.next(); 22 | if(max1 map = new Map<>(); 5 | for (int i = 0; i < 20; i++) { 6 | map.insert("abc" + i, 1 + i); 7 | System.out.println("i = " + i + " lf = " + map.loadFactor()); 8 | } 9 | 10 | map.removeKey("abc3"); 11 | map.removeKey("abc7"); 12 | 13 | for (int i = 0; i < 20; i++) { 14 | System.out.println("abc" + i + ":" + map.getValue("abc" + i)); 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /HashMaps/src/hashmapVVhashtable.java: -------------------------------------------------------------------------------- 1 | Differences between HashMap and HashTable in Java 2 | HashMap and Hashtable store key/value pairs in a hash table. When using a Hashtable or HashMap, we specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. 3 | 4 | Sample Java code. 5 | 6 | filter_none 7 | edit 8 | play_arrow 9 | 10 | brightness_4 11 | // A sample Java program to demonstrate HashMap and HashTable 12 | import java.util.*; 13 | import java.lang.*; 14 | import java.io.*; 15 | 16 | /* Name of the class has to be "Main" only if the class is public. */ 17 | class Ideone 18 | { 19 | public static void main(String args[]) 20 | { 21 | //----------hashtable ------------------------- 22 | Hashtable ht=new Hashtable(); 23 | ht.put(101," ajay"); 24 | ht.put(101,"Vijay"); 25 | ht.put(102,"Ravi"); 26 | ht.put(103,"Rahul"); 27 | System.out.println("-------------Hash table--------------"); 28 | for (Map.Entry m:ht.entrySet()) { 29 | System.out.println(m.getKey()+" "+m.getValue()); 30 | } 31 | 32 | //----------------hashmap-------------------------------- 33 | HashMap hm=new HashMap(); 34 | hm.put(100,"Amit"); 35 | hm.put(104,"Amit"); // hash map allows duplicate values 36 | hm.put(101,"Vijay"); 37 | hm.put(102,"Rahul"); 38 | System.out.println("-----------Hash map-----------"); 39 | for (Map.Entry m:hm.entrySet()) { 40 | System.out.println(m.getKey()+" "+m.getValue()); 41 | } 42 | } 43 | } 44 | Output: 45 | 46 | -------------Hash table-------------- 47 | 103 Rahul 48 | 102 Ravi 49 | 101 Vijay 50 | -----------Hash map----------- 51 | 100 Amit 52 | 101 Vijay 53 | 102 Rahul 54 | 104 Amit 55 | Hashmap vs Hashtable 56 | 1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads. 57 | 2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value. 58 | 3. HashMap is generally preferred over HashTable if thread synchronization is not needed 59 | 60 | Why HashTable doesn’t allow null and HashMap does? 61 | To successfully store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode method and the equals method. Since null is not an object, it can’t implement these methods. HashMap is an advanced version and improvement on the Hashtable. HashMap was created later. 62 | -------------------------------------------------------------------------------- /HashMaps/src/removeDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | 4 | public class removeDuplicates { 5 | 6 | public static ArrayList removeDuplicate(int a[]) { 7 | ArrayList output = new ArrayList<>(); 8 | HashMap seen = new HashMap<>(); 9 | for (int i = 0; i < a.length; i++) { 10 | if (seen.containsKey(a[i])) { 11 | continue; 12 | } 13 | output.add(a[i]); 14 | seen.put(a[i], true); 15 | } 16 | return output; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int a[] = {1,3,2,4,1,2,2,2,10000,3,2}; 21 | ArrayList output = removeDuplicate(a); 22 | for (int i = 0; i < output.size(); i++) { 23 | System.out.println(output.get(i)); 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Library/BufferedReader.java: -------------------------------------------------------------------------------- 1 | import java.io.OutputStream; 2 | import java.io.IOException; 3 | import java.io.InputStream; 4 | import java.io.PrintWriter; 5 | import java.util.StringTokenizer; 6 | import java.io.IOException; 7 | import java.io.BufferedReader; 8 | import java.io.InputStreamReader; 9 | import java.io.InputStream; 10 | 11 | 12 | // Remember that the class name should be "Main" and should be "public". 13 | public class Main { 14 | public static void main(String[] args) { 15 | // System.in and System.out are input and output streams, respectively. 16 | InputStream inputStream = System.in; 17 | 18 | InputReader in = new InputReader(inputStream); 19 | 20 | int n = in.nextInt(); 21 | int k = in.nextInt(); 22 | } 23 | 24 | static class InputReader { 25 | public BufferedReader reader; 26 | public StringTokenizer tokenizer; 27 | 28 | public InputReader(InputStream stream) { 29 | reader = new BufferedReader(new InputStreamReader(stream), 32768); 30 | tokenizer = null; 31 | } 32 | 33 | public String next() { 34 | while (tokenizer == null || !tokenizer.hasMoreTokens()) { 35 | try { 36 | tokenizer = new StringTokenizer(reader.readLine()); 37 | } catch (IOException e) { 38 | throw new RuntimeException(e); 39 | } 40 | } 41 | return tokenizer.nextToken(); 42 | } 43 | 44 | public int nextInt() { 45 | return Integer.parseInt(next()); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Linked List/src/ArrayListDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class ArrayListDemo { 4 | 5 | public static void main(String[] args) { 6 | 7 | ArrayList list1 = new ArrayList<>(); 8 | 9 | @SuppressWarnings("unused") 10 | ArrayList list2 = new ArrayList<>(); 11 | 12 | System.out.println(list1.size()); 13 | list1.add(15); 14 | 15 | list1.add(20); 16 | list1.add(25); 17 | list1.add(2, 50); 18 | // System.out.println(list1.get(5)); 19 | // System.out.println(list1.size()); 20 | // System.out.println(list1.get(2)); 21 | 22 | 23 | for(int elem : list1){ 24 | System.out.print(elem + " "); 25 | elem = 100; 26 | } 27 | 28 | System.out.println(); 29 | 30 | for(int i = 0; i < list1.size(); i++){ 31 | System.out.print(list1.get(i) + " "); 32 | } 33 | 34 | // System.out.println(); 35 | // //list1.remove(1); 36 | // list1.set(1, 100); 37 | // for(int i = 0; i < list1.size(); i++){ 38 | // System.out.print(list1.get(i) + " "); 39 | // } 40 | // 41 | 42 | 43 | 44 | 45 | 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /Linked List/src/Node.java: -------------------------------------------------------------------------------- 1 | 2 | public class Node { 3 | 4 | T data; 5 | Node next; 6 | 7 | Node(T data){ 8 | this.data = data; 9 | next = null; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Methods/ArrayList.java: -------------------------------------------------------------------------------- 1 | ArrayList arr = new ArrayList(n); 2 | where n is the size 3 | if you dont wnat to give the size then its ok 4 | Methods in Java ArrayList: 5 | 6 | forEach​(Consumer action): Performs the given action for each element of the Iterable until all 7 | elements have been processed or the action throws an exception. 8 | retainAll​(Collection c): Retains only the elements in this list that are contained in the specified collection. 9 | removeIf​(Predicate filter): Removes all of the elements of this collection that satisfy the given predicate. 10 | contains​(Object o): Returns true if this list contains the specified element. 11 | remove​(int index): Removes the element at the specified position in this list. 12 | remove​(Object o): Removes the first occurrence of the specified element from this list, if it is present. 13 | get​(int index): Returns the element at the specified position in this list. 14 | subList​(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. 15 | spliterator​(): Creates a late-binding and fail-fast Spliterator over the elements in this list. 16 | set​(int index, E element): Replaces the element at the specified position in this list with the specified element. 17 | size​(): Returns the number of elements in this list. 18 | removeAll​(Collection c): Removes from this list all of its elements that are contained in the specified collection. 19 | ensureCapacity​(int minCapacity): Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. 20 | listIterator​(): Returns a list iterator over the elements in this list (in proper sequence). 21 | listIterator​(int index): Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. 22 | isEmpty​(): Returns true if this list contains no elements. 23 | removeRange​(int fromIndex, int toIndex): Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. 24 | void clear(): This method is used to remove all the elements from any list. 25 | void add(int index, Object element): This method is used to insert a specific element at a specific position index in a list. 26 | void trimToSize(): This method is used to trim the capacity of the instance of the ArrayLis to the list’s current size. 27 | int indexOf(Object O): The 28 | index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list. 29 | int lastIndexOf(Object O): The index the last occurrence of a specific element is either returned, or -1 in case the element is not in the list. 30 | Object clone(): This method is used to return a shallow copy of an ArrayList. 31 | Object[] toArray(): This method is used to return an array containing all of the elements in the list in correct order. 32 | Object[] toArray(Object[] O): It is also used to return an array containing all of the elements in this list in the correct order same as the previous method. 33 | boolean addAll(Collection C): This method is used to append all the elements from a specific collection to the end of the mentioned list, in such a order that the values are returned by the specified collection’s iterator. 34 | boolean add(Object o): This method is used to append a specificd element to the end of a list. 35 | boolean addAll(int index, Collection C): Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list. 36 | -------------------------------------------------------------------------------- /Priority Queues/BuyTheTicket.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Priority Queues/CheckMaxHeap.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static boolean checkMaxHeap(int arr[]) { 4 | 5 | int parent=0; 6 | int child1=1; 7 | int child2=2; 8 | while(child1 0){ 6 | if(input[childindex] < input[parentIndex]) 7 | { 8 | int temp = input[childindex]; 9 | input[childindex]=input[parentIndex]; 10 | input[parentIndex]=temp; 11 | childindex = parentIndex; 12 | parentIndex = (childindex - 1) / 2; 13 | } 14 | else 15 | { 16 | return; 17 | } 18 | } 19 | } 20 | 21 | public static void inplaceHeapSort(int input[]) { 22 | int i=0; 23 | // the input index is converted to heap means the element on the top is smallest of all 24 | while(i0){ 31 | // now we just swap last element and the first element ; 32 | int tem=input[0]; 33 | input[0]=input[j]; 34 | input[j]=tem; 35 | // now we visualise that the array is now decreased by one because in the last place 36 | // our smallest element is there //\ 37 | // and now we do heapyfy process but the last emement is not incruded; 38 | int index = 0; 39 | int minIndex = index; 40 | int leftChildIndex = 1; 41 | int rightChildIndex = 2; 42 | 43 | while(leftChildIndex < j){ 44 | 45 | if(input[leftChildIndex] < input[minIndex]){ 46 | minIndex = leftChildIndex; 47 | } 48 | if(rightChildIndex < j && input[rightChildIndex] < input[minIndex]){ 49 | minIndex = rightChildIndex; 50 | } 51 | if(minIndex == index){ 52 | break; 53 | }else{ 54 | int temp1 = input[index]; 55 | input[index]=input[minIndex]; 56 | input[minIndex]=temp1; 57 | index = minIndex; 58 | leftChildIndex = 2 * index + 1; 59 | rightChildIndex = 2 * index + 2; 60 | } 61 | } 62 | j--; 63 | 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Priority Queues/KlargestElements.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.PriorityQueue; 3 | import java.util.*; 4 | public class Solution { 5 | 6 | public static ArrayList kLargest(int input[], int k) { 7 | PriorityQueue pq = new PriorityQueue<>(); 8 | ArrayList ans=new ArrayList(); 9 | int i = 0; 10 | for ( ; i heap; 5 | public PriorityQueue(){ 6 | heap = new ArrayList<>(); 7 | } 8 | 9 | boolean isEmpty(){ 10 | return heap.size() == 0; 11 | } 12 | 13 | int getSize(){ 14 | return heap.size(); 15 | } 16 | 17 | int getMax() { 18 | if(isEmpty()){ 19 | return (Integer.MIN_VALUE); 20 | } 21 | return heap.get(0); 22 | } 23 | 24 | void insert(int element){ 25 | heap.add(element); 26 | int childIndex = heap.size() - 1; 27 | int parentIndex = (childIndex - 1) / 2; 28 | 29 | while(childIndex > 0){ 30 | if(heap.get(childIndex) > heap.get(parentIndex)){ 31 | int temp = heap.get(childIndex); 32 | heap.set(childIndex, heap.get(parentIndex)); 33 | heap.set(parentIndex, temp); 34 | childIndex = parentIndex; 35 | parentIndex = (childIndex - 1) / 2; 36 | }else{ 37 | return; 38 | } 39 | } 40 | } 41 | 42 | 43 | int removeMax() { 44 | if(isEmpty()){ 45 | // Throw an exception 46 | return (Integer.MIN_VALUE); 47 | } 48 | int temp = heap.get(0); 49 | heap.set(0, heap.get(heap.size() - 1)); 50 | heap.remove(heap.size() - 1); 51 | int index = 0; 52 | int minIndex = index; 53 | int leftChildIndex = 1; 54 | int rightChildIndex = 2; 55 | 56 | while(leftChildIndex < heap.size()){ 57 | 58 | if(heap.get(leftChildIndex) > heap.get(minIndex)){ 59 | minIndex = leftChildIndex; 60 | } 61 | if(rightChildIndex < heap.size() && heap.get(rightChildIndex) > heap.get(minIndex)){ 62 | minIndex = rightChildIndex; 63 | } 64 | if(minIndex == index){ 65 | break; 66 | }else{ 67 | int temp1 = heap.get(index); 68 | heap.set(index, heap.get(minIndex)); 69 | heap.set(minIndex, temp1); 70 | index = minIndex; 71 | leftChildIndex = 2 * index + 1; 72 | rightChildIndex = 2 * index + 2; 73 | } 74 | } 75 | return temp; 76 | 77 | } 78 | } 79 | 80 | -------------------------------------------------------------------------------- /Priority Queues/MinPriorityQueueImplementation.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class PriorityQueueException extends Exception { 4 | } 5 | 6 | public class PQ { 7 | private ArrayList heap; 8 | 9 | public PQ() { 10 | heap = new ArrayList(); 11 | } 12 | 13 | boolean isEmpty(){ 14 | return heap.size() == 0; 15 | } 16 | 17 | int size(){ 18 | return heap.size(); 19 | } 20 | 21 | int getMin() throws PriorityQueueException{ 22 | if(isEmpty()){ 23 | // Throw an exception 24 | throw new PriorityQueueException(); 25 | } 26 | return heap.get(0); 27 | } 28 | 29 | void insert(int element){ 30 | heap.add(element); 31 | int childIndex = heap.size() - 1; 32 | int parentIndex = (childIndex - 1) / 2; 33 | 34 | while(childIndex > 0){ 35 | if(heap.get(childIndex) < heap.get(parentIndex)){ 36 | int temp = heap.get(childIndex); 37 | heap.set(childIndex, heap.get(parentIndex)); 38 | heap.set(parentIndex, temp); 39 | childIndex = parentIndex; 40 | parentIndex = (childIndex - 1) / 2; 41 | }else{ 42 | return; 43 | } 44 | } 45 | } 46 | 47 | int removeMin() throws PriorityQueueException{ 48 | // Complete this function 49 | // Throw the exception PriorityQueueException if queue is empty 50 | if(isEmpty()){ 51 | // Throw an exception 52 | throw new PriorityQueueException(); 53 | } 54 | int temp = heap.get(0); 55 | heap.set(0, heap.get(heap.size() - 1)); 56 | heap.remove(heap.size() - 1); 57 | int index = 0; 58 | int minIndex = index; 59 | int leftChildIndex = 1; 60 | int rightChildIndex = 2; 61 | 62 | while(leftChildIndex < heap.size()){ 63 | 64 | if(heap.get(leftChildIndex) < heap.get(minIndex)){ 65 | minIndex = leftChildIndex; 66 | } 67 | if(rightChildIndex < heap.size() && heap.get(rightChildIndex) < heap.get(minIndex)){ 68 | minIndex = rightChildIndex; 69 | } 70 | if(minIndex == index){ 71 | break; 72 | }else{ 73 | int temp1 = heap.get(index); 74 | heap.set(index, heap.get(minIndex)); 75 | heap.set(minIndex, temp1); 76 | index = minIndex; 77 | leftChildIndex = 2 * index + 1; 78 | rightChildIndex = 2 * index + 2; 79 | } 80 | } 81 | return temp; 82 | 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Priority Queues/PriorityQueueUse.java: -------------------------------------------------------------------------------- 1 | import java.util.Collection; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | 6 | 7 | class MinPQComparator implements Comparator{ 8 | 9 | @Override 10 | public int compare(Integer o1, Integer o2) { 11 | // TODO Auto-generated method stub 12 | if(o1 < o2){ 13 | return -1; 14 | }else if(o1 > o2){ 15 | return 1; 16 | } 17 | return 0; 18 | } 19 | 20 | } 21 | 22 | 23 | 24 | public class PriorityQueueUse { 25 | 26 | 27 | private static void insertIntoVirtualHeap(int[] arr, int i) { 28 | int childIndex = i; 29 | int parentIndex = (childIndex - 1) / 2; 30 | while(childIndex > 0){ 31 | if(arr[childIndex] < arr[parentIndex] ){ // compare(o1, o2) < 0 32 | int temp = arr[childIndex]; 33 | arr[childIndex] = arr[parentIndex]; 34 | arr[parentIndex] = temp; 35 | childIndex = parentIndex; 36 | parentIndex = (childIndex - 1) / 2; 37 | }else{ 38 | return; 39 | } 40 | } 41 | 42 | } 43 | 44 | private static int removeMinFromVirtualHeap(int[] arr, int heapSize) { 45 | 46 | int temp = arr[0]; 47 | arr[0] = arr[heapSize - 1]; 48 | heapSize--; 49 | int index = 0; 50 | int leftChildIndex = 2 * index + 1; 51 | int rightChildIndex = 2 * index + 2; 52 | 53 | while(leftChildIndex < heapSize){ 54 | 55 | int minIndex = index; 56 | if(arr[leftChildIndex] < arr[minIndex]){ 57 | minIndex = leftChildIndex; 58 | } 59 | if(rightChildIndex < heapSize && arr[rightChildIndex] < arr[minIndex]){ 60 | minIndex = rightChildIndex; 61 | } 62 | if(minIndex != index){ 63 | int temp1 = arr[index]; 64 | arr[index] = arr[minIndex]; 65 | arr[minIndex] = temp1; 66 | index = minIndex; 67 | leftChildIndex = 2 * index + 1; 68 | rightChildIndex = 2 * index + 2; 69 | }else{ 70 | break; 71 | } 72 | } 73 | return temp; 74 | } 75 | 76 | public static void sortKSorted(int arr[], int k){ 77 | PriorityQueue pq = new PriorityQueue<>(); 78 | int i = 0; 79 | for ( ; i < k; i++){ 80 | pq.add(arr[i]); 81 | } 82 | 83 | for(; i < arr.length; i++){ 84 | arr[i - k] = pq.remove(); 85 | pq.add(arr[i]); 86 | } 87 | 88 | for(int j = arr.length - k; j < arr.length; j++){ 89 | arr[j] = pq.remove(); 90 | } 91 | } 92 | 93 | 94 | public static void printKLargest(int arr[], int k){ 95 | PriorityQueue pq = new PriorityQueue<>(); 96 | int i = 0; 97 | for( ; i < k; i++){ 98 | pq.add(arr[i]); 99 | } 100 | 101 | for(; i < arr.length; i++){ 102 | int min = pq.element(); 103 | if(min < arr[i]){ 104 | pq.remove(); 105 | pq.add(arr[i]); 106 | } 107 | } 108 | 109 | while(! pq.isEmpty()){ 110 | System.out.println(pq.remove()); 111 | } 112 | 113 | } 114 | 115 | public static void main(String[] args) { 116 | int arr[] = {2,15,8,9,12,13,20}; 117 | printKLargest(arr, 3); 118 | 119 | } 120 | 121 | 122 | 123 | } 124 | 125 | 126 | 127 | class MaxPQComparator implements Comparator{ 128 | @Override 129 | public int compare(Integer o1, Integer o2) { 130 | // TODO Auto-generated method stub 131 | if(o1 < o2){ 132 | return 1; 133 | }else if(o1 > o2){ 134 | return -1; 135 | } 136 | return 0; 137 | } 138 | } 139 | 140 | class StringLengthComparator implements Comparator{ 141 | @Override 142 | public int compare(String o1, String o2) { 143 | if(o1.length() < o2.length()){ 144 | return 1; 145 | }else if(o1.length() > o2.length()){ 146 | return -1; 147 | }else{ 148 | return 0; 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /Priority Queues/PriorityQueueUse_Comparator.java: -------------------------------------------------------------------------------- 1 | import java.util.Collection; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | // all function 6 | // comparator is very important 7 | class MinPQComparator implements Comparator{ 8 | 9 | @Override 10 | public int compare(Integer o1, Integer o2) { 11 | // TODO Auto-generated method stub 12 | if(o1 < o2){ 13 | return -1; 14 | }else if(o1 > o2){ 15 | return 1; 16 | } 17 | return 0; 18 | } 19 | 20 | } 21 | 22 | public class PriorityQueueUse { 23 | 24 | private static void insertIntoVirtualHeap(int[] arr, int i) { 25 | int childIndex = i; 26 | int parentIndex = (childIndex - 1) / 2; 27 | while(childIndex > 0){ 28 | if(arr[childIndex] < arr[parentIndex] ){ // compare(o1, o2) < 0 29 | int temp = arr[childIndex]; 30 | arr[childIndex] = arr[parentIndex]; 31 | arr[parentIndex] = temp; 32 | childIndex = parentIndex; 33 | parentIndex = (childIndex - 1) / 2; 34 | }else{ 35 | return; 36 | } 37 | } 38 | 39 | } 40 | 41 | private static int removeMinFromVirtualHeap(int[] arr, int heapSize) { 42 | 43 | int temp = arr[0]; 44 | arr[0] = arr[heapSize - 1]; 45 | heapSize--; 46 | int index = 0; 47 | int leftChildIndex = 2 * index + 1; 48 | int rightChildIndex = 2 * index + 2; 49 | 50 | while(leftChildIndex < heapSize){ 51 | 52 | int minIndex = index; 53 | if(arr[leftChildIndex] < arr[minIndex]){ 54 | minIndex = leftChildIndex; 55 | } 56 | if(rightChildIndex < heapSize && arr[rightChildIndex] < arr[minIndex]){ 57 | minIndex = rightChildIndex; 58 | } 59 | if(minIndex != index){ 60 | int temp1 = arr[index]; 61 | arr[index] = arr[minIndex]; 62 | arr[minIndex] = temp1; 63 | index = minIndex; 64 | leftChildIndex = 2 * index + 1; 65 | rightChildIndex = 2 * index + 2; 66 | }else{ 67 | break; 68 | } 69 | } 70 | return temp; 71 | } 72 | 73 | public static void sortKSorted(int arr[], int k){ 74 | PriorityQueue pq = new PriorityQueue<>(); 75 | int i = 0; 76 | for ( ; i < k; i++){ 77 | pq.add(arr[i]); 78 | } 79 | 80 | for(; i < arr.length; i++){ 81 | arr[i - k] = pq.remove(); 82 | pq.add(arr[i]); 83 | } 84 | 85 | for(int j = arr.length - k; j < arr.length; j++){ 86 | arr[j] = pq.remove(); 87 | } 88 | } 89 | 90 | 91 | public static void printKLargest(int arr[], int k){ 92 | PriorityQueue pq = new PriorityQueue<>(); 93 | int i = 0; 94 | for( ; i < k; i++){ 95 | pq.add(arr[i]); 96 | } 97 | 98 | for(; i < arr.length; i++){ 99 | int min = pq.element(); 100 | if(min < arr[i]){ 101 | pq.remove(); 102 | pq.add(arr[i]); 103 | } 104 | } 105 | 106 | while(! pq.isEmpty()){ 107 | System.out.println(pq.remove()); 108 | } 109 | } 110 | 111 | public static void main(String[] args) { 112 | int arr[] = {2,15,8,9,12,13,20}; 113 | printKLargest(arr, 3); 114 | } 115 | } 116 | class MaxPQComparator implements Comparator{ 117 | @Override 118 | public int compare(Integer o1, Integer o2) { 119 | // TODO Auto-generated method stub 120 | if(o1 < o2){ 121 | return 1; 122 | }else if(o1 > o2){ 123 | return -1; 124 | } 125 | return 0; 126 | } 127 | } 128 | 129 | class StringLengthComparator implements Comparator{ 130 | @Override 131 | public int compare(String o1, String o2) { 132 | if(o1.length() < o2.length()){ 133 | return 1; 134 | }else if(o1.length() > o2.length()){ 135 | return -1; 136 | }else{ 137 | return 0; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Priority Queues/Runningmedian.java: -------------------------------------------------------------------------------- 1 | // made by ketan mehta.. 2 | import java.util.*; 3 | public class Solution { 4 | 5 | public static void runningMedian(int arr[]) { 6 | PriorityQueue maxpq=new PriorityQueue<>(Collections.reverseOrder()); 7 | PriorityQueue minpq=new PriorityQueue<>(); 8 | int i=0; 9 | while(i1){ 43 | minpq.add(maxpq.remove()); 44 | max=maxpq.peek(); 45 | min=minpq.peek(); 46 | System.out.println((max+min)/2); 47 | }//same 48 | else if(minpq.size()-maxpq.size()>1){ 49 | maxpq.add(minpq.remove()); 50 | max=maxpq.peek(); 51 | min=minpq.peek(); 52 | System.out.println((max+min)/2); 53 | } // if difference is less than two mwans one 54 | else if(minpq.size()>maxpq.size()){ 55 | System.out.println(minpq.peek()); 56 | } 57 | else if(minpq.size() 0){ 10 | if(arr[childIndex] < arr[parentIndex] ){ 11 | int temp = arr[childIndex]; 12 | arr[childIndex] = arr[parentIndex]; 13 | arr[parentIndex] = temp; 14 | childIndex = parentIndex; 15 | parentIndex = (childIndex - 1) / 2; 16 | }else{ 17 | return; 18 | } 19 | } 20 | 21 | } 22 | 23 | private static int removeMinFromVirtualHeap(int[] arr, int heapSize) { 24 | 25 | int temp = arr[0]; 26 | arr[0] = arr[heapSize - 1]; 27 | heapSize--; 28 | int index = 0; 29 | int leftChildIndex = 2 * index + 1; 30 | int rightChildIndex = 2 * index + 2; 31 | 32 | while(leftChildIndex < heapSize){ 33 | 34 | int minIndex = index; 35 | if(arr[leftChildIndex] < arr[minIndex]){ 36 | minIndex = leftChildIndex; 37 | } 38 | if(rightChildIndex < heapSize && arr[rightChildIndex] < arr[minIndex]){ 39 | minIndex = rightChildIndex; 40 | } 41 | if(minIndex != index){ 42 | int temp1 = arr[index]; 43 | arr[index] = arr[minIndex]; 44 | arr[minIndex] = temp1; 45 | index = minIndex; 46 | leftChildIndex = 2 * index + 1; 47 | rightChildIndex = 2 * index + 2; 48 | }else{ 49 | break; 50 | } 51 | } 52 | return temp; 53 | } 54 | 55 | public static void sortKSorted(int arr[], int k){ 56 | PriorityQueue pq = new PriorityQueue<>(); 57 | int i = 0; 58 | for ( ; i < k; i++){ 59 | pq.add(arr[i]); 60 | } 61 | 62 | for(; i < arr.length; i++){ 63 | arr[i - k] = pq.remove(); 64 | pq.add(arr[i]); 65 | } 66 | 67 | for(int j = arr.length - k; j < arr.length; j++){ 68 | arr[j] = pq.remove(); 69 | } 70 | 71 | } 72 | 73 | public static void main(String[] args) { 74 | int arr[] = {2,4,1,9,6,8}; 75 | int k = 3; 76 | sortKSorted(arr, k); 77 | for(int i = 0; i < arr.length; i++){ 78 | System.out.print(arr[i] + " "); 79 | } 80 | 81 | // PriorityQueue pq = new PriorityQueue<>(); 82 | // int arr[] = {9,1,0,4,7,3}; 83 | // for(int i = 0; i < arr.length; i++){ 84 | // pq.add(arr[i]); 85 | // if k is one then the element place is not change 86 | // because the elements are within k distance to get sorted 87 | // } 88 | // 89 | //// System.out.println(pq.element()); 90 | // while(! pq.isEmpty()){ 91 | // System.out.print(pq.remove() + " "); 92 | // } 93 | // time complexity nlogk 94 | 95 | } 96 | 97 | 98 | 99 | 100 | } 101 | -------------------------------------------------------------------------------- /Priority Queues/important.java: -------------------------------------------------------------------------------- 1 | some important points : 2 | import java.util.PriorityQueue; 3 | method to change the min priority queue to max priority queue:) 4 | PriorityQueue queue = new PriorityQueue<>(Collections.reverseOrder()); 5 | Declaration: PriorityQueue pq = new PriorityQueue<>(); 6 | 7 | Methods in PriorityQueue class: 8 | 9 | boolean add(E element): This method inserts the specified element into this priority queue. 10 | public remove(): This method removes a single instance of the specified element from this queue, if it is present 11 | public poll(): This method retrieves and removes the head of this queue, or returns null if this queue is empty. 12 | public peek(): This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. 13 | Iterator iterator(): Returns an iterator over the elements in this queue. 14 | boolean contains(Object o): This method returns true if this queue contains the specified element 15 | void clear(): This method is used to remove all of the contents of the priority queue. 16 | boolean offer(E e): This method is used to insert a specific element into the priority queue. 17 | int size(): The method is used to return the number of elements present in the set. 18 | toArray(): This method is used to return an array containing all of the elements in this queue. 19 | Comparator comparator(): The method is used to return the comparator that can be used to order the elements of the queue. 20 | example pq.add 21 | pq.remove; 22 | -------------------------------------------------------------------------------- /Priority Queues/kthLargest.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | 4 | public static int kthLargest(int arr[], int k) { 5 | int i=0; 6 | PriorityQueue pq=new PriorityQueue(Collections.reverseOrder()); 7 | for(i=0;i pq = new PriorityQueue(); 21 | // for(int i = 0; i < k; i++) { 22 | // pq.add(arr[i]); 23 | // } 24 | // for(int i = k; i < arr.length; i++) { 25 | // if(arr[i] > pq.peek()) { 26 | // pq.poll(); 27 | // pq.add(arr[i]); 28 | // } 29 | // } 30 | // return pq.peek(); 31 | // } 32 | // } 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # codingninjas 2 | all codes of Data Structures in Java 3 | for the interview perspective ,these all questions are very much important. 4 | 5 | 6 | contact: meetketanmehta@gmail.com 7 | 8 | i will suggest you not to directly copy paste the solution 9 | this will not help you bro so try to do questions on your own 10 | ask doubts bro 11 | 12 | if you want to contribute , please do it now 13 | -------------------------------------------------------------------------------- /Stack and Queue/bin/BalancedParenthesis.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/BalancedParenthesis.class -------------------------------------------------------------------------------- /Stack and Queue/bin/Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/Node.class -------------------------------------------------------------------------------- /Stack and Queue/bin/QueueEmptyException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/QueueEmptyException.class -------------------------------------------------------------------------------- /Stack and Queue/bin/QueueFullException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/QueueFullException.class -------------------------------------------------------------------------------- /Stack and Queue/bin/QueueUse.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/QueueUse.class -------------------------------------------------------------------------------- /Stack and Queue/bin/QueueUsingArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/QueueUsingArray.class -------------------------------------------------------------------------------- /Stack and Queue/bin/Queueusell.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/Queueusell.class -------------------------------------------------------------------------------- /Stack and Queue/bin/StackFullException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/StackFullException.class -------------------------------------------------------------------------------- /Stack and Queue/bin/StackUse.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/StackUse.class -------------------------------------------------------------------------------- /Stack and Queue/bin/StackUseLinkedlist.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/StackUseLinkedlist.class -------------------------------------------------------------------------------- /Stack and Queue/bin/StackUsingArray.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/StackUsingArray.class -------------------------------------------------------------------------------- /Stack and Queue/bin/StackUsingLL.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/StackUsingLL.class -------------------------------------------------------------------------------- /Stack and Queue/bin/queueusingll.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ketanMehtaa/codingninjas/0fad9523cebe4db6d10837cf83652bae29925a57/Stack and Queue/bin/queueusingll.class -------------------------------------------------------------------------------- /Stack and Queue/src/BalancedParenthesis.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | import java.util.*; 3 | import java.util.Arrays; 4 | public class Solution { 5 | 6 | public static boolean checkBalanced(String expr) { 7 | if (expr.isEmpty()) 8 | return true; 9 | 10 | Stack stack = new Stack(); 11 | 12 | for (int i = 0; i < expr.length(); i++) 13 | { 14 | char current = expr.charAt(i); 15 | if (current == '{' || current == '(' || current == '[') 16 | { 17 | stack.push(current); 18 | } 19 | if (current == '}' || current == ')' || current == ']') 20 | { 21 | if (stack.isEmpty()) 22 | return false; 23 | char last = stack.peek(); 24 | if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[') 25 | stack.pop(); 26 | else 27 | return false; 28 | } 29 | } 30 | return stack.isEmpty()?true:false; 31 | } 32 | } 33 | // second method 34 | import java.util.*; 35 | 36 | public class BalancedParenthesis { 37 | 38 | public static boolean checkBalanced(String exp) { 39 | StackUsingLL stack = new StackUsingLL(); 40 | int i=0; 41 | while(i { 78 | private Node head; 79 | private int size; 80 | 81 | public StackUsingLL() { 82 | head = null; 83 | size = 0; 84 | } 85 | 86 | int size(){ 87 | return size; 88 | } 89 | boolean isEmpty(){ 90 | return size() == 0; // head == null 91 | } 92 | 93 | T top(){ 94 | 95 | return head.data; 96 | } 97 | 98 | void push(T element){ 99 | 100 | Node newNode = new Node(element); 101 | newNode.next = head; 102 | head = newNode; 103 | size++; 104 | 105 | } 106 | 107 | T pop() { 108 | 109 | T tempdata = head.data; 110 | head = head.next; 111 | size--; 112 | return tempdata; 113 | 114 | } 115 | } 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /Stack and Queue/src/MinimumbracketReversal.java: -------------------------------------------------------------------------------- 1 | //the above approch passes all the test cases but not works fine 2 | import java.util.Stack; 3 | import java.lang.Math; 4 | public class Solution { 5 | public static int countBracketReversals(String input){ 6 | 7 | int i=0,count1=0,count2=0,count3=0; 8 | Stack k=new Stack(); 9 | if(input.length()%2!=0){ 10 | return -1; 11 | } 12 | while(input.length()>i) 13 | { 14 | if(input.charAt(i)=='{'){ 15 | k.push(input.charAt(i)); 16 | count1++; 17 | } 18 | else if(input.charAt(i)=='}') 19 | { 20 | if(k.size()==0) 21 | { 22 | count3=count3+2; 23 | k.push(input.charAt(i)); 24 | } 25 | if(k.peek() == '{'){ 26 | k.pop(); 27 | count2++; 28 | } 29 | else if(k.peek()!='{'){ 30 | k.push(input.charAt(i)); 31 | count3++; 32 | } 33 | } 34 | i++; 35 | } 36 | return (Math.abs((count1-count2)/2)+count3); 37 | //https://www.tutorialspoint.com/java/lang/math_abs_int.htm 38 | //maths.abs is used to get an absolute value 39 | } 40 | } 41 | //below is the provided solution 42 | // import java.util.Stack; 43 | // public class Solution { 44 | // // Function returns -1 if brackets can't be balanced 45 | // public static int countBracketReversals(String input){ 46 | // if(input.length() == 0){ 47 | // return 0; 48 | // } 49 | // if(input.length() % 2 != 0){ 50 | // return -1; 51 | // // reversal isn't possible 52 | // } 53 | // Stack stack = new Stack<>(); 54 | // for(int i = 0; i < input.length(); i++){ 55 | // char currentChar = input.charAt(i); 56 | // if(currentChar == '{'){ 57 | // stack.push(currentChar); 58 | // } 59 | // else{ 60 | // // pop if there is a balanced pair 61 | // if(!stack.isEmpty() && stack.peek() == '{'){ 62 | // stack.pop(); 63 | // } 64 | // else{ stack.push(currentChar); 65 | // } 66 | // } 67 | // } 68 | // int count = 0; 69 | // // only unbalanced brackets are there in stack now 70 | // while(!stack.isEmpty()){ 71 | // char char1 = stack.pop(); 72 | // char char2 = stack.pop(); 73 | // // i.e char1 = } and char2 = { then we need to reverse both of them 74 | // if(char1 != char2){ count += 2; } 75 | // // if both char1 and char2 are same i.e either the are {{ or }}, then we need only 1 reversal 76 | // else{ count += 1;} 77 | // } return count; 78 | // } 79 | // } 80 | -------------------------------------------------------------------------------- /Stack and Queue/src/Node.java: -------------------------------------------------------------------------------- 1 | 2 | public class Node { 3 | 4 | T data; 5 | Node next; 6 | 7 | Node(T data){ 8 | this.data = data; 9 | next = null; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Stack and Queue/src/QueueEmptyException.java: -------------------------------------------------------------------------------- 1 | 2 | public class QueueEmptyException extends Exception { 3 | 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 7243921724361015813L; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Stack and Queue/src/QueueFullException.java: -------------------------------------------------------------------------------- 1 | 2 | public class QueueFullException extends Exception{ 3 | 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = -7167634756637168192L; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Stack and Queue/src/QueueUse.java: -------------------------------------------------------------------------------- 1 | 2 | public class QueueUse { 3 | 4 | public static void main(String[] args) { 5 | QueueUsingArray queue = new QueueUsingArray(3); 6 | for(int i = 1; i <= 5; i++){ 7 | try { 8 | queue.enqueue(i); 9 | } catch (QueueFullException e) { 10 | 11 | } 12 | } 13 | 14 | 15 | while(! queue.isEmpty()){ 16 | try { 17 | System.out.println(queue.dequeue()); 18 | } catch (QueueEmptyException e) { 19 | // TODO Auto-generated catch block 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Stack and Queue/src/QueueUsingArray.java: -------------------------------------------------------------------------------- 1 | 2 | public class QueueUsingArray { 3 | 4 | private int data[]; 5 | private int front; // index at which front element is stored 6 | private int rear; // index at which rear element is stored 7 | private int size; 8 | 9 | public QueueUsingArray() { 10 | data = new int[10]; 11 | front = -1; 12 | rear = -1; 13 | size = 0; 14 | } 15 | public QueueUsingArray( int capacity) { 16 | data = new int[capacity]; 17 | front = -1; 18 | rear = -1; 19 | size = 0; 20 | } 21 | 22 | int size(){ 23 | return size; 24 | } 25 | 26 | boolean isEmpty(){ 27 | return size == 0; 28 | } 29 | 30 | int front() throws QueueEmptyException{ 31 | if(size == 0){ 32 | throw new QueueEmptyException(); 33 | } 34 | return data[front]; 35 | } 36 | 37 | void enqueue(int element) throws QueueFullException{ 38 | 39 | if(size == data.length){ 40 | // throw new QueueFullException(); 41 | doubleCapacity(); 42 | } 43 | 44 | if(size == 0){ 45 | front = 0; 46 | } 47 | size++; 48 | rear = (rear + 1) % data.length; 49 | // rear++; 50 | // if(rear == data.length){ 51 | // rear = 0; 52 | // } 53 | data[rear] = element; 54 | } 55 | 56 | private void doubleCapacity() { 57 | int temp[] = data; 58 | data = new int[ 2* temp.length]; 59 | int index = 0; 60 | for(int i = front ; i < temp.length; i++){ 61 | data[index] = temp[i]; 62 | index++; 63 | } 64 | for(int i = 0; i <= front - 1;i++){ 65 | data[index] = temp[i]; 66 | index++; 67 | } 68 | front = 0; 69 | rear = temp.length - 1; 70 | } 71 | 72 | 73 | int dequeue() throws QueueEmptyException{ 74 | if(size == 0){ 75 | throw new QueueEmptyException(); 76 | } 77 | int temp = data[front]; 78 | front = (front + 1) % data.length; 79 | // front++; 80 | // if(front == data.length){ 81 | // front = 0; 82 | // } 83 | size--; 84 | if(size == 0){ 85 | front = -1; 86 | rear = -1; 87 | } 88 | return temp; 89 | } 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | } 101 | -------------------------------------------------------------------------------- /Stack and Queue/src/Queueusell.java: -------------------------------------------------------------------------------- 1 | public class Queueusell { 2 | private Node front; 3 | private Node rear; 4 | private int size; 5 | 6 | public Queueusell() { 7 | this.front=this.rear=null; 8 | this.size=0; 9 | } 10 | 11 | public int size() { 12 | return size; 13 | } 14 | 15 | public boolean isEmpty() { 16 | if(size==0){ 17 | return true; 18 | } 19 | return false; 20 | } 21 | public T front() throws QueueEmptyException { 22 | if(size==0){ 23 | throw new QueueEmptyException(); 24 | } 25 | return front.data; 26 | } 27 | 28 | public void enqueue(T data) { 29 | Node temp = new Node(data); 30 | // If queue is empty, then new node is front and rear both 31 | if (this.rear == null) 32 | { 33 | front = rear = temp; 34 | size++; 35 | return; 36 | } 37 | 38 | // Add the new node at the end of queue and change rear 39 | this.rear.next = temp; 40 | this.rear = temp; 41 | // i just dont understand the above 2 lines work 42 | this.size++; 43 | } 44 | 45 | // public T dequeue() throws QueueEmptyException { 46 | // if(size==0){ 47 | // throw new QueueEmptyException(); 48 | 49 | // } 50 | // T tempdata = front.data; 51 | // front = front.next; 52 | // size--; 53 | // return tempdata; 54 | // } 55 | public T dequeue() throws QueueEmptyException { 56 | if(isEmpty()) { 57 | QueueEmptyException e = new QueueEmptyException(); 58 | throw e; 59 | } 60 | Node temp = front; 61 | if(size == 1) { 62 | front = null; 63 | rear = null; 64 | } 65 | else { 66 | front = front.next; 67 | temp.next = null; 68 | } 69 | size--; 70 | return temp.data; 71 | } 72 | } 73 | 74 | -------------------------------------------------------------------------------- /Stack and Queue/src/ReverseStack.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Solution { 4 | public static Stack reverse(Stack s1,Stack s2) { 5 | Stack ketan= new Stack(); 6 | if(s1.isEmpty()){ 7 | return ketan; 8 | } 9 | int k=s1.pop(); 10 | reverse(s1,s2); 11 | int j; 12 | while(!s1.isEmpty()){ 13 | j=s1.pop(); 14 | s2.push(j); 15 | } 16 | s2.push(k); 17 | while(!s2.isEmpty()){ 18 | j=s2.pop(); 19 | s1.push(j); 20 | } 21 | return s1; 22 | } 23 | 24 | public static void reverseStack(Stack s1, Stack s2) { 25 | reverse(s1,s2); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Stack and Queue/src/StackEmptyException.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackEmptyException extends Exception { 3 | 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 1L; 8 | 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Stack and Queue/src/StackFullException.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackFullException extends Exception { 3 | 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 1L; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Stack and Queue/src/StackUse.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackUse { 3 | 4 | public static void main(String[] args) throws StackFullException { 5 | 6 | StackUsingArray stack = new StackUsingArray(3); 7 | for(int i = 1; i <= 5; i++){ 8 | stack.push(i); 9 | } 10 | 11 | while(!stack.isEmpty()){ 12 | try { 13 | System.out.println(stack.pop()); 14 | } catch (StackEmptyException e) { 15 | // Never reach here 16 | } 17 | } 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Stack and Queue/src/StackUseLinkedlist.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackUseLinkedlist { 3 | 4 | public static void main(String[] args) throws StackFullException { 5 | 6 | StackUsingLL stack = new StackUsingLL<>(); 7 | 8 | // StackUsingArray stack = new StackUsingArray(3); 9 | for(int i = 1; i <= 5; i++){ 10 | stack.push(i); 11 | } 12 | 13 | while(!stack.isEmpty()){ 14 | try { 15 | System.out.println(stack.pop()); 16 | } catch (StackEmptyException e) { 17 | // Never reach here 18 | } 19 | } 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Stack and Queue/src/StackUsingArray.java: -------------------------------------------------------------------------------- 1 | public class StackUsingArray { 2 | 3 | private int data[]; 4 | private int top; // is the index of topmost element of stack 5 | 6 | public StackUsingArray() { 7 | data = new int[10]; 8 | top = -1; 9 | } 10 | 11 | public StackUsingArray(int capacity) { 12 | data = new int[capacity]; 13 | top = -1; 14 | } 15 | 16 | public boolean isEmpty(){ 17 | // if(top == -1){ 18 | // return true; 19 | // }else{ 20 | // return false; 21 | // } 22 | return (top == -1); 23 | } 24 | 25 | public int size(){ 26 | return top + 1; 27 | } 28 | 29 | public int top() throws StackEmptyException{ 30 | if(size() == 0){ 31 | //StackEmptyException 32 | StackEmptyException e = new StackEmptyException(); 33 | throw e; 34 | } 35 | return data[top]; 36 | } 37 | 38 | public void push(int elem) throws StackFullException{ 39 | if(size() == data.length){ 40 | // // Stack Full 41 | // StackFullException e = new StackFullException(); 42 | // throw e; 43 | doubleCapacity(); 44 | 45 | } 46 | top++; 47 | data[top] = elem; 48 | } 49 | 50 | private void doubleCapacity() { 51 | int temp[] = data; 52 | data = new int[2 * temp.length]; 53 | for(int i = 0; i <= top; i++){ 54 | data[i] = temp[i]; 55 | } 56 | 57 | } 58 | 59 | public int pop() throws StackEmptyException{ 60 | if(size() == 0){ 61 | //StackEmptyException 62 | StackEmptyException e = new StackEmptyException(); 63 | throw e; 64 | } 65 | int temp = data[top]; 66 | top--; 67 | return temp; 68 | 69 | } 70 | 71 | 72 | 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /Stack and Queue/src/StackUsingLL.java: -------------------------------------------------------------------------------- 1 | public class StackUsingLL { 2 | private Node head; 3 | private int size; 4 | 5 | public StackUsingLL() { 6 | head = null; 7 | size = 0; 8 | } 9 | 10 | int size(){ 11 | return size; 12 | } 13 | boolean isEmpty(){ 14 | return size() == 0; // head == null 15 | } 16 | 17 | T top() throws StackEmptyException{ 18 | if(size() == 0){ 19 | //StackEmptyException e = new StackEmptyException(); 20 | //throw e; 21 | throw new StackEmptyException(); 22 | } 23 | return head.data; 24 | } 25 | 26 | void push(T element){ 27 | 28 | Node newNode = new Node(element); 29 | newNode.next = head; 30 | head = newNode; 31 | size++; 32 | 33 | } 34 | 35 | T pop() throws StackEmptyException{ 36 | if(size() == 0){ 37 | //StackEmptyException e = new StackEmptyException(); 38 | //throw e; 39 | throw new StackEmptyException(); 40 | } 41 | T tempdata = head.data; 42 | head = head.next; 43 | size--; 44 | return tempdata; 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Stack and Queue/src/checkRedundantBrackets.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class solution { 4 | public static boolean checkRedundantBrackets(String input) { 5 | // create a stack of characters 6 | Stack st = new Stack<>(); 7 | char[] str = input.toCharArray(); 8 | // Iterate through the given expression 9 | for (char ch : str) { 10 | 11 | // if current character is close parenthesis ')' 12 | if (ch == ')') { 13 | char top = st.peek(); 14 | st.pop(); 15 | 16 | // If immediate pop have open parenthesis '(' 17 | // duplicate brackets found 18 | boolean flag = true; 19 | 20 | while (top != '(') { 21 | 22 | // Check for operators in expression 23 | if (top == '+' || top == '-' 24 | || top == '*' || top == '/') { 25 | flag = false; 26 | } 27 | 28 | // Fetch top element of stack 29 | top = st.peek(); 30 | st.pop(); 31 | } 32 | 33 | // If operators not found 34 | if (flag == true) { 35 | return true; 36 | } 37 | } else { 38 | st.push(ch); // push open parenthesis '(', 39 | } // operators and operands to stack 40 | } 41 | return false; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Stack and Queue/src/queue important.java: -------------------------------------------------------------------------------- 1 | Queue Interface In Java 2 | The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle. Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java.It is to be noted that both the implementations are not thread safe. PriorityBlockingQueue is one alternative implementation if thread safe implementation is needed. Few important characteristics of Queue are: 3 | 4 | The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept. 5 | The Java Queue supports all methods of Collection interface including insertion, deletion etc. 6 | LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations. 7 | If any null operation is performed on BlockingQueues, NullPointerException is thrown. 8 | 9 | BlockingQueues have thread-safe implementations. 10 | The Queues which are available in java.util package are Unbounded Queues 11 | The Queues which are available in java.util.concurrent package are the Bounded Queues. 12 | All Queues except the Deques supports insertion and removal at the tail and head of the queue respectively. The Deques support element insertion and removal at both ends. 13 | Methods in Queue: 14 | 15 | add()- This method is used to add elements at the tail of queue. More specifically, at the last of linked-list if it is used, or according to the priority in case of priority queue implementation. 16 | peek()- This method is used to view the head of queue without removing it. It returns Null if the queue is empty. 17 | element()- This method is similar to peek(). It throws NoSuchElementException when the queue is empty. 18 | remove()- This method removes and returns the head of the queue. It throws NoSuchElementException when the queue is empty. 19 | poll()- This method removes and returns the head of the queue. It returns null if the queue is empty. 20 | size()- This method return the no. of elements in the queue. 21 | 22 | 23 | Since it is a subtype of Collections class, it inherits all the methods of it namely size(), isEmpty(), contains() etc. 24 | Below is a simple Java program to demonstrate these methods: 25 | 26 | filter_none 27 | edit 28 | play_arrow 29 | 30 | brightness_4 31 | // Java orogram to demonstrate working of Queue 32 | // interface in Java 33 | import java.util.LinkedList; 34 | import java.util.Queue; 35 | 36 | public class QueueExample 37 | { 38 | public static void main(String[] args) 39 | { 40 | Queue q = new LinkedList<>(); 41 | 42 | // Adds elements {0, 1, 2, 3, 4} to queue 43 | for (int i=0; i<5; i++) 44 | q.add(i); 45 | 46 | // Display contents of the queue. 47 | System.out.println("Elements of queue-"+q); 48 | 49 | // To remove the head of queue. 50 | int removedele = q.remove(); 51 | System.out.println("removed element-" + removedele); 52 | 53 | System.out.println(q); 54 | 55 | // To view the head of queue 56 | int head = q.peek(); 57 | System.out.println("head of queue-" + head); 58 | 59 | // Rest all methods of collection interface, 60 | // Like size and contains can be used with this 61 | // implementation. 62 | int size = q.size(); 63 | System.out.println("Size of queue-" + size); 64 | } 65 | } 66 | Output: 67 | Elements of queue-[0, 1, 2, 3, 4] 68 | removed element-0 69 | [1, 2, 3, 4] 70 | head of queue-1 71 | Size of queue-4 72 | -------------------------------------------------------------------------------- /Stack and Queue/src/queueusingll.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class queueusingll { 3 | 4 | public static void main(String[] args) { 5 | @SuppressWarnings("resource") 6 | Scanner s = new Scanner(System.in); 7 | 8 | Queueusell st = new Queueusell(); 9 | 10 | int choice = s.nextInt(); 11 | int input; 12 | 13 | while (choice !=-1) { 14 | if(choice == 1) { 15 | input = s.nextInt(); 16 | st.enqueue(input); 17 | } 18 | else if(choice == 2) { 19 | try { 20 | System.out.println(st.dequeue()); 21 | } catch (QueueEmptyException e) { 22 | System.out.println(-1); 23 | } 24 | } 25 | else if(choice == 3) { 26 | try { 27 | System.out.println(st.front()); 28 | } catch (QueueEmptyException e) { 29 | System.out.println(-1); 30 | } 31 | } 32 | else if(choice == 4) { 33 | System.out.println(st.size()); 34 | } 35 | else if(choice == 5) { 36 | System.out.println(st.isEmpty()); 37 | } 38 | choice = s.nextInt(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Stack and Queue/src/reversequeue.java: -------------------------------------------------------------------------------- 1 | /********** Given Queue Class ************** 2 | // You can directly use these functions 3 | 4 | class Queue { 5 | 6 | public int size(); 7 | 8 | public boolean isEmpty(); 9 | 10 | public T front(); 11 | 12 | public void enqueue(T element); 13 | 14 | public T dequeue(); 15 | } 16 | 17 | **********************************/ 18 | 19 | 20 | 21 | public class Solution { 22 | 23 | public static void reverseQueue(Queue q) { 24 | if(q.isEmpty()){ 25 | //q.size()<=1 26 | return; 27 | } 28 | int top=q.dequeue(); 29 | reverseQueue(q); 30 | q.enqueue(top); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Stack and Queue/src/stack important.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | Methods in Stack class 3 | 4 | 1 Object push(Object element) : Pushes an element on the top of the stack. 5 | 2 Object pop() : Removes and returns the top element of the stack. An ‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack is empty. 6 | 3 Object peek() : Returns the element on the top of the stack, but does not remove it. 7 | 4 boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false. 8 | 5 int search(Object element) : It determines whether an object exists in the stack. If the element is found, it returns the 9 | position of the element from the top of the stack. Else, it returns -1. 10 | -------------------------------------------------------------------------------- /Stack and Queue/src/stockSpan.java: -------------------------------------------------------------------------------- 1 | //made by ketan mehta 2 | import java.util.*; 3 | public class Solution { 4 | 5 | public static int[] stockSpan(int[] price) { 6 | Stack index = new Stack<>(); 7 | int i=0; 8 | int peek=0; 9 | int arr[]=new int[price.length]; 10 | while(i=price[i]){ 17 | index.push(i); 18 | arr[i]=1; 19 | }else{ 20 | peek=index.peek(); 21 | while(price[peek] st = new Stack<>(); 50 | // st.push(0); 51 | // int S[] = new int[price.length]; 52 | // S[0] = 1; 53 | // int x= 0 ; 54 | 55 | // for (int i = 1; i < price.length ; i++) 56 | // { 57 | 58 | // // Pop elements from stack while stack is not 59 | // // empty and top of stack is smaller than 60 | // // price[i] 61 | // while (!st.empty() && price[st.peek()] < price[i]) 62 | // x= st.pop(); 63 | 64 | // // If stack becomes empty, then price[i] is 65 | // // greater than all elements on left of it, i.e., 66 | // // price[0], price[1], ..price[i-1]. Else price[i] 67 | // // is greater than elements after top of stack 68 | // if(st.empty()) 69 | // { 70 | // if(price[x]==price[i]) 71 | // S[i]=1 ; 72 | // else 73 | // S[i]=i+1 ; 74 | // } 75 | // else 76 | // { 77 | // S[i]=i-st.peek(); 78 | // } 79 | 80 | // // Push this element to stack 81 | // st.push(i); 82 | // } 83 | // return S ; 84 | // } 85 | // } 86 | -------------------------------------------------------------------------------- /TEST 2/Deletealternatenodes.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | class LinkedListNode { 4 | public T data; 5 | public LinkedListNode next; 6 | public LinkedListNode(T data) { 7 | this.setData(data); 8 | this.next = null; 9 | } 10 | public T getData() { 11 | return data; 12 | } 13 | public void setData(T data) { 14 | this.data = data; 15 | } 16 | } */ 17 | public class Solution { 18 | public static void deleteAlternateNodes(LinkedListNode head) { 19 | while(head.next!=null){ 20 | if(head.next.next!=null){ 21 | head.next=head.next.next; 22 | head=head.next; 23 | }else{ 24 | head.next=null; 25 | } 26 | } 27 | } 28 | } 29 | // Delete alternate nodes 30 | // Send Feedback 31 | // Given a linked list, delete all alternate nodes in the list. That means given Linked List is - 32 | // 10 20 30 40 50 60 33 | // you need to delete nodes - 20, 40 and 60 34 | // Note : Head of the list will remain same. Don't need to print or return anything. 35 | // Input Constraints: 36 | // 1 <= Length of Linked List <=10^6. 37 | // Input format : 38 | // Linked list elements (separated by space and terminated by -1) 39 | // Output Format : 40 | // Updated linked list elements 41 | // Sample Input : 42 | // 1 2 3 4 5 -1 43 | // Sample Output : 44 | // 1 3 5 45 | -------------------------------------------------------------------------------- /TEST 2/NextNumber.java: -------------------------------------------------------------------------------- 1 | /*************** 2 | * Following is the Node class already written 3 | class LinkedListNode { 4 | T data; 5 | LinkedListNode next; 6 | 7 | public LinkedListNode(T data) { 8 | this.data = data; 9 | } 10 | } 11 | ***************/ 12 | public class Solution { 13 | public static LinkedListNode nextLargeNumber(LinkedListNode head) { 14 | LinkedListNode temp; 15 | LinkedListNode prev =null; 16 | LinkedListNode curr=head; 17 | while(curr!=null){ 18 | temp=curr.next; 19 | curr.next=prev; 20 | prev=curr; 21 | curr=temp; 22 | } 23 | LinkedListNode tem=prev; 24 | int extra=0; 25 | LinkedListNode a= new LinkedListNode(1); 26 | while(tem!=null){ 27 | if(tem.data==9){ 28 | tem.data=0; 29 | extra=1; 30 | if(tem.next==null){ 31 | tem.next=a; 32 | } 33 | }else{ 34 | if(extra==1){ 35 | int d=tem.data+1; 36 | if(d==10){ 37 | tem.data=0; 38 | extra=1; 39 | }else{ 40 | extra=0; 41 | } 42 | }else{ 43 | tem.data=tem.data+1; 44 | break; 45 | }} 46 | tem=tem.next; 47 | } 48 | LinkedListNode temp1; 49 | LinkedListNode prev1 =null; 50 | LinkedListNode curr1=prev; 51 | while(curr1!=null){ 52 | temp1=curr1.next; 53 | curr1.next=prev1; 54 | prev1=curr1; 55 | curr1=temp1; 56 | } 57 | return prev1; 58 | } 59 | } 60 | // Given a large number represented in the form of a linked list. Write code to increment the number by 1 in-place(i.e. without using extra space). 61 | // Note: You don't need to print the elements, just update the elements and return the head of updated LL. 62 | // Input Constraints: 63 | // 1 <= Length of Linked List <=10^6. 64 | // Input format : 65 | // Line 1 : Linked list elements (separated by space and terminated by -1) 66 | // Output Format : 67 | // Line 1: Updated linked list elements 68 | // Sample Input 1 : 69 | // 3 9 2 5 -1 70 | // Sample Output 1 : 71 | // 3 9 2 6 72 | // Sample Input 2 : 73 | // 9 9 9 -1 74 | // Sample Output 1 : 75 | // 1 0 0 0 76 | // concept 77 | // the main concept for this question is that we first reverse the linked list and the do the process 78 | // and after it we again reverse the linked list 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/BinaryTreeNode.java: -------------------------------------------------------------------------------- 1 | package BinaryTrees; 2 | 3 | public class BinaryTreeNode { 4 | public BinaryTreeNode(T data) { 5 | this.data = data; 6 | } 7 | public T data; 8 | public BinaryTreeNode left; 9 | public BinaryTreeNode right; 10 | } 11 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/ConstructTreefromPostorderandInorder.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /* Binary Tree Node class 4 | * 5 | * class BinaryTreeNode { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | 16 | public static BinaryTreeNode help(int[] post,int[] in,int inS,int inE,int preS,int preE){ 17 | if(inS > inE) 18 | return null; 19 | 20 | int root=post[preE]; 21 | BinaryTreeNode ans=new BinaryTreeNode(root); 22 | int index=-1; 23 | for(int i=0;i getTreeFromPostorderAndInorder(int[] post,int[] in){ 48 | return help(post,in,0,in.length-1,0,post.length-1); 49 | } 50 | 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/ConstructTreefromPreorderAndInorder.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static int preindex = 0; 3 | public static BinaryTreeNode help(int[] pre,int[] in,int ins,int ine){ 4 | if (ins > ine) 5 | return null; 6 | int root=pre[preindex++]; 7 | BinaryTreeNode ans=new BinaryTreeNode(root); 8 | int index=-1; 9 | for(int i=0;i getTreeFromPreorderAndInorder(int[] pre,int[] in){ 29 | return help(pre,in,0,in.length-1); 30 | } 31 | } 32 | // Time Complexity: O(n^2). Worst case occurs when tree is 33 | // left skewed. Example Preorder and Inorder traversals for 34 | // worst case are {A, B, C, D} and {D, C, B, A}. 35 | // Efficient Approach : 36 | // We can optimize the above solution using hashing (unordered_map in C++ or HashMap in Java). We store indexes of inorder traversal in a hash table. So that search can be done O(1) time. 37 | // filter_none 38 | // below is the same method but we are not using the static variable for pres 39 | // public static BinaryTreeNode help(int[] pre,int[] in,int inS,int inE,int preS,int preE){ 40 | // if(inS > inE) 41 | // return null; 42 | 43 | // int root=pre[preS]; 44 | // BinaryTreeNode ans=new BinaryTreeNode(root); 45 | // int index=-1; 46 | // for(int i=0;i getTreeFromPreorderAndInorder(int[] pre,int[] in){ 73 | // return help(pre,in,0,in.length-1,0,pre.length-1); 74 | // } 75 | 76 | // } 77 | 78 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/Levelwiselinkedlist.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | public class Solution { 3 | public static ArrayList>> LLForEachLevel(BinaryTreeNode root) { 4 | QueueUsingLL> q =new QueueUsingLL>(); 5 | ArrayList>> arr=new ArrayList>>(); 6 | Node> head=null; 7 | Node> tail=null; 8 | q.enqueue(root); 9 | q.enqueue(null); 10 | // first insert the root and null in the queue 11 | // so that we can know the level is fully traversed or not 12 | while(!q.isEmpty()) { 13 | BinaryTreeNode temp= null; 14 | try{ 15 | temp = q.dequeue(); 16 | } 17 | catch (QueueEmptyException e){} 18 | if(temp==null){ 19 | // if the node which is dequeued is null than 20 | // it has two meaning 21 | // one is that the level is completed and the tree traversal is completed 22 | arr.add(head); 23 | head=null; 24 | tail=null; 25 | if(q.isEmpty()){ 26 | break; 27 | } 28 | q.enqueue(null); 29 | continue; 30 | } 31 | else{ 32 | if(temp.left!=null) 33 | q.enqueue(temp.left); 34 | // insert the childrens 35 | if(temp.right!=null) 36 | q.enqueue(temp.right); 37 | 38 | Node> ans1=new Node>(temp); 39 | if(head==null){ 40 | // check if this is the first node and if it is then we assign the both variables to ans1 41 | head=ans1; 42 | tail=ans1; 43 | } 44 | else{ 45 | // we are using tail 46 | // if we dont use the tail then we have to traverse the linked list again which make the algo worthless 47 | tail.next=ans1; 48 | tail=tail.next; 49 | } 50 | } 51 | } 52 | return arr; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/Node.java: -------------------------------------------------------------------------------- 1 | package BinaryTrees; 2 | 3 | 4 | public class Node { 5 | 6 | T data; 7 | Node next; 8 | 9 | Node(T data){ 10 | this.data = data; 11 | next = null; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/Pair.java: -------------------------------------------------------------------------------- 1 | package BinaryTrees; 2 | 3 | public class Pair { 4 | public T first; 5 | public V second; 6 | } 7 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/QueueEmptyException.java: -------------------------------------------------------------------------------- 1 | package BinaryTrees; 2 | 3 | 4 | public class QueueEmptyException extends Exception { 5 | 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 7243921724361015813L; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Trees/src/BinaryTrees/QueueUsingLL.java: -------------------------------------------------------------------------------- 1 | package BinaryTrees; 2 | 3 | 4 | public class QueueUsingLL { 5 | 6 | private Node front; 7 | private Node rear; 8 | private int size; 9 | 10 | public QueueUsingLL() { 11 | front = null; 12 | rear = null; 13 | size = 0; 14 | } 15 | int size(){ 16 | return size; 17 | } 18 | 19 | boolean isEmpty(){ 20 | return size == 0; 21 | } 22 | 23 | T front() throws QueueEmptyException{ 24 | if(size == 0){ 25 | throw new QueueEmptyException(); 26 | } 27 | return front.data; 28 | } 29 | 30 | void enqueue(T element){ 31 | Node newNode = new Node<>(element); 32 | if(rear == null){ 33 | front = newNode; 34 | rear = newNode; 35 | }else{ 36 | rear.next = newNode; 37 | rear = newNode; 38 | } 39 | size++; 40 | 41 | } 42 | 43 | T dequeue() throws QueueEmptyException{ 44 | if(size == 0){ 45 | throw new QueueEmptyException(); 46 | } 47 | 48 | T temp = front.data; 49 | front = front.next; 50 | if(size == 1){ 51 | rear = null; 52 | } 53 | size--; 54 | 55 | return temp; 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Trees/src/Node.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class Node { 4 | 5 | T data; 6 | Node next; 7 | 8 | Node(T data){ 9 | this.data = data; 10 | next = null; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Trees/src/QueueEmptyException.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class QueueEmptyException extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = 7243921724361015813L; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Trees/src/QueueUsingLL.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class QueueUsingLL { 4 | 5 | private Node front; 6 | private Node rear; 7 | private int size; 8 | 9 | public QueueUsingLL() { 10 | front = null; 11 | rear = null; 12 | size = 0; 13 | } 14 | int size(){ 15 | return size; 16 | } 17 | 18 | boolean isEmpty(){ 19 | return size == 0; 20 | } 21 | 22 | T front() throws QueueEmptyException{ 23 | if(size == 0){ 24 | throw new QueueEmptyException(); 25 | } 26 | return front.data; 27 | } 28 | 29 | void enqueue(T element){ 30 | Node newNode = new Node<>(element); 31 | if(rear == null){ 32 | front = newNode; 33 | rear = newNode; 34 | }else{ 35 | rear.next = newNode; 36 | rear = newNode; 37 | } 38 | size++; 39 | 40 | } 41 | 42 | T dequeue() throws QueueEmptyException{ 43 | if(size == 0){ 44 | throw new QueueEmptyException(); 45 | } 46 | 47 | T temp = front.data; 48 | front = front.next; 49 | if(size == 1){ 50 | rear = null; 51 | } 52 | size--; 53 | 54 | return temp; 55 | } 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Trees/src/TreeNode.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class TreeNode { 4 | public T data; 5 | public ArrayList> children; 6 | 7 | public TreeNode(T data) { 8 | this.data = data; 9 | children = new ArrayList<>(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Trees/src/binarysearchtree/BinaryTreeNode.java: -------------------------------------------------------------------------------- 1 | package binarysearchtree; 2 | 3 | public class BinaryTreeNode { 4 | public BinaryTreeNode(T data) { 5 | this.data = data; 6 | } 7 | public T data; 8 | public BinaryTreeNode left; 9 | public BinaryTreeNode right; 10 | } 11 | -------------------------------------------------------------------------------- /Trees/src/binarysearchtree/Pair.java: -------------------------------------------------------------------------------- 1 | package binarysearchtree; 2 | 3 | public class Pair { 4 | public T first; 5 | public V second; 6 | } 7 | -------------------------------------------------------------------------------- /Trees/src/binarysearchtree/PathSumRoottoLeaf.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /* Binary Tree Node class 4 | * 5 | * class BinaryTreeNode { 6 | T data; 7 | BinaryTreeNode left; 8 | BinaryTreeNode right; 9 | 10 | public BinaryTreeNode(T data) { 11 | this.data = data; 12 | } 13 | } 14 | */ 15 | public static void rootToLeafPathsSumToK(BinaryTreeNode root, int k,String ans) { 16 | if(k==root.data){ 17 | if(root.right==null&&root.left==null){ 18 | System.out.println(ans+" "+root.data); 19 | return; 20 | }else{ 21 | return; 22 | } 23 | } 24 | 25 | if(root.left!=null){ 26 | if(ans=="") 27 | rootToLeafPathsSumToK(root.left ,k-root.data,ans+root.data); 28 | else{ 29 | rootToLeafPathsSumToK(root.left ,k-root.data,ans+" "+root.data); 30 | } 31 | } 32 | if(root.right!=null){ 33 | if(ans=="") 34 | rootToLeafPathsSumToK(root.right ,k-root.data,ans+root.data); 35 | else{ 36 | rootToLeafPathsSumToK(root.right ,k-root.data,ans+" "+root.data); 37 | } 38 | } 39 | } 40 | public static void rootToLeafPathsSumToK(BinaryTreeNode root, int k) { 41 | rootToLeafPathsSumToK(root,k,""); 42 | } 43 | } 44 | // // below is the solution 45 | // import java.util.ArrayList; 46 | // public class Solution { 47 | // public static void rootToLeafPathsSumToK(BinaryTreeNode root, ArrayList path, int k) { 48 | // if(root == null) { 49 | // return; 50 | // } 51 | // k -= root.data; 52 | // path.add(root.data); 53 | // if(root.left == null && root.right == null) { 54 | // if(k == 0) { 55 | // for(int i : path) { 56 | // System.out.print(i + " "); 57 | // } 58 | // System.out.println(); 59 | // } 60 | // path.remove(path.size() - 1); 61 | // return; 62 | // } 63 | // rootToLeafPathsSumToK(root.left, path, k); 64 | // rootToLeafPathsSumToK(root.right, path, k); 65 | // path.remove(path.size() - 1); 66 | // } 67 | // public static void rootToLeafPathsSumToK(BinaryTreeNode root, int k) { 68 | // ArrayList path = new ArrayList(); 69 | // rootToLeafPathsSumToK(root, path, k); 70 | // } 71 | // } 72 | -------------------------------------------------------------------------------- /Tries and Huffman Coding/Autocomplete.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TrieNode{ 3 | char data; 4 | boolean isTerminating; 5 | TrieNode children[]; 6 | int childCount; 7 | 8 | public TrieNode(char data) { 9 | this.data = data; 10 | isTerminating = false; 11 | children = new TrieNode[26]; 12 | childCount = 0; 13 | } 14 | } 15 | 16 | public class Trie { 17 | private TrieNode root; 18 | 19 | public Trie() { 20 | root = new TrieNode('\0'); 21 | } 22 | 23 | private void add(TrieNode root, String word){ 24 | if(word.length() == 0){ 25 | root.isTerminating = true; 26 | return; 27 | } 28 | int childIndex = word.charAt(0) - 'a'; 29 | TrieNode child = root.children[childIndex]; 30 | if(child == null){ 31 | child = new TrieNode(word.charAt(0)); 32 | root.children[childIndex] = child; 33 | root.childCount++; 34 | } 35 | add(child, word.substring(1)); 36 | } 37 | 38 | public void add(String word){ 39 | add(root, word); 40 | } 41 | 42 | public TrieNode findword(TrieNode root, String word) { 43 | if(word.length() == 0){ 44 | return root; 45 | } 46 | int childIndex = word.charAt(0) - 'a'; 47 | TrieNode child = root.children[childIndex]; 48 | if(child == null){ 49 | return null; 50 | } 51 | return findword(child, word.substring(1)); 52 | } 53 | 54 | public void allwords(TrieNode root,String word,String output){ 55 | if(root.childCount == 0) { 56 | if(output.length() > 0) { 57 | System.out.println(word + output); 58 | } 59 | return; 60 | } 61 | if(root.isTerminating == true) { 62 | System.out.println(word + output); 63 | } 64 | 65 | for(int i = 0; i < root.children.length; i++) { 66 | if(root.children[i] != null) { 67 | String ans = output + root.children[i].data; 68 | allwords(root.children[i],word,ans); 69 | } 70 | } 71 | } 72 | public void autoComplete(ArrayList input, String word){ 73 | // for(String w : input) { 74 | // add(w); 75 | // } 76 | int i=0; 77 | while(i vect) 51 | { 52 | ArrayList s=new ArrayList<>(); 53 | for(int i=0;i input, String pattern) { 58 | for (int i = 0; i < input.size(); i++) { 59 | String word = input.get(i); 60 | for (int j = 0; j < word.length(); j++) { 61 | add(word.substring(j)); 62 | } 63 | } 64 | return search(pattern); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Tries and Huffman Coding/SearchWordsInTries.java: -------------------------------------------------------------------------------- 1 | class TrieNode{ 2 | 3 | char data; 4 | boolean isTerminating; 5 | TrieNode children[]; 6 | int childCount; 7 | 8 | public TrieNode(char data) { 9 | this.data = data; 10 | isTerminating = false; 11 | children = new TrieNode[26]; 12 | childCount = 0; 13 | } 14 | } 15 | 16 | public class Trie { 17 | 18 | private TrieNode root; 19 | public int count; 20 | public Trie() { 21 | root = new TrieNode('\0'); 22 | count = 0; 23 | } 24 | 25 | private boolean add(TrieNode root, String word){ 26 | if(word.length() == 0){ 27 | if (!root.isTerminating) { 28 | root.isTerminating = true; 29 | return true; 30 | } else { 31 | return false; 32 | } 33 | } 34 | int childIndex = word.charAt(0) - 'a'; 35 | TrieNode child = root.children[childIndex]; 36 | if(child == null){ 37 | child = new TrieNode(word.charAt(0)); 38 | root.children[childIndex] = child; 39 | root.childCount++; 40 | } 41 | return add(child, word.substring(1)); 42 | } 43 | 44 | public void add(String word){ 45 | if (add(root, word)) { 46 | this.count++; 47 | } 48 | } 49 | public boolean searchhealper(TrieNode root,String word){ 50 | if(word.length() == 0){ 51 | return root.isTerminating; 52 | } 53 | int childIndex = word.charAt(0) - 'a'; 54 | TrieNode child = root.children[childIndex]; 55 | if(child == null){ 56 | return false; 57 | } 58 | return searchhealper(child,word.substring(1)); 59 | } 60 | public boolean search(String word){ 61 | return searchhealper(root,word); 62 | } 63 | 64 | 65 | } 66 | -------------------------------------------------------------------------------- /codechef/src/codechef/EVENT.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | import java.util.stream.IntStream; 4 | 5 | public class Main { 6 | static final String[] DAY_NAMES = { "saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday" }; 7 | 8 | public static void main(String[] args) { 9 | Scanner sc = new Scanner(System.in); 10 | 11 | int T = sc.nextInt(); 12 | for (int tc = 0; tc < T; tc++) { 13 | String S = sc.next(); 14 | String E = sc.next(); 15 | int L = sc.nextInt(); 16 | int R = sc.nextInt(); 17 | 18 | System.out.println(solve(S, E, L, R)); 19 | } 20 | 21 | sc.close(); 22 | } 23 | 24 | static String solve(String S, String E, int L, int R) { 25 | int startIndex = Arrays.asList(DAY_NAMES).indexOf(S); 26 | int[] durations = IntStream.rangeClosed(L, R) 27 | .filter(d -> DAY_NAMES[(startIndex + d - 1) % DAY_NAMES.length].equals(E)).toArray(); 28 | 29 | if (durations.length == 0) { 30 | return "impossible"; 31 | } else if (durations.length >= 2) { 32 | return "many"; 33 | } else { 34 | return String.valueOf(durations[0]); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /codechef/src/codechef/MDL.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TestPQ 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner H = new Scanner(System.in); 7 | int T = H.nextInt(); 8 | int b[][] = new int[T][2]; 9 | int t1,t2,t3; 10 | int c = 0; 11 | for(int i=0;it2) 18 | { 19 | t3 = t2; 20 | t2 = t1; 21 | t1 = t3; 22 | c = 1; 23 | } 24 | for(int j=2;jt2) 28 | { 29 | t2 = t3; 30 | c = 0; 31 | } 32 | else if(t30){ 10 | int num=k.nextInt(); 11 | int count=0; 12 | int x=1; 13 | while(num>0){ 14 | if(((num/((int)Math.pow(2,x)))!=0)&&x<13){ 15 | x++; 16 | } 17 | else 18 | { 19 | num=num-(int)Math.pow(2,x-1); 20 | x=1; 21 | count++; 22 | } 23 | } 24 | System.out.println(count); 25 | 26 | n--;} 27 | 28 | }} -------------------------------------------------------------------------------- /codechef/src/codechef/Strch.java: -------------------------------------------------------------------------------- 1 | package codechef; 2 | import java.util.Scanner; 3 | public class Strch { 4 | public static void main (String[] args) throws java.lang.Exception{ 5 | 6 | Scanner s = new Scanner(System.in); 7 | int t = s.nextInt(); 8 | while(t>0){ 9 | int a=s.nextInt(); 10 | String str = s.next(); 11 | char check = s.next().charAt(0); 12 | int j,i=0; 13 | int max=0; 14 | for(i=0;iroot.data){ 55 | root.right=insertKey(root.right,key,2*pos+1); 56 | } 57 | return root; 58 | } 59 | void delete(int key){ 60 | root=deleteKey(root,key); 61 | } 62 | Node deleteKey(Node root,int key){ 63 | if(root.data==key){ 64 | System.out.println(root.pos); 65 | if(root.right==null) 66 | return root.left; 67 | else if(root.left==null) 68 | return root.right; 69 | 70 | root.data=min(root.right); 71 | root.right=deleteKey(root.right,root.data); 72 | }else if(key<=root.data) 73 | root.left=deleteKey(root.left,key); 74 | else if(key>root.data) 75 | root.right=deleteKey(root.right,key); 76 | return root; 77 | } 78 | int min(Node root){ 79 | Node node=root; 80 | while(node.left!=null){ 81 | node=node.left; 82 | } 83 | return node.data; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /codechef/src/codechef/chnum.java: -------------------------------------------------------------------------------- 1 | package codechef; 2 | import java.util.*; 3 | public class chnum { 4 | public static void main (String[] args) throws java.lang.Exception 5 | { 6 | @SuppressWarnings("resource") 7 | Scanner s = new Scanner(System.in); 8 | int t = s.nextInt(); 9 | while(t>0){ 10 | int size = s.nextInt(); 11 | int arr[] = new int[size]; 12 | for (int i = 0; i < size; i++) { 13 | arr[i] = s.nextInt(); 14 | 15 | } 16 | 17 | int i,j=0,m=0,q=0; 18 | for(i=0;i0){ 20 | j++; 21 | } 22 | else if(arr[i]<0){ 23 | m++; 24 | } 25 | else{ 26 | q++; 27 | } 28 | } 29 | if(j>m){ 30 | q=j+q; 31 | System.out.print(q+" "+j); 32 | }else{ 33 | q=m+q; 34 | System.out.print(q+" "+m); 35 | } 36 | --t; 37 | } 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /codechef/src/codechef/jj.java: -------------------------------------------------------------------------------- 1 | package codechef; 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | class jj{ 7 | public static void main (String[] args) throws java.lang.Exception 8 | { 9 | Scanner s = new Scanner(System.in); 10 | int t = s.nextInt(); 11 | while(t>0){ 12 | int total=s.nextInt(); 13 | String str=s.nextLine(); 14 | int count=0; 15 | int ptotal=0; 16 | int atotal=0; 17 | int i=0; 18 | 19 | for(i=0;i=75) { 39 | System.out.println(0); 40 | }else { 41 | while(percent<75) { 42 | if(count>0) { 43 | percent=((ptotal+1)/total)*100; 44 | count--; 45 | out++; 46 | } 47 | } 48 | System.out.println(out); 49 | } 50 | 51 | --t; 52 | } 53 | 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /codechef/src/codechef/modulo.java: -------------------------------------------------------------------------------- 1 | package codechef; 2 | 3 | import java.util.Scanner; 4 | 5 | public class modulo { 6 | public static void main(String[] args) { 7 | Scanner k = new Scanner(System.in); 8 | int n=k.nextInt(); 9 | int m=k.nextInt(); 10 | System.out.println("%"+n%m); 11 | System.out.println("/"+n/m); 12 | 13 | 14 | }} 15 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/ComplexNumbers.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | 3 | public class ComplexNumbers { 4 | private int real ; 5 | private int imaginary; 6 | public ComplexNumbers(int real ,int imaginary){ 7 | this.real=real; 8 | this.imaginary=imaginary; 9 | } 10 | 11 | public int getImaginary(){ 12 | return imaginary; 13 | 14 | } 15 | public int getReal(){ 16 | return real; 17 | } 18 | public int setReal(int real){ 19 | return this.real=real; 20 | } 21 | public int setImaginary(int imaginary){ 22 | return this.imaginary=imaginary; 23 | } 24 | public void print(){ 25 | System.out.println(real+" + "+'i'+imaginary); 26 | } 27 | public void plus(ComplexNumbers c2){ 28 | 29 | } 30 | 31 | public void multiply(ComplexNumbers c2){ 32 | 33 | } 34 | public ComplexNumbers conjugate(){ 35 | return null; 36 | 37 | } 38 | public static ComplexNumbers add(ComplexNumbers c1 ,ComplexNumbers c2 ) 39 | { 40 | return c2; 41 | 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/DynamicArray.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | public class DynamicArray { 3 | private int data[]; 4 | private int nextIndex; 5 | 6 | public DynamicArray() { 7 | data = new int[5]; 8 | nextIndex = 0; 9 | } 10 | 11 | public int size() { 12 | return nextIndex; 13 | } 14 | 15 | public void add(int element) { 16 | if (nextIndex == data.length) { 17 | restructure(); 18 | } 19 | data[nextIndex] = element; 20 | nextIndex++; 21 | } 22 | 23 | public void set(int index, int element) { 24 | if (index > nextIndex) { 25 | return; 26 | } 27 | if (index < nextIndex) { 28 | data[index] = element; 29 | } else { 30 | add(element); 31 | } 32 | 33 | } 34 | 35 | public int get(int index) { 36 | if (index >= nextIndex) { 37 | // error out 38 | return -1; 39 | } 40 | return data[index]; 41 | } 42 | 43 | public boolean isEmpty() { 44 | if (size() == 0) { 45 | return true; 46 | } else { 47 | return false; 48 | } 49 | } 50 | 51 | public int removeLast() { 52 | if (size() == 0) { 53 | // error out 54 | return -1; 55 | } 56 | int value = data[nextIndex - 1]; 57 | data[nextIndex - 1] = 0; 58 | nextIndex--; 59 | return value; 60 | } 61 | 62 | private void restructure() { 63 | int temp[] = data; 64 | data = new int[data.length * 2]; 65 | for (int i = 0; i < temp.length; i++) { 66 | data[i] = temp[i]; 67 | } 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/DynamicArrayUse.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | public class DynamicArrayUse { 3 | 4 | public static void main(String[] args) { 5 | DynamicArray d = new DynamicArray(); 6 | 7 | for (int i = 0; i < 10; i++) { 8 | d.add(i); 9 | } 10 | 11 | System.out.println(d.size()); 12 | 13 | d.set(4, 10); 14 | System.out.println(d.get(3)); 15 | System.out.println(d.get(4)); 16 | 17 | while (!d.isEmpty()) { 18 | System.out.println(d.removeLast()); 19 | System.out.println("size = " + d.size()); 20 | } 21 | } 22 | 23 | } 24 | 25 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/Fraction.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | public class Fraction { 3 | //instanse variabe numerator 4 | private int numerator; 5 | private int denominator; 6 | 7 | public Fraction(int numerator, int denominator) { 8 | this.numerator = numerator; 9 | if (denominator == 0) { 10 | // TODO error out 11 | } 12 | this.denominator = denominator; 13 | simplify(); 14 | } 15 | 16 | public int getDenominator() { 17 | return denominator; 18 | } 19 | 20 | public int getNumerator() { 21 | return numerator; 22 | } 23 | 24 | public void setNumerator(int n) { 25 | numerator = n; 26 | simplify(); 27 | } 28 | 29 | public void setDenominator(int d) { 30 | if (d == 0){ 31 | // TODO error out 32 | return; 33 | } 34 | this.denominator = d; 35 | this.simplify(); 36 | } 37 | 38 | public static Fraction add(Fraction f1, Fraction f2) { 39 | int newNum = f1.numerator * f2.denominator + f2.numerator * f1.denominator; 40 | int newDen = f1.denominator * f2.denominator; 41 | Fraction f = new Fraction(newNum, newDen); 42 | return f; 43 | } 44 | 45 | public void add(Fraction f2) { 46 | this.numerator = this.numerator * f2.denominator + this.denominator*f2.numerator; 47 | this.denominator = this.denominator * f2.denominator; 48 | simplify(); 49 | } 50 | 51 | public void multiply(Fraction f2) { 52 | this.numerator = this.numerator * f2.numerator; 53 | this.denominator = this.denominator * f2.denominator; 54 | simplify(); 55 | } 56 | 57 | public void print() { 58 | if (denominator == 1) { 59 | System.out.println(numerator); 60 | } else { 61 | System.out.println(numerator + "/" + denominator); 62 | } 63 | } 64 | 65 | private void simplify() { 66 | int gcd = 1; 67 | int smaller = Math.min(numerator, denominator); 68 | for (int i = 2; i <= smaller; i++) { 69 | if (numerator % i == 0 && denominator % i == 0) { 70 | gcd = i; 71 | } 72 | } 73 | numerator = numerator/gcd; 74 | denominator=denominator/gcd; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/FractionUse.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | 3 | 4 | public class FractionUse { 5 | //main method in java 6 | public static void main(String[] args) { 7 | Fraction f1 = new Fraction(20,30); 8 | f1.print(); 9 | // 2/3 10 | 11 | f1.setNumerator(12); 12 | // 4/1 13 | int d = f1.getDenominator(); 14 | System.out.println(d); 15 | //accessing member through reference variable 16 | f1.print(); 17 | 18 | f1.setNumerator(10); 19 | f1.setDenominator(30); 20 | // 1/3 21 | f1.print(); 22 | 23 | Fraction f2 = new Fraction(3,4); 24 | f1.add(f2); 25 | f1.print(); 26 | // f1 => 13/12 27 | f2.print(); 28 | // f2 => 3/4 29 | 30 | Fraction f3 = new Fraction(4,5); 31 | f3.multiply(f2); 32 | f3.print(); 33 | // f3 => 3/5 34 | f2.print(); 35 | //f2 => 3/4 36 | 37 | Fraction f4 = Fraction.add(f1, f3); 38 | f1.print(); 39 | f3.print(); 40 | f4.print(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/Polynomial.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | 3 | public class Polynomial { 4 | int degCoeff[]; 5 | /* This function sets coefficient for a particular degree value, if degree is not there in the polynomial 6 | * then corresponding term(with specified degree and value is added in the polynomial. If the degree * 7 | is already present in the polynomial then previous coefficient is replaced by * 8 | new coefficient value passed as function argument */ 9 | Polynomial() 10 | { 11 | degCoeff = new int[10]; } 12 | public void setCoefficient(int degree, int coeff) { 13 | if(degree > degCoeff.length-1) { 14 | //create a new array with size= degree+1 15 | int temp[] = degCoeff; 16 | degCoeff = new int[degree+1]; 17 | //copy values from temp to degCoeff 18 | for(int i = 0; i < temp.length; i++) { 19 | degCoeff[i] = temp[i]; } } 20 | degCoeff[degree] = coeff; } 21 | // Prints all the terms(only terms with non zero coefficients are to be printed) in increasing order of degree. 22 | public void print(){ 23 | for(int i = 0;i < degCoeff.length; i++) 24 | { if(degCoeff[i] != 0) { System.out.print(degCoeff[i] + "x" + i + " "); 25 | } 26 | } 27 | } 28 | // Adds two polynomials and returns a new polynomial which has result 29 | public Polynomial add(Polynomial p){ 30 | Polynomial ans = new Polynomial(); 31 | int plen1 = this.degCoeff.length; 32 | int plen2 = p.degCoeff.length; 33 | int len = Math.min(plen1, plen2); 34 | int i; 35 | for(i = 0; i < len; i++) { 36 | ans.setCoefficient(i, this.degCoeff[i] + p.degCoeff[i]); } 37 | while(i < plen1){ 38 | ans.setCoefficient(i, this.degCoeff[i]); i++; } 39 | while(i < plen2){ 40 | ans.setCoefficient(i, p.degCoeff[i]); i++; } 41 | return ans; } 42 | // Subtracts two polynomials and returns a new polynomial which has result 43 | public Polynomial subtract(Polynomial p){ 44 | int plen1 = this.degCoeff.length; 45 | int plen2 = p.degCoeff.length; 46 | int len = Math.min(plen1, plen2); 47 | Polynomial ans = new Polynomial(); 48 | int i; for(i = 0; i < len; i++) { 49 | ans.setCoefficient(i, this.degCoeff[i] - p.degCoeff[i]); } 50 | while(i < plen1){ 51 | ans.setCoefficient(i, this.degCoeff[i]); i++; } 52 | while(i < plen2){ 53 | ans.setCoefficient(i, -p.degCoeff[i]); i++; } 54 | return ans; } 55 | public int getCoeff(int degree) { 56 | if(degree < this.degCoeff.length) { 57 | return degCoeff[degree]; } 58 | else { 59 | return 0; } 60 | } 61 | // Multiply two polynomials and returns a new polynomial which has result 62 | public Polynomial multiply(Polynomial p){ 63 | Polynomial ans = new Polynomial(); 64 | for(int i = 0; i < this.degCoeff.length; i++){ 65 | for(int j = 0; j < p.degCoeff.length; j+=1){ 66 | int termdeg = i + j; 67 | int termCoeff = this.degCoeff[i] * p.degCoeff[j]; 68 | int oldCoeff = ans.getCoeff(termdeg); 69 | ans.setCoefficient(termdeg, termCoeff + oldCoeff); } 70 | } 71 | return ans; 72 | } 73 | } -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/PolynomialUse.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PolynomialUse { 6 | 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | @SuppressWarnings("resource") 11 | Scanner s = new Scanner(System.in); 12 | int n = s.nextInt(); 13 | int degree1[] = new int[n]; 14 | for(int i = 0; i < n; i++){ 15 | degree1[i] = s.nextInt(); 16 | } 17 | int coeff1[] = new int[n]; 18 | for(int i = 0; i < n; i++){ 19 | coeff1[i] = s.nextInt(); 20 | } 21 | Polynomial first = new Polynomial(); 22 | for(int i = 0; i < n; i++){ 23 | first.setCoefficient(degree1[i],coeff1[i]); 24 | } 25 | n = s.nextInt(); 26 | int degree2[] = new int[n]; 27 | for(int i = 0; i < n; i++){ 28 | degree2[i] = s.nextInt(); 29 | } 30 | int coeff2[] = new int[n]; 31 | for(int i = 0; i < n; i++){ 32 | coeff2[i] = s.nextInt(); 33 | } 34 | Polynomial second = new Polynomial(); 35 | for(int i = 0; i < n; i++){ 36 | second.setCoefficient(degree2[i],coeff2[i]); 37 | } 38 | int choice = s.nextInt(); 39 | Polynomial result; 40 | switch(choice){ 41 | // Add 42 | case 1: 43 | result = first.add(second); 44 | result.print(); 45 | break; 46 | // Subtract 47 | case 2 : 48 | result = first.subtract(second); 49 | result.print(); 50 | break; 51 | // Multiply 52 | case 3 : 53 | result = first.multiply(second); 54 | result.print(); 55 | break; 56 | } 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/Runner.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Runner { 6 | 7 | public static void main(String[] args) { 8 | @SuppressWarnings("resource") 9 | Scanner s = new Scanner(System.in); 10 | 11 | int real1 = s.nextInt(); 12 | int imaginary1 = s.nextInt(); 13 | 14 | int real2 = s.nextInt(); 15 | int imaginary2 = s.nextInt(); 16 | 17 | ComplexNumbers c1 = new ComplexNumbers(real1, imaginary1); 18 | ComplexNumbers c2 = new ComplexNumbers(real2, imaginary2); 19 | 20 | int choice = s.nextInt(); 21 | if(choice == 1) { 22 | // Add 23 | c1.plus(c2); 24 | c1.print(); 25 | } 26 | else if(choice == 2) { 27 | // Multiply 28 | c1.multiply(c2); 29 | c1.print(); 30 | } 31 | else { 32 | return; 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/Student.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | 3 | // public class Student { 4 | // String name; 5 | // int rollNumber; 6 | //} 7 | // 8 | // 9 | 10 | //////////////////////////////////////////////// 11 | // public class Student { 12 | // public String name; 13 | // private int rollNumber; 14 | // 15 | // public void setRollnumber(int rn) { 16 | // if (rn <= 0) { 17 | // System.out.println('n'); 18 | // return; 19 | // } 20 | // rollNumber = rn; 21 | // } 22 | // 23 | // public int getRollNumber() { 24 | // return rollNumber; 25 | // } 26 | //} 27 | ////////////////////////////////////////// 28 | 29 | //public class Student { 30 | // public String name; 31 | // private int rollNumber; 32 | // 33 | // public Student() { 34 | // 35 | // } 36 | // 37 | // public Student(String n) { 38 | // name = n; 39 | // rollNumber = 100; 40 | // } 41 | // 42 | // public Student(String n, int rn) { 43 | // name = n; 44 | // if (rn <= 0) { 45 | // return; 46 | // } 47 | // rollNumber = rn;} 48 | // 49 | // public void setRollnumber(int rn) { 50 | // if (rn <= 0) { 51 | // return; 52 | // } 53 | // rollNumber = rn; 54 | // } 55 | // 56 | // public int getRollNumber() { 57 | // return rollNumber; 58 | // } 59 | // 60 | // public void print() { 61 | // System.out.println(name + " : " + rollNumber); 62 | // } 63 | // 64 | //} 65 | ////////////////////////////////////// 66 | ///imported keywords 67 | 68 | //public class Student { 69 | // public String name; 70 | // // final data members can be initialized as soon as they are declared 71 | // private final int rollNumber; 72 | // private static int numStudents; 73 | // 74 | // 75 | //// public Student(String n) { 76 | //// name = n; 77 | //// rollNumber = 100; 78 | //// } 79 | // 80 | // public static int getNumStudents() { 81 | // return numStudents; 82 | // } 83 | // 84 | //public Student(String name, int rollNumber) { 85 | // this.name = name; 86 | // this.rollNumber = rollNumber; 87 | // numStudents++; 88 | // } 89 | // 90 | //// public void setRollnumber(int rn) { 91 | //// if (rn <= 0) { 92 | //// return; 93 | //// } 94 | //// rollNumber = rn; 95 | //// } 96 | // 97 | // public int getRollNumber() { 98 | // return rollNumber; 99 | // } 100 | // 101 | // public void print() { 102 | // System.out.println(name + " : " + rollNumber); 103 | // } 104 | // 105 | //} 106 | ////////////////friction classes -------------------------------------------------------------------------------- /objectoriented/src/objectoriented/StudentUse.java: -------------------------------------------------------------------------------- 1 | package objectoriented; 2 | ////import java.util.*; 3 | ////public class StudentUse { 4 | //// 5 | //// public static void main(String[] args) { 6 | //// Scanner s = new Scanner(System.in); 7 | //// creating an object student 8 | ////Student s1 = new Student(); 9 | //// s1.name = "Ankush"; 10 | //// s1.rollNumber=123; 11 | //// 12 | //// Student s2 = new Student(); 13 | //// s2.name = "Manisha"; 14 | //// s2.rollNumber = 121; 15 | //// 16 | //// System.out.println(s1.name); 17 | //// System.out.println(s2.name); 18 | //// //System.out.println(s1); 19 | //// } 20 | //// 21 | //// } 22 | ////////////////////////////////// 23 | ////public class StudentUse { 24 | //// 25 | //// public static void main(String[] args) { 26 | //// Student s1 = new Student(); 27 | //// s1.name = "ketan"; 28 | //// s1.setRollnumber(-123); 29 | //// 30 | //// Student s2 = new Student(); 31 | //// s2.name = "Manjeet"; 32 | //// s2.setRollnumber(121); 33 | //// 34 | //// System.out.println(s1.name); 35 | //// System.out.println(s2.name); 36 | //// System.out.println(s1.getRollNumber()); 37 | //// System.out.println(s2.getRollNumber()); 38 | //// } 39 | //// 40 | ////} 41 | ///////////////////////////////////////// 42 | //import java.util.Scanner; 43 | //public class StudentUse { 44 | // 45 | // @SuppressWarnings("unused") 46 | // public static void main(String[] args) { 47 | // @SuppressWarnings("resource") 48 | // Scanner s = new Scanner(System.in); 49 | // 50 | // Student s1 = new Student(); 51 | // s1.name="ketan mehta"; 52 | // s1.setRollnumber(420); 53 | // System.out.println(s1); 54 | // System.out.println(s1.name); 55 | // System.out.println(s1.getRollNumber()); 56 | // s1.print(); 57 | // 58 | // Student s2 = new Student("Manisha",-121); 59 | // //System.out.println(s2); 60 | // s2.print(); 61 | //// System.out.println(s1.name); 62 | //// System.out.println(s2.name); 63 | //// System.out.println(s1.getRollNumber()); 64 | //// //System.out.println(s1); 65 | // } 66 | // 67 | //} 68 | ////////////////////////////////////////////////// 69 | //imported keywords 70 | 71 | //public class StudentUse { 72 | // 73 | // public static void main(String[] args) { 74 | // 75 | // Student s1 = new Student("Ankush", -123); 76 | // //System.out.println(s1); 77 | //// System.out.println(s1.name); 78 | //// System.out.println(s1.getRollNumber()); 79 | // s1.print(); 80 | // 81 | // Student s2 = new Student("Manisha", 121); 82 | // //System.out.println(s2); 83 | // s2.print(); 84 | // 85 | //// System.out.println(s1.numStudents); 86 | //// System.out.println(s2.numStudents); 87 | // System.out.println(Student.getNumStudents()); 88 | // //System.out.println(s1.getNumStudents()); 89 | // 90 | // System.out.println(s1.name); 91 | // 92 | //// System.out.println(s1.name); 93 | //// System.out.println(s2.name); 94 | //// System.out.println(s1.getRollNumber()); 95 | //// //System.out.println(s1); 96 | // } 97 | // 98 | //} 99 | /////////////////////////////friction classes 100 | 101 | 102 | 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /objectoriented/src/readme.java/access Modifiers: -------------------------------------------------------------------------------- 1 | https://www.javatpoint.com/object-and-class-in-java 2 | https://www.geeksforgeeks.org/access-modifiers-java/ 3 | https://www.javatpoint.com/access-modifiers 4 | https://www.javatpoint.com/inheritance-in-java 5 | -------------------------------------------------------------------------------- /objectoriented/src/vehicle/Car.java: -------------------------------------------------------------------------------- 1 | package vehicle; 2 | 3 | public class Car extends Vehicle { 4 | int numGears; 5 | private boolean isConvertible; 6 | 7 | public void print() { 8 | System.out.println("Car color : " + color); 9 | System.out.println("Car Speed : " + maxSpeed); 10 | System.out.println("Car numGears : " + numGears); 11 | System.out.println("Car isConvertible : " + isConvertible); 12 | super.print(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /objectoriented/src/vehicle/Vehicle.java: -------------------------------------------------------------------------------- 1 | package vehicle; 2 | 3 | public class Vehicle { 4 | String color; 5 | int maxSpeed; 6 | 7 | 8 | public void setMaxSpeed(int maxSpeed) { 9 | this.maxSpeed = maxSpeed; 10 | } 11 | 12 | public void print() { 13 | System.out.println("Vehicle color : " + color); 14 | System.out.println("Vehicle Speed : " + maxSpeed); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /objectoriented/src/vehicle/VehicleUse.java: -------------------------------------------------------------------------------- 1 | package vehicle; 2 | public class VehicleUse { 3 | 4 | public static void main(String[] args) { 5 | Vehicle v = new Vehicle(); 6 | v.color = "Black"; 7 | v.setMaxSpeed(10); 8 | v.print(); 9 | ///// 10 | 11 | Vehicle k = new Car(); 12 | k.color="green"; 13 | k.print(); 14 | // k.isConvertible=false; 15 | //in above line you only assecc common members of both the classes 16 | // you can not specify the unique properties of the car in the above line 17 | 18 | 19 | Car c = new Car(); 20 | c.numGears = 10; 21 | c.color = "Blackeeee"; 22 | c.setMaxSpeed(11100); 23 | c.print(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /read/Break.java: -------------------------------------------------------------------------------- 1 | Java Break Statement with Labeled For Loop 2 | We can use break statement with a label. This feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer loop or inner. 3 | 4 | Example: 5 | 6 | //Java Program to illustrate the use of continue statement 7 | //with label inside an inner loop to break outer loop 8 | public class BreakExample3 { 9 | public static void main(String[] args) { 10 | aa: 11 | for(int i=1;i<=3;i++){ 12 | bb: 13 | for(int j=1;j<=3;j++){ 14 | if(i==2&&j==2){ 15 | //using break statement with label 16 | break aa; 17 | } 18 | System.out.println(i+" "+j); 19 | } 20 | } 21 | } 22 | } 23 | Output: 24 | 25 | 1 1 26 | 1 2 27 | 1 3 28 | 2 1 29 | -------------------------------------------------------------------------------- /read/long.java: -------------------------------------------------------------------------------- 1 | https://www.geeksforgeeks.org/java-lang-long-class-in-java/ 2 | // Java program to illustrate 3 | // various Long class methods 4 | public class Long_test 5 | { 6 | public static void main(String args[]) 7 | { 8 | long b = 55; 9 | String bb = "45"; 10 | 11 | // Construct two Long objects 12 | Long x = new Long(b); 13 | Long y = new Long(bb); 14 | 15 | // toString() 16 | System.out.println("toString(b) = " + Long.toString(b)); 17 | //toString(b) = 55 18 | // toHexString(),toOctalString(),toBinaryString() 19 | // converts into hexadecimal, octal and binary forms. 20 | System.out.println("toHexString(b) =" + Long.toHexString(b)); 21 | System.out.println("toOctalString(b) =" + Long.toOctalString(b)); 22 | System.out.println("toBinaryString(b) =" + Long.toBinaryString(b)); 23 | 24 | // valueOf(): return Long object 25 | // an overloaded method takes radix as well. 26 | Long z = Long.valueOf(b); 27 | System.out.println("valueOf(b) = " + z); 28 | z = Long.valueOf(bb); 29 | System.out.println("ValueOf(bb) = " + z); 30 | z = Long.valueOf(bb, 6); 31 | System.out.println("ValueOf(bb,6) = " + z); 32 | 33 | // parseLong(): return primitive long value 34 | // an overloaded method takes radix as well 35 | long zz = Long.parseLong(bb); 36 | System.out.println("parseLong(bb) = " + zz); 37 | zz = Long.parseLong(bb, 6); 38 | System.out.println("parseLong(bb,6) = " + zz); 39 | 40 | // getLong(): can be used to retrieve 41 | // long value of system property 42 | long prop = Long.getLong("sun.arch.data.model"); 43 | System.out.println("getLong(sun.arch.data.model) = " + prop); 44 | System.out.println("getLong(abcd) =" + Long.getLong("abcd")); 45 | 46 | // an overloaded getLong() method 47 | // which return default value if property not found. 48 | System.out.println("getLong(abcd,10) =" + Long.getLong("abcd", 10)); 49 | 50 | // decode() : decodes the hex,octal and decimal 51 | // string to corresponding long values. 52 | String decimal = "45"; 53 | String octal = "005"; 54 | String hex = "0x0f"; 55 | 56 | Long dec = Long.decode(decimal); 57 | System.out.println("decode(45) = " + dec); 58 | dec = Long.decode(octal); 59 | System.out.println("decode(005) = " + dec); 60 | dec = Long.decode(hex); 61 | System.out.println("decode(0x0f) = " + dec); 62 | 63 | // rotateLeft and rotateRight can be used 64 | // to rotate bits by specified distance 65 | long valrot = 2; 66 | System.out.println("rotateLeft(0000 0000 0000 0010 , 2) =" + 67 | Long.rotateLeft(valrot, 2)); 68 | System.out.println("rotateRight(0000 0000 0000 0010,3) =" + 69 | Long.rotateRight(valrot, 3)); 70 | } 71 | } 72 | Output : 73 | 74 | 75 | toHexString(b) =37 76 | toOctalString(b) =67 77 | toBinaryString(b) =110111 78 | valueOf(b) = 55 79 | ValueOf(bb) = 45 80 | ValueOf(bb,6) = 29 81 | parseInt(bb) = 45 82 | parseInt(bb,6) = 29 83 | getLong(sun.arch.data.model) = 64 84 | getLong(abcd) =null 85 | getLong(abcd,10) =10 86 | decode(45) = 45 87 | decode(005) = 5 88 | decode(0x0f) = 15 89 | rotateLeft(0000 0000 0000 0010 , 2) =8 90 | rotateRight(0000 0000 0000 0010,3) =1073741824 91 | -------------------------------------------------------------------------------- /read/queue important.java: -------------------------------------------------------------------------------- 1 | Queue Interface In Java 2 | The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle. Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java.It is to be noted that both the implementations are not thread safe. PriorityBlockingQueue is one alternative implementation if thread safe implementation is needed. Few important characteristics of Queue are: 3 | 4 | The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept. 5 | The Java Queue supports all methods of Collection interface including insertion, deletion etc. 6 | LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations. 7 | If any null operation is performed on BlockingQueues, NullPointerException is thrown. 8 | 9 | 10 | BlockingQueues have thread-safe implementations. 11 | The Queues which are available in java.util package are Unbounded Queues 12 | The Queues which are available in java.util.concurrent package are the Bounded Queues. 13 | All Queues except the Deques supports insertion and removal at the tail and head of the queue respectively. The Deques support element insertion and removal at both ends. 14 | Methods in Queue: 15 | 16 | add()- This method is used to add elements at the tail of queue. More specifically, at the last of linked-list if it is used, or according to the priority in case of priority queue implementation. 17 | peek()- This method is used to view the head of queue without removing it. It returns Null if the queue is empty. 18 | element()- This method is similar to peek(). It throws NoSuchElementException when the queue is empty. 19 | remove()- This method removes and returns the head of the queue. It throws NoSuchElementException when the queue is empty. 20 | poll()- This method removes and returns the head of the queue. It returns null if the queue is empty. 21 | size()- This method return the no. of elements in the queue. 22 | 23 | 24 | Since it is a subtype of Collections class, it inherits all the methods of it namely size(), isEmpty(), contains() etc. 25 | Below is a simple Java program to demonstrate these methods: 26 | 27 | filter_none 28 | edit 29 | play_arrow 30 | 31 | brightness_4 32 | // Java orogram to demonstrate working of Queue 33 | // interface in Java 34 | import java.util.LinkedList; 35 | import java.util.Queue; 36 | 37 | public class QueueExample 38 | { 39 | public static void main(String[] args) 40 | { 41 | Queue q = new LinkedList<>(); 42 | 43 | // Adds elements {0, 1, 2, 3, 4} to queue 44 | for (int i=0; i<5; i++) 45 | q.add(i); 46 | 47 | // Display contents of the queue. 48 | System.out.println("Elements of queue-"+q); 49 | 50 | // To remove the head of queue. 51 | int removedele = q.remove(); 52 | System.out.println("removed element-" + removedele); 53 | 54 | System.out.println(q); 55 | 56 | // To view the head of queue 57 | int head = q.peek(); 58 | System.out.println("head of queue-" + head); 59 | 60 | // Rest all methods of collection interface, 61 | // Like size and contains can be used with this 62 | // implementation. 63 | int size = q.size(); 64 | System.out.println("Size of queue-" + size); 65 | } 66 | } 67 | Output: 68 | Elements of queue-[0, 1, 2, 3, 4] 69 | removed element-0 70 | [1, 2, 3, 4] 71 | head of queue-1 72 | Size of queue-4 73 | -------------------------------------------------------------------------------- /recursion/Binarysearch.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | import java.util.Scanner; 3 | public class Binarysearch { 4 | 5 | public static int binarySearch(int input[], int start,int end,int x) { 6 | if(end>=start) { 7 | int mid = start+(end-start)/2; 8 | if(input[mid]==x){ 9 | return mid; 10 | } 11 | if(input[mid]>x) 12 | return binarySearch(input,start,mid-1,x); 13 | return binarySearch(input,mid+1,end,x); 14 | 15 | } 16 | return -1; 17 | 18 | } 19 | public static int binarySearch(int input[], int element) { 20 | int k= binarySearch(input,0,input.length,element); 21 | return k; 22 | } 23 | 24 | static Scanner s = new Scanner(System.in); 25 | public static int[] takeInput() { 26 | int size = s.nextInt(); 27 | int arr[] = new int[size]; 28 | for (int i = 0; i < size; i++) { 29 | arr[i] = s.nextInt(); 30 | } 31 | return arr; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] input = takeInput(); 36 | int element = s.nextInt(); 37 | System.out.println(binarySearch(input, element)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /recursion/CheckSorted.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | public class CheckSorted { 3 | 4 | 5 | public static boolean checkSorted(int input[]){ 6 | 7 | if(input.length <= 1){ 8 | return true; 9 | } 10 | 11 | int smallInput[] = new int[input.length - 1]; 12 | for(int i = 1; i < input.length; i++){ 13 | smallInput[i - 1] = input[i]; 14 | } 15 | 16 | boolean smallAns = checkSorted(smallInput); 17 | if(!smallAns){ 18 | return false; 19 | } 20 | if(input[0] <= input[1]){ 21 | return true; 22 | }else{ 23 | return false; 24 | } 25 | 26 | } 27 | public static boolean checkSorted_2(int input[]){ 28 | 29 | if(input.length <= 1){ 30 | return true; 31 | } 32 | if(input[0] > input[1]){ 33 | return false; 34 | } 35 | 36 | int smallInput[] = new int[input.length - 1]; 37 | for(int i = 1; i < input.length; i++){ 38 | smallInput[i - 1] = input[i]; 39 | } 40 | boolean smallAns = checkSorted_2(smallInput); 41 | return smallAns; 42 | // if(smallAns){ 43 | // return true; 44 | // }else{ 45 | // return false; 46 | // } 47 | 48 | } 49 | 50 | // This function checks if the array is sorted from startIndex to end 51 | public static boolean checkSortedBetter(int input[],int startIndex){ 52 | 53 | if(startIndex >= input.length - 1){ 54 | return true; 55 | } 56 | if(input[startIndex] > input[startIndex + 1]){ 57 | return false; 58 | } 59 | boolean smallAns = checkSortedBetter(input, startIndex + 1); 60 | return smallAns; 61 | 62 | } 63 | public static boolean checkSortedBetter(int input[]){ 64 | return checkSortedBetter(input,0) ; 65 | } 66 | 67 | public static void main(String[] args) { 68 | int input[] = {1,2,3}; 69 | System.out.println(checkSortedBetter(input)); 70 | 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /recursion/PrintSubsequences.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | public class PrintSubsequences { 4 | 5 | 6 | public static void printSubsequences(String input, String outputSoFar){ 7 | if(input.length() == 0){ 8 | System.out.println(outputSoFar); 9 | return; 10 | } 11 | // we choose not to include the first character 12 | printSubsequences(input.substring(1), outputSoFar); 13 | // we choose to include the first character 14 | printSubsequences(input.substring(1), outputSoFar + input.charAt(0)); 15 | 16 | } 17 | 18 | public static void printSubsequences(String input){ 19 | 20 | printSubsequences(input, ""); 21 | } 22 | 23 | public static void main(String[] args) { 24 | printSubsequences("xy"); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /recursion/Printkeypadcode.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | import java.util.Scanner; 3 | 4 | public class Printkeypadcode { 5 | public static String [] help(int num){ 6 | if(num<=1||num>=10){ 7 | System.exit(0); 8 | } 9 | if(num==2){ 10 | String[] ans = {"a","b","c"}; 11 | return ans; 12 | }else if(num==3){ 13 | String[] ans = {"d","e","f"}; 14 | return ans; 15 | }else if(num==4){ 16 | String[] ans = {"g","h","i"}; 17 | return ans; 18 | }else if(num==5){ 19 | String[] ans = {"j","k","l"}; 20 | return ans; 21 | }else if(num==6){ 22 | String[] ans = {"m","n","o"}; 23 | return ans; 24 | }else if(num==7){ 25 | String[] ans = {"p","q","r","s"}; 26 | return ans; 27 | }else if(num==8){ 28 | String[] ans = {"t","u","v"}; 29 | return ans; 30 | }else { 31 | String[] ans = {"w","x","y","z"}; 32 | return ans; 33 | } 34 | } 35 | 36 | public static void keypad(int n, String[] outputSoFar){ 37 | if(n==0){ 38 | for(int i = 0; i < outputSoFar.length; i++) { 39 | System.out.println(outputSoFar[i]); 40 | } 41 | return; 42 | } 43 | 44 | int k=n%10; 45 | String[] help=help(k); 46 | String ans[] = new String[help.length*outputSoFar.length]; 47 | int i,j; 48 | int p=0; 49 | 50 | for(j=0;j=10){ 7 | System.exit(0); 8 | } 9 | if(num==2){ 10 | String[] ans = {"a","b","c"}; 11 | return ans; 12 | }else if(num==3){ 13 | String[] ans = {"d","e","f"}; 14 | return ans; 15 | }else if(num==4){ 16 | String[] ans = {"g","h","i"}; 17 | return ans; 18 | }else if(num==5){ 19 | String[] ans = {"j","k","l"}; 20 | return ans; 21 | }else if(num==6){ 22 | String[] ans = {"m","n","o"}; 23 | return ans; 24 | }else if(num==7){ 25 | String[] ans = {"p","q","r","s"}; 26 | return ans; 27 | }else if(num==8){ 28 | String[] ans = {"t","u","v"}; 29 | return ans; 30 | }else { 31 | String[] ans = {"w","x","y","z"}; 32 | return ans; 33 | } 34 | } 35 | 36 | 37 | public static String[] keypad(int n){ 38 | if(n==0){ 39 | String ans[] = {""}; 40 | return ans; 41 | } 42 | int k=n%10; 43 | String smallAns[] = keypad(n/10); 44 | String[] help=help(k); 45 | String ans[] = new String[help.length*smallAns.length]; 46 | int i,j; 47 | int p=0; 48 | 49 | for(j=0;j= input.length) 11 | { 12 | int ans[][] = new int[1][0]; 13 | return ans; 14 | } 15 | int i,j,k,p; 16 | int arr[]=new int[input.length-1]; 17 | for(i=0;iarr[j+1]) { 20 | k=arr[j+1]; 21 | arr[j+1]=arr[j]; 22 | arr[j]=k; 23 | } 24 | } 25 | } 26 | for(i=1;i0;j--) { 20 | if(arr[min]>arr[j]) { 21 | min=j; 22 | }} 23 | 24 | 25 | 26 | } 27 | 28 | 29 | 30 | 31 | 32 | 33 | for(i=0;ipivot); 36 | if(i=e){ 73 | return ; 74 | } 75 | int m=(s+e)/2; 76 | sort(input,s,m); 77 | sort(input,m+1,e); 78 | merge(input,s,m,e); 79 | } 80 | 81 | 82 | public static void mergeSort(int[] input){ 83 | sort(input , 0 ,input.length-1); 84 | } 85 | } 86 | 87 | -------------------------------------------------------------------------------- /strings/src/strings/reverseeach.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.Scanner; 4 | 5 | public class reverseeach { 6 | 7 | public void main(String[] args) { 8 | @SuppressWarnings("resource") 9 | Scanner s = new Scanner(System.in); 10 | String input = s.nextLine(); 11 | System.out.println(reverseEachWord(input)); 12 | } 13 | 14 | public static String reverseEachWord(String input) { 15 | String a=""; 16 | int i =0; 17 | int start=0; 18 | int end=0; 19 | int j=0; 20 | for(i=0;i input() { 11 | int data = s.nextInt(); 12 | 13 | LinkedListNode head = null; 14 | LinkedListNode tail = null; 15 | while (data!=-1) { 16 | LinkedListNode newNode = new LinkedListNode(data); 17 | if (head == null) { 18 | head = newNode; 19 | tail = newNode; 20 | } else { 21 | tail.next = newNode; 22 | tail = newNode; 23 | } 24 | data = s.nextInt(); 25 | } 26 | return head; 27 | } 28 | } 29 | 30 | class LinkedListNode { 31 | public T data; 32 | public LinkedListNode next; 33 | 34 | public LinkedListNode(T data) { 35 | this.setData(data); 36 | this.next = null; 37 | } 38 | 39 | public T getData() { 40 | return data; 41 | } 42 | 43 | public void setData(T data) { 44 | this.data = data; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /testing/src/Solution.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | class LinkedListNode { 4 | public T data; 5 | public LinkedListNode next; 6 | 7 | public LinkedListNode(T data) { 8 | this.setData(data); 9 | this.next = null; 10 | } 11 | 12 | public T getData() { 13 | return data; 14 | } 15 | 16 | public void setData(T data) { 17 | this.data = data; 18 | } 19 | 20 | } 21 | * */ 22 | public class Solution { 23 | public static int printMiddel(LinkedListNode head) { 24 | if(head==null||head.next==null){ 25 | return head.data; 26 | } 27 | LinkedListNode< 28 | Integer> slow=head; 29 | head=head.next; 30 | LinkedListNode fast=head.next; 31 | 32 | while(fast.data!=null){ 33 | slow=slow.next; 34 | fast=fast.next; 35 | fast=fast.next; 36 | } 37 | return slow.data; 38 | } 39 | } -------------------------------------------------------------------------------- /testing/src/a.java: -------------------------------------------------------------------------------- 1 | import binarysearchtree.BinaryTreeNode; 2 | 3 | public class a { 4 | 5 | private BinaryTreeNode root; 6 | 7 | private BinaryTreeNode insertData(int data, BinaryTreeNode root) { 8 | if (root == null) { 9 | BinaryTreeNode newNode = new BinaryTreeNode(data); 10 | return newNode; 11 | } 12 | if (root.data > data) { 13 | root.left = insertData(data, root.left); 14 | } else { 15 | root.right = insertData(data, root.right); 16 | } 17 | return root; 18 | } 19 | 20 | public void insertData(int data) { 21 | root = insertData(data, root); 22 | } 23 | 24 | public void deleteData(int data) { 25 | root = deleteData(data, root); 26 | } 27 | 28 | private BinaryTreeNode deleteData(int data, BinaryTreeNode root) { 29 | if (root == null) { 30 | return null; 31 | } 32 | if (data < root.data) { 33 | root.left = deleteData(data, root.left); 34 | return root; 35 | } else if (data > root.data) { 36 | root.right = deleteData(data, root.right); 37 | return root; 38 | } else { 39 | if (root.left == null && root.right == null) { 40 | return null; 41 | } else if (root.left == null) { 42 | return root.right; 43 | } else if (root.right == null) { 44 | return root.left; 45 | } else { 46 | BinaryTreeNode minNode = root.right; 47 | while (minNode.left != null) { 48 | minNode = minNode.left; 49 | } 50 | root.data = minNode.data; 51 | root.right = deleteData(minNode.data, root.right); 52 | return root; 53 | } 54 | } 55 | 56 | } 57 | 58 | private void printTree(BinaryTreeNode root) { 59 | if (root == null) { 60 | return; 61 | } 62 | String toBePrinted = root.data + ""; 63 | if (root.left != null) { 64 | toBePrinted += "L:" + root.left.data + ","; 65 | } 66 | 67 | if (root.right != null) { 68 | toBePrinted += "R:" + root.right.data; 69 | } 70 | System.out.println(toBePrinted); 71 | printTree(root.left); 72 | printTree(root.right); 73 | } 74 | 75 | public void printTree() { 76 | printTree(root); 77 | } 78 | 79 | private boolean hasDataHelper(int data, BinaryTreeNode root) { 80 | if (root == null) { 81 | return false; 82 | } 83 | 84 | if (root.data == data) { 85 | return true; 86 | } else if (data > root.data) { 87 | // call right 88 | return hasDataHelper(data, root.right); 89 | } else { 90 | // call left 91 | return hasDataHelper(data, root.left); 92 | } 93 | } 94 | 95 | public boolean hasData(int data) { 96 | return hasDataHelper(data, root); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /testing/src/sss.java: -------------------------------------------------------------------------------- 1 | public class sss { 2 | public static int length(LinkedListNode head){ 3 | int count=0; 4 | while(head!=null){ 5 | head=head.next; 6 | count++; 7 | } 8 | return count; 9 | } 10 | public static LinkedListNode bubbleSort(LinkedListNode head ){ 11 | if(head==null||head.next==null){ 12 | return head; 13 | } 14 | int lengt=length(head); 15 | int i=0; 16 | LinkedListNode prev=null,curr=head; 17 | while(i next=curr.next; 20 | if(curr.data>next.data){ 21 | if(prev==null){ 22 | curr.next=next.next; 23 | next.next=curr; 24 | head=next; 25 | next=prev; 26 | }else{ 27 | prev.next=curr.next; 28 | curr.next=next.next; 29 | next.next=curr; 30 | prev=next; 31 | } 32 | }else{ 33 | prev=curr; 34 | curr=next; 35 | next=next.next; 36 | } 37 | } 38 | } return head; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /testing/src/sw.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class sw { 3 | private static Scanner s= new Scanner(System.in); 4 | public static LinkedListNode input() { 5 | int data = s.nextInt(); 6 | 7 | LinkedListNode head = null; 8 | LinkedListNode tail = null; 9 | while (data!=-1) { 10 | LinkedListNode newNode = new LinkedListNode(data); 11 | if (head == null) { 12 | head = newNode; 13 | tail = newNode; 14 | } else { 15 | tail.next = newNode; 16 | tail = newNode; 17 | } 18 | data = s.nextInt(); 19 | } 20 | return head; 21 | } 22 | 23 | public static void print(LinkedListNode head) { 24 | while (head != null) { 25 | System.out.print(head.data + " "); 26 | head = head.next; 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | print(sss.bubbleSort(input())); 32 | } 33 | } 34 | class LinkedListNode { 35 | public T data; 36 | public LinkedListNode next; 37 | 38 | public LinkedListNode(T data) { 39 | this.data = data; 40 | this.next = null; 41 | } 42 | } 43 | --------------------------------------------------------------------------------