├── Array ├── ARRAY_generatePascalTriangle.java ├── ARRAY_nthRowOfPascalTriangle.java ├── README.md ├── findPivotIndex.java ├── findingTheDuplicateNumber.java ├── maximumSubarraySum.java ├── mergeOverlappingIntervals.java ├── mergeTwoSortedArraysWithoutUsingExtraSpace.java ├── nextPermutation.java ├── pascalTriangle1.java ├── pascalTriangle2.java ├── rearrangaElementsAlternatively.java ├── repeatAndMissingNumber.java ├── setMatricesZero.java ├── sort012.java ├── sortBinaryArray.java └── sumOfTwoArrays.java ├── Binary Search Tree ├── InorderSuccessor.java ├── LCAofBST.java ├── README.md ├── checkForBST.java ├── floorBST.java ├── populateNextRightPointerInEachNode.java └── searchInBST.java ├── Binary Tree ├── BEST_Question_minDistanceBtwTwoGivenNodesInBinaryTree.java ├── LCAofBinaryTree.java ├── LCS_BST.java ├── LCS_binaryTree.java ├── README.md ├── Traversals │ ├── README.md │ └── bundaryLevelTraversal.java ├── binaryTreeZigZagLevelOrderTraversal.java ├── bottomViewOfBinaryTree.java ├── checkForBalancedBinaryTree.java ├── constructBinaryTreeFromPostorderAndInorder.java ├── constructBinaryTreeFromPreorderAndInorder.java ├── diameterOfBinaryTree.java ├── findPrimeNumbersInRange.java ├── flattenBinaryTreeToLinkedList.java ├── heightOfBinaryTree.java ├── inorderTraversal.java ├── isTreesIdentical.java ├── leftViewOfBinaryTree.java ├── levelOrderTraversal.java ├── maxPathSum.java ├── maxWidthOfBinaryTree.java ├── postorderTraversal.java ├── preInPostTraversal.java ├── preorderTraversal.java ├── rightViewOfBinaryTree.java ├── sumRootToLeafNode.java ├── symmetricBinaryTree.java └── topViewOfBinaryTree.java ├── Bit Magic ├── AorBtoC.java ├── README.md ├── bitDifference.java ├── checkKthSetBit.java ├── longestConsecutiveOnes.java ├── nonRepeatingNumbers.java ├── numberOf1bits.java ├── powerOf2.java ├── powerSet.java ├── reverseBits.java └── twoNumbersWithOddOccurence.java ├── DP ├── 01KnapSack.java ├── LCS │ ├── Palindrome │ │ ├── README.md │ │ ├── longestPalindromeSubsequence.java │ │ ├── minDeletionToMakeStringIntoPalindrome.java │ │ └── minInsertionToMakeStringIntoPalindrome.java │ ├── Pattern Matching │ │ ├── README.md │ │ └── checkForSequence.java │ ├── README.md │ ├── longestCommonSubsequence.java │ ├── longestCommonSubstring.java │ ├── longestRepeatingSequence.java │ ├── minNumberOfInsertionsAndDeletion.java │ └── shortestCommonSuperSequence.java ├── MCM │ ├── Palindrome │ │ ├── README.md │ │ └── palindromePatitioning.java │ ├── README.md │ ├── booleanParenthesization.java │ └── matrixChainMultiplication.java ├── README.md ├── Unbounded Knapsack │ ├── README.md │ ├── coinChange.java │ ├── knapSackWithDuplicateItems.java │ ├── maximizeTheCutSegments.java │ └── minNumberOfCoins.java ├── countSubsetSumWithAGivenSum.java ├── partitonEqualSum.java ├── subsetSumProblem.java └── targetSum.java ├── Graph ├── BFS.java ├── BFS_BipartiteGraph.java ├── DFS.java ├── DFS_bipartitiGraph.java ├── DFS_detectCycleInUndirectedGraph.java ├── DFS_topoSort.java ├── README.md ├── detectCycleInDirectedGraph.java ├── detectCycleInUndirectedGraph.java ├── shortestDistanceInUnidirectedGraphWithUnitDistance.java ├── shortestPathInDirectedGraph.java ├── topoSortBFS.java └── topoSortDFS.java ├── Greedy Algo ├── Nmeetings.java ├── README.md ├── fractionalKnapsack.java ├── jobSequencing.java ├── minimumPlatform.java └── numberOfCoins.java ├── LinkedList ├── ClonelLinkedListWithNextAndRandomPointer.java ├── README.md ├── addTwoNumbers.java ├── deleteNodeInLL.java ├── detectLoopInLL.java ├── findStartingPointOfTheCycle.java ├── flatteningALL.java ├── intersectionPointOfTwoLinkedList.java ├── lengthOfLL.java ├── mergeTwoSortedLL.java ├── middleOfLinkedList.java ├── nthNodeFromEndOfLL.java ├── palindromeLL.java ├── removeNthNodeFromEndOfList.java ├── removingLoopInLL.java ├── reverseLinkedList.java ├── reverseNodeInKGroup.java └── swapNodeInPair.java ├── README.md ├── RECURSION ├── Core concept of String questions in recursion │ ├── README.md │ ├── WhatsApp_Image_2021-08-07_at_00.21.27[1].jpeg │ ├── WhatsApp_Image_2021-08-07_at_00.21.27_(1)[1].jpeg │ ├── WhatsApp_Image_2021-08-07_at_00.21.27_(2)[1].jpeg │ ├── WhatsApp_Image_2021-08-07_at_00.21.28[1].jpeg │ └── WhatsApp_Image_2021-08-07_at_00.21.28_(1)[1].jpeg ├── GoodQuestion_printNBit-binaryNumbers#1s>#0.java ├── Good_question_KthSymbolInGrammar.java ├── Good_question_generateBalancedParanthesis.java ├── M2_printAllPermutations.java ├── PermutationsOfNumbers.java ├── README.md ├── combinationsSum.java ├── combinationsSumSDE.java ├── deleteMiddleElementInStack.java ├── generateAllSubsetsOfString.java ├── letterCasePermutations.java ├── permutationWithSpaces.java ├── sortArrayUsingRecursion.java └── sortStackUsingRecursion.java ├── Sliding Window ├── README.md └── fixed size window │ ├── README.md │ ├── firstNegativeIntegerWindowOfSizeK.java │ └── maxSumSubarrayOfSizeK.java ├── Sorting ├── BUBBLE_SORT.java ├── COUNT_SORT.java ├── INSERTION_SORT.java ├── MERGE_SORT.java ├── QUICK_SORT.java ├── README.md ├── SELECTION_SORT.java ├── WAVE_SORT.java ├── countInversions.java ├── intersectionOfTwoSortedArrays.java └── unionOfTwoSortedArray.java ├── Stack ├── BFS.java ├── LRUCache.java ├── QueueUsingArray.java ├── README.md ├── StackUseArray.java ├── deleteMidElementOfStack.java ├── implementStackUsingQueue.java ├── largestAreaInHistogram.java ├── minStack.java ├── nextGreaterElement.java ├── nextSmallerElement.java ├── queueUsingStack.java ├── rainWaterTrapping.java ├── slidingWindowMaximum.java ├── stockSpanProblem.java └── validPalindrome.java ├── Strings ├── KMP_Algorithm.java ├── README.md ├── lookAndSayPattern.java ├── lpsArray.java ├── permutationsOfGivenString.java ├── removeCharacters.java ├── reverseWordsInString.java ├── rotateString.java ├── runLengthEncoding.java ├── stringMatching_naive.java └── validIPAddress.java ├── Two pointer ├── 3Sum.java ├── ClonelLinkedListWithNextAndRandomPointer.java ├── README.md ├── maxConsecutiveOnes.java ├── removeDuplicateFromSortedArray1.java ├── removeDuplicateFromSortedArray2.java └── trappingRainWater.java ├── binary search ├── README.md ├── elementAppearsOnlyOnceInSortedArray.java └── indexOfAnExtraElement.java ├── foundation ├── README.md ├── allPrime.java ├── matrix │ ├── README.md │ ├── printSpiral.java │ └── setMatricesZero.java └── string │ ├── README.md │ ├── checkPermutations.java │ ├── compressString.java │ ├── isPalindrome.java │ ├── occurenceOfString1InString2.java │ └── reverseSringWordByWord.java └── matrix ├── README.md ├── rotateMatrix.java ├── search2DMatrix.java ├── spiralMatrix.java └── transposeMatrix.java /Array/ARRAY_generatePascalTriangle.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> generate(int numRows) { 3 | List> ans = new ArrayList<>(); 4 | List row, prev = null; 5 | 6 | for(int i=0; i(); 8 | for(int j=0; j<=i; j++){ 9 | if(j == 0 || j == i) 10 | row.add(1); 11 | else 12 | row.add(prev.get(j-1) + prev.get(j)); 13 | } 14 | prev = row; 15 | ans.add(row); 16 | } 17 | 18 | return ans; 19 | } 20 | } 21 | 22 | 23 | -------------------------------------------------------------------------------- /Array/ARRAY_nthRowOfPascalTriangle.java: -------------------------------------------------------------------------------- 1 | // methdo 1 2 | // using nCr 3 | // space o(n) and time o(n) 4 | 5 | 6 | class Solution { 7 | public List getRow(int rowIndex) { 8 | List row = new ArrayList<>(); 9 | 10 | int prev = 1; 11 | row.add(prev); 12 | 13 | for(int i=1; i<=rowIndex; i++){ 14 | int curr = (prev * (rowIndex - i+1))/i; 15 | row.add(curr); 16 | prev = curr; 17 | } 18 | 19 | return row; 20 | } 21 | } 22 | 23 | 24 | // method 2 25 | // using additon of previous values; 26 | // time o(n2) and space o(n) 27 | 28 | class Solution { 29 | public List getRow(int rowIndex) { 30 | Integer ans[] = new Integer[rowIndex + 1]; 31 | Arrays.fill(ans, 0); 32 | ans[0] = 1; 33 | 34 | for(int i=1; i<=rowIndex; i++){ 35 | for(int j=i; j>0; j--) 36 | ans[j] = ans[j-1] + ans[j]; 37 | } 38 | 39 | return Arrays.asList(ans); 40 | } 41 | } 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Array/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Array/findPivotIndex.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int pivotIndex(int[] arr) { 3 | int n = arr.length; 4 | int sum=0, lSum = 0; 5 | for(int i: arr) 6 | sum += i; 7 | 8 | // right Sum = sum - arr[i]-lSum 9 | for(int i=0; i max) 69 | max = sum; 70 | if(sum < 0) 71 | sum = 0; 72 | } 73 | 74 | return max; 75 | } 76 | 77 | } 78 | 79 | -------------------------------------------------------------------------------- /Array/mergeTwoSortedArraysWithoutUsingExtraSpace.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // time o(nm) and space o(1) 3 | 4 | 5 | // some big test cases are failing 6 | class Solution 7 | { 8 | //Function to merge the arrays. 9 | public static void merge(long arr1[], long arr2[], int n, int m) 10 | { 11 | int i=0, j=0; 12 | 13 | while(i arr2[0]){ 15 | long temp = arr1[i]; 16 | arr1[i] = arr2[0]; 17 | arr2[0] = temp; 18 | 19 | 20 | if(m >= 2 && arr2[0] > arr2[1]) 21 | arrangeElementsInSortedWay(arr2); 22 | 23 | } 24 | 25 | i++; 26 | 27 | } 28 | 29 | } 30 | 31 | 32 | private static void arrangeElementsInSortedWay(long arr[]){ 33 | int n = arr.length; 34 | long val = arr[0]; 35 | 36 | int i=1; 37 | for(; i= arr[i]) 39 | arr[i-1] = arr[i]; 40 | else 41 | break; 42 | } 43 | 44 | if(i != n) 45 | arr[i-1] = val; 46 | 47 | } 48 | 49 | } 50 | 51 | 52 | // method 2 53 | // time o(nlogn) + o(mlogm) 54 | 55 | class Solution 56 | { 57 | public static void merge(long arr1[], long arr2[], int n, int m) 58 | { 59 | int j=0; 60 | int i=n-1; 61 | 62 | 63 | while(i>=0 && j=0 && arr[i] >= arr[i+1]) i--; 8 | 9 | if(i>=0){ 10 | int j = n-1; 11 | while(arr[i] >= arr[j]) j--; 12 | 13 | swap(arr, i, j); 14 | 15 | } 16 | 17 | reverse(arr, i+1, n-1); 18 | } 19 | 20 | private void reverse(int arr[], int sI, int eI){ 21 | // for(int i=sI, j=eI; i> generate(int numRows) { 5 | List> ans = new ArrayList<>(); 6 | List row, pre = null; 7 | 8 | for(int i=0; i(); 10 | for(int j=0; j<=i; j++){ 11 | if(j==0 || i==j) 12 | row.add(1); 13 | else 14 | row.add(pre.get(j-1) + pre.get(j)); 15 | } 16 | pre = row; 17 | ans.add(row); 18 | } 19 | 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Array/pascalTriangle2.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // time o(n2) 3 | class Solution { 4 | public List getRow(int rowIndex) { 5 | Integer ans[] = new Integer[rowIndex + 1]; 6 | Arrays.fill(ans, 0); 7 | ans[0] = 1; 8 | 9 | for(int i=1; i<=rowIndex; i++){ 10 | for(int j=i; j>0; j--){ 11 | ans[j] = ans[j-1] + ans[j]; 12 | } 13 | } 14 | 15 | return Arrays.asList(ans); 16 | } 17 | } 18 | 19 | 20 | // method 2 21 | // not valid for long integers 22 | 23 | // time o(n) 24 | class Solution { 25 | public List getRow(int rowIndex) { 26 | List ans = new ArrayList<>(); 27 | int prev = 1; 28 | ans.add(prev); 29 | for(int i=1; i<=rowIndex; i++){ 30 | int curr = (prev * (rowIndex - i + 1))/i; 31 | ans.add(curr); 32 | prev = curr; 33 | } 34 | 35 | return ans; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Array/rearrangaElementsAlternatively.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | 4 | public static void rearrange(int arr[], int n){ 5 | 6 | int maxIndex = n-1; 7 | int minIndex = 0; 8 | 9 | int me = arr[n-1] + 1; 10 | 11 | for(int i=0; i= 0; i--) { 53 | for (int j = cols - 1; j >= 1; j--) 54 | if (matrix[i][0] == 0 || matrix[0][j] == 0) 55 | matrix[i][j] = 0; 56 | if (col0 == 0) matrix[i][0] = 0; 57 | } 58 | } 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /Array/sort012.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] arr) { 3 | int l = 0, m = 0, h = arr.length - 1; 4 | 5 | while(m<=h) 6 | { 7 | if(arr[m] == 0){ 8 | swap(arr, m, l); 9 | m++; 10 | l++; 11 | } 12 | else if(arr[m] == 1) 13 | m++; 14 | else if(arr[m] == 2){ 15 | swap(arr, m, h); 16 | h--; 17 | } 18 | } 19 | } 20 | 21 | private void swap(int arr[], int m, int n){ 22 | int t = arr[m]; 23 | arr[m] = arr[n]; 24 | arr[n] = t; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Array/sortBinaryArray.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | static int[] SortBinaryArray(int arr[], int n) 5 | { 6 | int i=-1; 7 | int pivot = 0; 8 | 9 | for(int j=0; j=0 && n >=0){ 11 | int sum = carry + arr1[m] + arr2[n]; 12 | carry = sum/10; 13 | output[k] = sum%10; 14 | 15 | m--; 16 | n--; 17 | k--; 18 | } 19 | 20 | while(m >=0){ 21 | int sum = carry + arr1[m]; 22 | carry = sum/10; 23 | output[k] = sum%10; 24 | 25 | k--; 26 | m--; 27 | } 28 | 29 | while(n >=0){ 30 | int sum = carry + arr2[n]; 31 | carry = sum/10; 32 | output[k] = sum%10; 33 | 34 | k--; 35 | n--; 36 | } 37 | 38 | output[0] = carry; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Binary Search Tree/InorderSuccessor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 4 | 5 | TreeNode successor = null; 6 | 7 | while (root != null) { 8 | 9 | if (p.val >= root.val) { 10 | root = root.right; 11 | } else { 12 | successor = root; 13 | root = root.left; 14 | } 15 | } 16 | 17 | return successor; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Binary Search Tree/LCAofBST.java: -------------------------------------------------------------------------------- 1 | // method1 2 | // recursive 3 | 4 | 5 | 6 | class Solution { 7 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 8 | if(root == null) return null; 9 | 10 | if(root.val > p.val && root.val > q.val) 11 | return lowestCommonAncestor(root.left, p, q); 12 | else if(root.val < p.val && root.val < q.val) 13 | return lowestCommonAncestor(root.right, p, q); 14 | else 15 | return root; 16 | } 17 | } 18 | 19 | // method2 20 | // itetative 21 | 22 | class Solution { 23 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 24 | 25 | // Value of p 26 | int pVal = p.val; 27 | 28 | // Value of q; 29 | int qVal = q.val; 30 | 31 | // Start from the root node of the tree 32 | TreeNode node = root; 33 | 34 | // Traverse the tree 35 | while (node != null) { 36 | 37 | // Value of ancestor/parent node. 38 | int parentVal = node.val; 39 | 40 | if (pVal > parentVal && qVal > parentVal) { 41 | // If both p and q are greater than parent 42 | node = node.right; 43 | } else if (pVal < parentVal && qVal < parentVal) { 44 | // If both p and q are lesser than parent 45 | node = node.left; 46 | } else { 47 | // We have found the split point, i.e. the LCA node. 48 | return node; 49 | } 50 | } 51 | return null; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Binary Search Tree/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Binary Search Tree/floorBST.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public static int floorInBST(TreeNode root, int key) { 4 | int floor = -1; 5 | while (root != null) { 6 | if (root.data == key) { 7 | floor = root.data; 8 | return floor; 9 | } 10 | 11 | if (key > root.data) { 12 | floor = root.data; 13 | root = root.right; 14 | } 15 | else { 16 | root = root.left; 17 | } 18 | } 19 | return floor; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Binary Search Tree/searchInBST.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode searchBST(TreeNode root, int val) { 3 | if(root == null) 4 | return null; 5 | 6 | if(root.val == val) 7 | return root; 8 | 9 | if(root.val > val) 10 | return searchBST(root.left, val); 11 | else 12 | return searchBST(root.right, val); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Binary Tree/BEST_Question_minDistanceBtwTwoGivenNodesInBinaryTree.java: -------------------------------------------------------------------------------- 1 | class GfG { 2 | int findDist(Node root, int a, int b) { 3 | if(root == null) 4 | return -1; 5 | 6 | Node lca = findLCA(root, a, b); 7 | 8 | int d1 = pathDistance(lca, a, 0); 9 | int d2 = pathDistance(lca, b, 0); 10 | 11 | return d1+d2; 12 | } 13 | 14 | 15 | private static Node findLCA(Node root, int a, int b){ 16 | if(root == null) 17 | return null; 18 | 19 | if(root.data == a || root.data == b) 20 | return root; 21 | 22 | Node leftTree = findLCA(root.left, a, b); 23 | Node rightTree = findLCA(root.right, a, b); 24 | 25 | if(leftTree == null && rightTree == null) 26 | return null; 27 | else if(leftTree == null && rightTree != null) 28 | return rightTree; 29 | else if(leftTree != null && rightTree == null) 30 | return leftTree; 31 | else 32 | return root; 33 | } 34 | 35 | 36 | private static int pathDistance(Node root, int key, int len){ 37 | if(root == null) 38 | return 0; 39 | if(root.data == key) 40 | return len; 41 | 42 | return pathDistance(root.left, key, len+1) + pathDistance(root.right, key, len+1); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Binary Tree/LCAofBinaryTree.java: -------------------------------------------------------------------------------- 1 | // method1 2 | // time o(n) and space o(n) 3 | 4 | 5 | class Solution 6 | { 7 | Node lca(Node root, int n1,int n2) 8 | { 9 | ArrayList path1 = new ArrayList<>(); 10 | ArrayList path2 = new ArrayList<>(); 11 | 12 | // if we dont get a path then I simply return false; 13 | if(!getPath(root, n2, path1) || !getPath(root, n1, path2)) 14 | return null; 15 | 16 | int l1 = path1.size(); 17 | int l2 = path2.size(); 18 | 19 | int i=0, j=0; 20 | while(i path){ 33 | if(root == null) 34 | return false; 35 | 36 | // initially i am asumming root is a part of the path 37 | // thats why i am adding it into the path list 38 | // if in case it is not a path of a desirable path 39 | // then i will remove it in the end; 40 | 41 | path.add(root); 42 | 43 | if(root.data == key) 44 | return true; 45 | 46 | // if root's data is not equal to key 47 | // then I will search for it in left part of the tree and the right part of tree 48 | 49 | boolean flag1 = getPath(root.left, key, path); 50 | boolean flag2 = getPath(root.right, key, path); 51 | 52 | // if the root is not a part of path then we remove it from the list and return false; 53 | if(!flag1 && !flag2){ 54 | path.remove(path.size()-1); 55 | return false; 56 | } 57 | 58 | return true; 59 | 60 | } 61 | 62 | } 63 | 64 | 65 | 66 | 67 | // method 2 68 | // time o(n) and space o(1) 69 | 70 | 71 | class Solution 72 | { 73 | 74 | Node lca(Node root, int n1,int n2) 75 | { 76 | if(root == null) 77 | return null; 78 | if(root.data == n1 || root.data == n2) 79 | return root; 80 | 81 | // if ancestor is present in left or right sub tree 82 | Node leftTree = lca(root.left, n1, n2); 83 | Node rightTree = lca(root.right, n1, n2); 84 | 85 | if(leftTree == null && rightTree == null) 86 | return null; 87 | 88 | if(leftTree != null && rightTree == null) 89 | return leftTree; 90 | 91 | else if(leftTree == null && rightTree != null) 92 | return rightTree; 93 | 94 | else 95 | return root; 96 | } 97 | } 98 | 99 | 100 | -------------------------------------------------------------------------------- /Binary Tree/LCS_BST.java: -------------------------------------------------------------------------------- 1 | class BST 2 | { 3 | Node LCA(Node root, int n1, int n2) 4 | { 5 | if(root == null) return null; 6 | 7 | if(root.data > n1 && root.data > n2) 8 | return LCA(root.left, n1, n2); 9 | else if(root.data < n1 && root.data < n2) 10 | return LCA(root.right, n1, n2); 11 | else 12 | return root; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Binary Tree/LCS_binaryTree.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | 5 | Node lca(Node root, int n1,int n2) 6 | { 7 | if(root == null) return null; 8 | 9 | if(root.data == n1 || root.data == n2) return root; 10 | 11 | // search lca in the left tree 12 | Node leftNode = lca(root.left, n1, n2); 13 | Node rightNode = lca(root.right, n1, n2); 14 | 15 | if(leftNode == null && rightNode == null) return null; 16 | 17 | else if(leftNode == null && rightNode != null) return rightNode; 18 | 19 | else if(leftNode != null && rightNode == null) return leftNode; 20 | 21 | else 22 | return root; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Binary Tree/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Binary Tree/Traversals/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Binary Tree/Traversals/bundaryLevelTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.* ; 2 | import java.io.*; 3 | 4 | 5 | import java.util.ArrayList; 6 | 7 | public class Solution { 8 | public static ArrayList traverseBoundary(TreeNode root){ 9 | ArrayList res = new ArrayList<>(); 10 | if(root == null) return res; 11 | 12 | if(isLeaf(root) == false) 13 | res.add(root.data); 14 | addLeftBoundary(root, res); 15 | addLeaves(root, res); 16 | addRightBoundary(root, res); 17 | 18 | return res; 19 | } 20 | 21 | private static boolean isLeaf(TreeNode root){ 22 | if(root == null) return true; 23 | return root.left == null && root.right == null; 24 | } 25 | 26 | private static void addLeftBoundary(TreeNode root, ArrayList res){ 27 | TreeNode curr = root.left; 28 | while(curr != null){ 29 | if(!isLeaf(curr)) 30 | res.add(curr.data); 31 | if(curr.left != null) 32 | curr = curr.left; 33 | else 34 | curr = curr.right; 35 | } 36 | } 37 | 38 | private static void addRightBoundary(TreeNode root, ArrayList res){ 39 | Stack st = new Stack<>(); 40 | TreeNode curr = root.right; 41 | while(curr != null){ 42 | if(!isLeaf(curr)) 43 | st.push(curr.data); 44 | if(curr.right != null) 45 | curr = curr.right; 46 | else 47 | curr = curr.left; 48 | } 49 | 50 | while(!st.isEmpty()) 51 | res.add(st.pop()); 52 | } 53 | 54 | private static void addLeaves(TreeNode root, ArrayList res){ 55 | if(root == null) return; 56 | 57 | if(isLeaf(root)){ 58 | res.add(root.data); 59 | return; 60 | } 61 | 62 | addLeaves(root.left, res); 63 | addLeaves(root.right, res); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Binary Tree/bottomViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Pair{ 2 | Node node; 3 | int hd; 4 | 5 | Pair(Node node, int hd){ 6 | this.node = node; 7 | this.hd = hd; 8 | } 9 | } 10 | 11 | 12 | class Tree 13 | { 14 | static ArrayList bottomView(Node root) 15 | { 16 | if(root == null) 17 | return new ArrayList<>(); 18 | 19 | ArrayList ans = new ArrayList<>(); 20 | Queue queue = new LinkedList<>(); 21 | HashMap map = new HashMap<>(); 22 | queue.add(new Pair(root, 0)); 23 | 24 | while(!queue.isEmpty()){ 25 | Pair front = queue.poll(); 26 | Node curr = front.node; 27 | int dis = front.hd; 28 | 29 | // if(!map.containsKey(dis)) // remove this line and we will get the bottom view 30 | map.put(dis, curr); 31 | 32 | if(curr.left != null) 33 | queue.add(new Pair(curr.left, dis-1)); 34 | 35 | if(curr.right != null) 36 | queue.add(new Pair(curr.right, dis+1)); 37 | 38 | } 39 | 40 | int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; 41 | for(Map.Entry entry : map.entrySet()){ 42 | min = Math.min(min, entry.getKey()); 43 | max = Math.max(max, entry.getKey()); 44 | } 45 | 46 | for(int i=min; i<=max; i++) 47 | ans.add(map.get(i).data); 48 | 49 | return ans; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Binary Tree/checkForBalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Brute force 2 | // time o(n2) 3 | 4 | class Solution { 5 | public boolean isBalanced(TreeNode root) { 6 | if(root == null) return true; 7 | 8 | int lh = height(root.left); 9 | int rh = height(root.right); 10 | 11 | if(Math.abs(lh-rh) > 1) return false; 12 | 13 | boolean lTree = isBalanced(root.left); 14 | boolean rTree = isBalanced(root.right); 15 | 16 | return lTree != rTree ? false : (lTree == false ? false : true); 17 | } 18 | 19 | private int height(TreeNode root){ 20 | if(root == null) return 0; 21 | 22 | return 1 + Math.max(height(root.left), height(root.right)); 23 | } 24 | } 25 | 26 | // better optimal sol 27 | // time o(n) 28 | 29 | 30 | class Solution { 31 | public boolean isBalanced(TreeNode root) { 32 | return dfsHeight(root) != -1; 33 | } 34 | 35 | private int dfsHeight(TreeNode root){ 36 | if(root == null) return 0; 37 | 38 | int leftH = dfsHeight(root.left); 39 | if(leftH == -1) return -1; 40 | 41 | int rightH = dfsHeight(root.right); 42 | if(rightH == -1) return -1; 43 | 44 | if(Math.abs(leftH - rightH) > 1) return -1; 45 | 46 | return 1 + Math.max(leftH, rightH); 47 | } 48 | 49 | } 50 | 51 | 52 | 53 | // another way of writing sol using pair class 54 | // time o(n) 55 | class Pair{ 56 | int height = 0; 57 | boolean isBalance = true; 58 | } 59 | 60 | class Tree 61 | { 62 | 63 | boolean isBalanced(Node root) 64 | { 65 | return helper(root).isBalance; 66 | } 67 | private Pair helper(Node root){ 68 | if(root == null) 69 | return new Pair(); 70 | 71 | Pair l = helper(root.left); 72 | Pair r = helper(root.right); 73 | 74 | Pair ans = new Pair(); 75 | // for binary tree to be balanced we need to make sure every node of the 76 | // binary tree must be balance 77 | if(Math.abs(l.height-r.height) > 1 || l.isBalance == false || r.isBalance == false) 78 | ans.isBalance = false; 79 | ans.height = 1 + Math.max(l.height, r.height); 80 | 81 | return ans; 82 | } 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /Binary Tree/constructBinaryTreeFromPostorderAndInorder.java: -------------------------------------------------------------------------------- 1 | 2 | class GfG 3 | { 4 | Node buildTree(int in[], int post[], int n) { 5 | return helper(in, 0, n-1, post, 0, n-1); 6 | } 7 | 8 | private static Node helper(int in[], int inSi, int inEi, int po[], int poSi, int poEi){ 9 | if(inSi > inEi) return null; 10 | if(poSi > poEi) return null; 11 | 12 | int n = po.length; 13 | int rootData = po[poEi]; 14 | Node root = new Node(rootData); 15 | 16 | // find index of root node 17 | int index = -1; 18 | for(int i=inSi; i<=inEi; i++){ 19 | if(rootData == in[i]){ 20 | index = i; 21 | break; 22 | } 23 | } 24 | 25 | if(index == -1) return null; 26 | 27 | // doing required calculations 28 | 29 | // left part 30 | int inSiLeft = inSi; 31 | int inEiLeft = index - 1; 32 | int inSiRight = index + 1; 33 | int inEiRight = inEi; 34 | 35 | // right part 36 | int poSiLeft = poSi; 37 | int poEiLeft = poSiLeft + (inEiLeft - inSiLeft); 38 | int poSiRight = poEiLeft+1; 39 | int poEiRight = poEi - 1; 40 | 41 | root.left = helper(in, inSiLeft, inEiLeft, po, poSiLeft, poEiLeft); 42 | root.right = helper(in, inSiRight, inEiRight, po, poSiRight, poEiRight); 43 | 44 | return root; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Binary Tree/constructBinaryTreeFromPreorderAndInorder.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public static Node buildTree(int inorder[], int preorder[], int n) 4 | { 5 | return helper(inorder, 0, n-1, preorder, 0, n-1); 6 | } 7 | 8 | private static Node helper(int in[], int inSi, int inEi, int pr[], int prSi, int prEi){ 9 | int n = in.length; 10 | 11 | // base case 12 | if(inSi > inEi) return null; 13 | if(prSi > prEi) return null; 14 | 15 | // find index of the root 16 | int index = -1; 17 | int rootData = pr[prSi]; 18 | Node root = new Node(rootData); 19 | 20 | for(int i=inSi; i<=inEi; i++){ 21 | if(rootData == in[i]){ 22 | index = i; 23 | break; 24 | } 25 | } 26 | 27 | if(index == -1) return null; 28 | 29 | // doing required calculations; 30 | 31 | // left half 32 | int inSiLeft = inSi; 33 | int inEiLeft = index - 1; 34 | int inSiRight = index + 1; 35 | int inEiRight = inEi; 36 | 37 | // right half; 38 | int prSiLeft = prSi + 1; 39 | int prEiLeft = prSiLeft + (inEiLeft - inSiLeft); 40 | int prSiRight = prEiLeft + 1; 41 | int prEiRight = prEi; 42 | 43 | root.left = helper(in, inSiLeft, inEiLeft, pr, prSiLeft, prEiLeft); 44 | root.right = helper(in, inSiRight, inEiRight, pr, prSiRight, prEiRight); 45 | 46 | return root; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Binary Tree/diameterOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // without using pair class 3 | // time O(n2) && space o(1) 4 | 5 | 6 | 7 | class Solution { 8 | int diameter(Node root) { 9 | if(root == null) 10 | return 0; 11 | 12 | int op1 = 1 + height(root.left) + height(root.right); 13 | int op2 = diameter(root.left) ; 14 | int op3 = diameter(root.right); 15 | 16 | return Math.max(op1, Math.max(op2, op3)); 17 | } 18 | 19 | private static int height(Node root){ 20 | if(root == null) 21 | return 0; 22 | 23 | return 1 + Math.max(height(root.left), height(root.right)); 24 | } 25 | 26 | } 27 | 28 | 29 | // method 2 30 | // using pair class 31 | // time o(n) and space o(1) 32 | 33 | class Solution { 34 | int diameter(Node root) { 35 | if(root == null) return 0; 36 | 37 | return helper(root).diameter; 38 | } 39 | 40 | private Pair helper(Node root){ 41 | if(root == null) 42 | return new Pair(); 43 | 44 | 45 | Pair leftTree = helper(root.left); 46 | Pair rightTree = helper(root.right); 47 | 48 | Pair ans = new Pair(); 49 | 50 | int op1 = 1 + leftTree.height + rightTree.height; 51 | int op2 = leftTree.diameter; 52 | int op3 = rightTree.diameter; 53 | 54 | ans.height = 1 + Math.max(leftTree.height, rightTree.height); 55 | ans.diameter = Math.max(op1, Math.max(op2, op3)); 56 | 57 | return ans; 58 | } 59 | 60 | } 61 | 62 | 63 | class Pair{ 64 | int diameter; 65 | int height; 66 | 67 | Pair(){ 68 | diameter = 0; 69 | height = 0; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /Binary Tree/findPrimeNumbersInRange.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList primeRange(int M, int N) { 3 | ArrayList list = new ArrayList<>(); 4 | 5 | for(int i=M; i<=N; i++){ 6 | if(i == 1) continue; 7 | 8 | if(isPrime(i)) 9 | list.add(i); 10 | } 11 | 12 | return list; 13 | } 14 | 15 | private static boolean isPrime(int num){ 16 | int len = (int)Math.sqrt(num); 17 | for(int i=2; i<=len; i++){ 18 | if(num%i == 0) 19 | return false; 20 | } 21 | 22 | return true; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Binary Tree/flattenBinaryTreeToLinkedList.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // time O(N) and space O(N) 3 | 4 | class Solution { 5 | public void flatten(TreeNode root) { 6 | if(root == null) return; 7 | 8 | ArrayList list = new ArrayList<>(); 9 | preorder(root, list); 10 | root.left = null; 11 | root.right = null; 12 | TreeNode curr = root; 13 | 14 | int len = list.size(); 15 | for(int i=1; i list){ 26 | if(root == null) return; 27 | 28 | list.add(root); 29 | preorder(root.left, list); 30 | preorder(root.right, list); 31 | } 32 | 33 | } 34 | 35 | 36 | // method 2 37 | // time O(N) and space O(h), h is the height of the recursive stack; 38 | 39 | class Solution { 40 | TreeNode prev = null; 41 | public void flatten(TreeNode root) { 42 | if(root == null) return; 43 | flatter(root); 44 | } 45 | 46 | private void flatter(TreeNode root){ 47 | if(root == null) return; 48 | 49 | flatter(root.right); 50 | flatter(root.left); 51 | 52 | root.right = prev; 53 | root.left = null; 54 | prev = root; 55 | } 56 | 57 | } 58 | 59 | 60 | // method 3 61 | // using stack 62 | // time o(n) and space o(n) 63 | 64 | class Solution { 65 | public void flatten(TreeNode root) { 66 | Stack stack = new Stack<>(); 67 | stack.push(root); 68 | 69 | while(!stack.isEmpty()){ 70 | TreeNode currNode = stack.pop(); 71 | 72 | if(currNode.right!= null) 73 | stack.push(currNode.right); 74 | if(currNode.left != null) 75 | stack.push(currNode.left); 76 | 77 | if(!stack.isEmpty()) 78 | currNode.right = stack.peek(); 79 | 80 | currNode.left = null; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Binary Tree/heightOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Recursive solution; 2 | 3 | 4 | class Solution { 5 | public int maxDepth(TreeNode root) { 6 | if(root == null) 7 | return 0; 8 | 9 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 10 | } 11 | } 12 | 13 | 14 | // Iterative sol 15 | 16 | class Solution { 17 | public int maxDepth(TreeNode root) { 18 | if(root == null) 19 | return 0; 20 | int height = 0; 21 | Queue queue = new LinkedList<>(); 22 | queue.add(root); 23 | 24 | while(!queue.isEmpty()){ 25 | height++; 26 | int len = queue.size(); 27 | for(int i=0; i inorderTraversal(TreeNode root) { 3 | if(root == null) return new ArrayList(); 4 | 5 | Stack stack = new Stack<>(); 6 | List list = new ArrayList<>(); 7 | 8 | TreeNode curr = root; 9 | 10 | while(curr != null || !stack.isEmpty()){ 11 | while(curr != null){ 12 | stack.add(curr); 13 | curr = curr.left; 14 | } 15 | 16 | curr = stack.pop(); 17 | list.add(curr.val); 18 | curr = curr.right; 19 | } 20 | 21 | return list; 22 | } 23 | } 24 | 25 | 26 | // seconode way of writing code 27 | 28 | class Solution { 29 | public List inorderTraversal(TreeNode root) { 30 | Stack st = new Stack<>(); 31 | List list = new ArrayList<>(); 32 | 33 | TreeNode node = root; 34 | while(true){ 35 | if(node != null){ 36 | st.push(node); 37 | node = node.left; 38 | }else{ 39 | if(st.isEmpty()){ 40 | break; 41 | } 42 | node = st.pop(); 43 | list.add(node); 44 | node = node.right; 45 | } 46 | } 47 | 48 | return list; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Binary Tree/isTreesIdentical.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | boolean isIdentical(Node root1, Node root2) 5 | { 6 | if(root1 == null && root2 == null) 7 | return true; 8 | else if(root1 == null || root2 == null || root1.data != root2.data) 9 | return false; 10 | 11 | // int h1 = height(root1); 12 | // int h2 = height(root2); 13 | 14 | // if(h1 != h2) 15 | // return false; 16 | 17 | 18 | boolean flag1 = isIdentical(root1.left, root2.left); 19 | boolean flag2 = isIdentical(root1.right, root2.right); 20 | 21 | return flag1 && flag2; 22 | 23 | } 24 | 25 | private static int height(Node root){ 26 | if(root == null) 27 | return 0; 28 | 29 | return 1 + Math.max(height(root.left), height(root.right)); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Binary Tree/leftViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // using preorder traversal(DFS) 3 | // time o(n) and space o(h), h is the height of the binary tree 4 | 5 | class Tree 6 | { 7 | static boolean check[]; 8 | ArrayList leftView(Node root) 9 | { 10 | if(root == null) 11 | return new ArrayList<>(); 12 | 13 | 14 | int height = depth(root); 15 | check = new boolean[height]; 16 | 17 | ArrayList list = new ArrayList<>(); 18 | leftView(root, list, 0); 19 | 20 | return list; 21 | } 22 | 23 | private static void leftView(Node root, ArrayList list, int level){ 24 | if(root == null) return; 25 | 26 | if(check[level] == false){ 27 | list.add(root.data); 28 | check[level] = true; 29 | } 30 | 31 | leftView(root.left, list, level+1); 32 | leftView(root.right, list, level+1); 33 | 34 | return; 35 | } 36 | 37 | private static int depth(Node root){ 38 | if(root == null) 39 | return 0; 40 | 41 | return 1 + Math.max(depth(root.left), depth(root.right)); 42 | } 43 | 44 | } 45 | 46 | 47 | // method 2 48 | // using level order traversal 49 | // time o(n) and space o(n) 50 | 51 | class Tree 52 | { 53 | //Function to return list containing elements of left view of binary tree. 54 | ArrayList leftView(Node root) 55 | { 56 | if(root == null) 57 | return new ArrayList(); 58 | 59 | ArrayList ans = new ArrayList<>(); 60 | Queue queue = new LinkedList<>(); 61 | queue.add(root); 62 | queue.add(null); 63 | 64 | boolean flag = true; 65 | while(!queue.isEmpty()){ 66 | Node front; 67 | if(queue.peek() != null){ 68 | front = queue.poll(); 69 | 70 | if(flag){ 71 | ans.add(front.data); 72 | flag = false; 73 | } 74 | 75 | if(front.left != null) 76 | queue.add(front.left); 77 | 78 | if(front.right != null) 79 | queue.add(front.right); 80 | 81 | 82 | } else{ 83 | queue.poll(); 84 | flag = true; 85 | if(queue.isEmpty()) 86 | break; 87 | else 88 | queue.add(null); 89 | } 90 | } 91 | 92 | return ans; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Binary Tree/levelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> levelOrder(TreeNode root) { 3 | List> ans = new LinkedList<>(); 4 | Queue queue = new LinkedList<>(); 5 | 6 | if(root == null) 7 | return ans; 8 | 9 | queue.offer(root); 10 | while(!queue.isEmpty()){ 11 | int len = queue.size(); 12 | List list = new ArrayList<>(); 13 | for(int i=0; i q = new LinkedList<>(); 19 | q.add(new Pair(root, 0)); 20 | 21 | 22 | while(!q.isEmpty()){ 23 | int size = q.size(); 24 | int min = q.peek().num; 25 | int first = 0, last = 0; 26 | 27 | for(int i=0; i list = new ArrayList<>(); 9 | public List postorderTraversal(TreeNode root) { 10 | if(root == null) return list; 11 | 12 | postorderTraversal(root.left); 13 | postorderTraversal(root.right); 14 | list.add(root.val); 15 | 16 | return list; 17 | } 18 | } 19 | 20 | 21 | 22 | // method 2 23 | // iterative approach using 2 stacks 24 | // time o(n) && space o(n) 25 | 26 | 27 | class Solution { 28 | public List postorderTraversal(TreeNode root) { 29 | if(root == null) return new ArrayList<>(); 30 | 31 | Stack s1 = new Stack<>(); 32 | Stack s2 = new Stack<>(); 33 | 34 | s1.add(root); 35 | while(!s1.isEmpty()){ 36 | TreeNode node = s1.pop(); 37 | 38 | if(node.left != null) 39 | s1.add(node.left); 40 | if(node.right != null) 41 | s1.add(node.right); 42 | 43 | s2.add(node); 44 | } 45 | 46 | List list = new ArrayList<>(); 47 | while(!s2.isEmpty()) 48 | list.add(s2.pop().val); 49 | 50 | return list; 51 | } 52 | } 53 | 54 | // method 3 55 | // iterative approach using 1 stack 56 | // time o(n) && space o(n) 57 | 58 | class Solution { 59 | public List postorderTraversal(TreeNode root) { 60 | Stack st = new Stack<>(); 61 | List list = new ArrayList<>(); 62 | 63 | if(root == null) 64 | return list; 65 | 66 | TreeNode curr = root; 67 | while(curr != null || !st.isEmpty()){ 68 | if(curr != null){ 69 | st.push(curr); 70 | curr = curr.left; 71 | } else{ 72 | TreeNode temp = st.peek().right; 73 | if(temp != null) 74 | curr = temp; 75 | else{ 76 | temp = st.pop(); 77 | list.add(temp.val); 78 | while(!st.isEmpty() && temp == st.peek().right){ 79 | temp = st.pop(); 80 | list.add(temp.val); 81 | } 82 | } 83 | } 84 | } 85 | 86 | return list; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Binary Tree/preInPostTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class TreeNode { 3 | int val; 4 | TreeNode left; 5 | TreeNode right; 6 | TreeNode() {} 7 | TreeNode(int val) { 8 | this.val = val; 9 | } 10 | } 11 | class Pair { 12 | TreeNode node; 13 | int num; 14 | Pair(TreeNode _node, int _num) { 15 | num = _num; 16 | node = _node; 17 | } 18 | } 19 | public class TUF { 20 | public static void allTraversal(TreeNode root, List < Integer > pre, List < Integer > in , List < Integer > post) { 21 | Stack < Pair > st = new Stack < Pair > (); 22 | st.push(new Pair(root, 1)); 23 | 24 | if (root == null) return; 25 | 26 | while (!st.isEmpty()) { 27 | Pair it = st.pop(); 28 | 29 | // this is part of pre 30 | // increment 1 to 2 31 | // push the left side of the tree 32 | if (it.num == 1) { 33 | pre.add(it.node.val); 34 | it.num++; 35 | st.push(it); 36 | 37 | if (it.node.left != null) { 38 | st.push(new Pair(it.node.left, 1)); 39 | } 40 | } 41 | 42 | // this is a part of in 43 | // increment 2 to 3 44 | // push right 45 | else if (it.num == 2) { in .add(it.node.val); 46 | it.num++; 47 | st.push(it); 48 | 49 | if (it.node.right != null) { 50 | st.push(new Pair(it.node.right, 1)); 51 | } 52 | } 53 | // don't push it back again 54 | else { 55 | post.add(it.node.val); 56 | } 57 | } 58 | 59 | 60 | } 61 | public static void main(String args[]) { 62 | 63 | TreeNode root = new TreeNode(1); 64 | root.left = new TreeNode(2); 65 | root.left.left = new TreeNode(4); 66 | root.left.right = new TreeNode(5); 67 | root.right = new TreeNode(3); 68 | root.right.left = new TreeNode(6); 69 | root.right.right = new TreeNode(7); 70 | 71 | List < Integer > pre = new ArrayList < > (); 72 | List < Integer > in = new ArrayList < > (); 73 | List < Integer > post = new ArrayList < > (); 74 | allTraversal(root, pre, in , post); 75 | 76 | System.out.println("The preorder Traversal is : "); 77 | for (int nodeVal: pre) { 78 | System.out.print(nodeVal + " "); 79 | } 80 | System.out.println(); 81 | System.out.println("The inorder Traversal is : "); 82 | for (int nodeVal: in ) { 83 | System.out.print(nodeVal + " "); 84 | } 85 | System.out.println(); 86 | System.out.println("The postorder Traversal is : "); 87 | for (int nodeVal: post) { 88 | System.out.print(nodeVal + " "); 89 | } 90 | System.out.println(); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Binary Tree/preorderTraversal.java: -------------------------------------------------------------------------------- 1 | // method1 2 | // using recursion 3 | 4 | class Solution { 5 | List list = new ArrayList<>(); 6 | public List preorderTraversal(TreeNode root) { 7 | if(root == null) 8 | return list; 9 | 10 | list.add(root.val); 11 | if(root.left != null) 12 | preorderTraversal(root.left); 13 | if(root.right != null) 14 | preorderTraversal(root.right); 15 | 16 | return list; 17 | } 18 | } 19 | 20 | 21 | // method 2 22 | // iterative approach 23 | // time o(n) and space o(n) 24 | 25 | class Solution { 26 | public List preorderTraversal(TreeNode root) { 27 | if(root == null) 28 | return new ArrayList(); 29 | 30 | List ans = new ArrayList<>(); 31 | Stack st = new Stack<>(); 32 | 33 | st.add(root); 34 | 35 | while(!st.isEmpty()){ 36 | TreeNode node = st.pop(); 37 | 38 | if(node.right != null) 39 | st.add(node.right); 40 | if(node.left != null) 41 | st.add(node.left); 42 | 43 | ans.add(node.val); 44 | } 45 | 46 | return ans; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Binary Tree/rightViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // using level order traversal 3 | // Time o(n) and space o(n) 4 | 5 | class Solution { 6 | public List rightSideView(TreeNode root) { 7 | 8 | if(root == null) 9 | return new ArrayList(); 10 | 11 | ArrayList ans = new ArrayList<>(); 12 | Queue queue = new LinkedList<>(); 13 | queue.add(root); 14 | queue.add(null); 15 | 16 | boolean flag = true; 17 | while(!queue.isEmpty()){ 18 | TreeNode front; 19 | if(queue.peek() != null){ 20 | front = queue.poll(); 21 | 22 | if(flag){ 23 | ans.add(front.val); 24 | flag = false; 25 | } 26 | 27 | 28 | if(front.right != null) 29 | queue.add(front.right); 30 | 31 | if(front.left != null) 32 | queue.add(front.left); 33 | 34 | } else{ 35 | queue.poll(); 36 | flag = true; 37 | if(queue.isEmpty()) 38 | break; 39 | else 40 | queue.add(null); 41 | } 42 | } 43 | 44 | return ans; 45 | } 46 | } 47 | 48 | 49 | // method 2 50 | // using preorder traversal 51 | // time o(n) and space o(h), h is the height of the binary tree 52 | 53 | 54 | class Solution { 55 | 56 | boolean check[]; 57 | List rightSideView(TreeNode root) 58 | { 59 | if(root == null) 60 | return new ArrayList<>(); 61 | 62 | 63 | int height = depth(root); 64 | check = new boolean[height]; 65 | 66 | ArrayList list = new ArrayList<>(); 67 | leftView(root, list, 0); 68 | 69 | return list; 70 | } 71 | 72 | private void leftView(TreeNode root, ArrayList list, int level){ 73 | if(root == null) return; 74 | 75 | if(check[level] == false){ 76 | list.add(root.val); 77 | check[level] = true; 78 | } 79 | 80 | leftView(root.right, list, level+1); 81 | leftView(root.left, list, level+1); 82 | 83 | return; 84 | } 85 | 86 | private int depth(TreeNode root){ 87 | if(root == null) 88 | return 0; 89 | 90 | return 1 + Math.max(depth(root.left), depth(root.right)); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Binary Tree/sumRootToLeafNode.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int sumNumbers(TreeNode root, int res) { 3 | if(root == null) 4 | return 0; 5 | 6 | if(root.left == null && root.right == null) 7 | return res *10 + root.val; 8 | 9 | res = res *10 + root.val; 10 | 11 | int left = sumNumbers(root.left, res); 12 | int right = sumNumbers(root.right, res); 13 | 14 | return left + right; 15 | } 16 | 17 | public int sumNumbers(TreeNode root){ 18 | return sumNumbers(root, 0); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Binary Tree/symmetricBinaryTree.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // using recursion 3 | // time o(n) and space o(h), where h is the height of internal stack which is used during recursion calls; 4 | 5 | 6 | class GfG 7 | { 8 | public static boolean isSymmetric(Node root) 9 | { 10 | return isMirror(root, root); 11 | } 12 | 13 | 14 | private static boolean isMirror(Node root1, Node root2){ 15 | if(root1 == null && root2 == null) 16 | return true; 17 | 18 | // Two tree to be symmetric or mirror 19 | // 1. their root values must be equal; 20 | // 2. left sub tree of first tree must be symmetric to sub right tree of another tree 21 | // 3. vice versa of 2 step; 22 | 23 | if(root1 != null && root2 != null) 24 | if(root1.data == root2.data) 25 | return isMirror(root1.left, root2.right) && isMirror(root1.right, root2.left); 26 | 27 | return false; 28 | } 29 | } 30 | 31 | 32 | // method 2 33 | // using iterative approach 34 | // time o(n) and space (n) 35 | 36 | class Solution { 37 | public boolean isSymmetric(TreeNode root) { 38 | Queue queue = new LinkedList<>(); 39 | queue.add(root); 40 | queue.add(root); 41 | 42 | while(!queue.isEmpty()){ 43 | TreeNode t1 = queue.poll(); 44 | TreeNode t2 = queue.poll(); 45 | 46 | if(t1 == null && t2 == null) continue; 47 | if(t1 == null || t2 == null) return false; 48 | if(t1.val != t2.val) return false; 49 | 50 | queue.add(t1.left); 51 | queue.add(t2.right); 52 | queue.add(t1.right); 53 | queue.add(t2.left); 54 | } 55 | 56 | return true; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Binary Tree/topViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | class Pair{ 2 | Node node; 3 | int hd; 4 | 5 | Pair(Node node, int hd){ 6 | this.node = node; 7 | this.hd = hd; 8 | } 9 | } 10 | 11 | 12 | class Solution 13 | { 14 | static ArrayList topView(Node root) 15 | { 16 | if(root == null) 17 | return new ArrayList<>(); 18 | 19 | ArrayList ans = new ArrayList<>(); 20 | Queue queue = new LinkedList<>(); 21 | HashMap map = new HashMap<>(); 22 | queue.add(new Pair(root, 0)); 23 | 24 | while(!queue.isEmpty()){ 25 | Pair front = queue.poll(); 26 | Node curr = front.node; 27 | int dis = front.hd; 28 | 29 | if(!map.containsKey(dis)) 30 | map.put(dis, curr); 31 | 32 | if(curr.left != null) 33 | queue.add(new Pair(curr.left, dis-1)); 34 | 35 | if(curr.right != null) 36 | queue.add(new Pair(curr.right, dis+1)); 37 | 38 | } 39 | 40 | int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; 41 | for(Map.Entry entry : map.entrySet()){ 42 | min = Math.min(min, entry.getKey()); 43 | max = Math.max(max, entry.getKey()); 44 | } 45 | 46 | for(int i=min; i<=max; i++) 47 | ans.add(map.get(i).data); 48 | 49 | return ans; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Bit Magic/AorBtoC.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minFlips(int a, int b, int c) { 3 | int totalCount = 0; 4 | 5 | for(int i=0; i<32; i++){ 6 | int x = a & (1<0 || b>0){ 8 | if((a&1) == 1 || (b&1) == 1) 9 | count++; 10 | 11 | if((a&1) == 1 && (b&1) == 1) 12 | count--; 13 | 14 | a = a>>1; 15 | b = b>>1; 16 | } 17 | return count; 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Bit Magic/checkKthSetBit.java: -------------------------------------------------------------------------------- 1 | 2 | class CheckBit 3 | { 4 | // using left shift operator 5 | static boolean checkKthBit(int n, int k) 6 | { 7 | return (n & (1 << k)) != 0; 8 | } 9 | 10 | 11 | 12 | // using right shift operator 13 | static boolean checkKthBit(int n, int k) 14 | { 15 | return (((n>>k) & 1) != 0); 16 | } 17 | 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Bit Magic/longestConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public static int maxConsecutiveOnes(int n) { 4 | int max = 0; 5 | int count = 0; 6 | while(n > 0){ 7 | if((n&1) == 1){ 8 | count++; 9 | max = Math.max(max, count); 10 | } else 11 | count = 0; 12 | 13 | n = n >>1; 14 | } 15 | 16 | return max; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Bit Magic/nonRepeatingNumbers.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int[] singleNumber(int[] arr) 4 | { 5 | int n = arr.length; 6 | int res = 0; 7 | for(int i: arr) 8 | res ^= i; 9 | 10 | int set = res & ~(res-1); 11 | int gp1=0, gp2=0; 12 | 13 | for(int i=0; i 0){ 9 | if((n & 1) == 1) 10 | res++; 11 | 12 | n = n>>1; 13 | } 14 | return res; 15 | } 16 | } 17 | 18 | 19 | 20 | // method 2 21 | // time o(total bits in n) 22 | 23 | class Solution { 24 | static int setBits(int n) { 25 | int res = 0; 26 | while(n > 0){ 27 | if(n%2 != 0) 28 | res++; 29 | 30 | n = n/2; 31 | } 32 | return res; 33 | } 34 | } 35 | 36 | 37 | 38 | 39 | 40 | // method 3 41 | // using Brion kerningam's Algo 42 | // time O(total number of set bits in n) 43 | 44 | 45 | class Solution { 46 | static int setBits(int n) { 47 | int res = 0; 48 | while(n != 0){ 49 | n = (n & (n-1)); 50 | res++; 51 | } 52 | return res; 53 | } 54 | } 55 | 56 | // method 4 57 | // time O(total number of set bits in n) 58 | 59 | 60 | class Solution { 61 | static int setBits(int n) { 62 | int res = 0; 63 | while(n != 0){ 64 | // by this we are removing right most set bit 65 | // 110 -> 100, after the operation 66 | n = n - (n&(-n)); 67 | res++; 68 | } 69 | return res; 70 | } 71 | } 72 | 73 | 74 | 75 | // method 5 76 | // using lookup table method for 32 bit numbers; 77 | // time o(1) 78 | 79 | // in this approach I split 32 bits into 4 section of 8 bits each; 80 | class Solution { 81 | static int setBits(int n) { 82 | int table[] = new int[256]; // 2^8 = 256 83 | 84 | table[0] = 0; 85 | // initializing how many set bits are there in each number from 1 to 256; 86 | for(int i=1; i<256; i++) 87 | table[i] = (i&1) + table[i/2]; 88 | 89 | int res = table[n & 0xff]; // 0xff -> 11111111 90 | n = n>>8; 91 | 92 | res += table[n & 0xff]; 93 | n = n >> 8; 94 | 95 | res += table[n & 0xff]; 96 | n = n >> 8; 97 | 98 | res += table[n & 0xff]; 99 | n = n >> 8; 100 | 101 | return res; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Bit Magic/powerOf2.java: -------------------------------------------------------------------------------- 1 | 2 | // method 1 3 | 4 | 5 | class Solution{ 6 | public static boolean isPowerofTwo(long n){ 7 | 8 | while(n != 1){ 9 | if(n%2 != 0) 10 | return false; 11 | 12 | n = n/2; 13 | } 14 | return true; 15 | } 16 | 17 | } 18 | 19 | 20 | 21 | // method 2; 22 | 23 | class Solution{ 24 | public static boolean isPowerofTwo(long n){ 25 | 26 | if(n == 0) 27 | return false; 28 | 29 | while(n != 1){ 30 | if((n&1) != 1) 31 | return false; 32 | 33 | n = n>>1; 34 | } 35 | return true; 36 | } 37 | 38 | } 39 | 40 | 41 | 42 | 43 | // method 3 44 | class Solution{ 45 | public static boolean isPowerofTwo(long n){ 46 | 47 | if(n == 0) return false; 48 | return ((n&(n-1)) == 0); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Bit Magic/powerSet.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public List AllPossibleStrings(String s) 4 | { 5 | ArrayList a = new ArrayList<>(); 6 | int n = s.length(); 7 | int powerSet = (int)Math.pow(2, n); 8 | 9 | for(int counter = 0; counter>1; 9 | } 10 | 11 | return res; 12 | } 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /Bit Magic/twoNumbersWithOddOccurence.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int[] twoOddNum(int arr[], int n) 4 | { 5 | int res1 = 0; 6 | int res2 = 0; 7 | int xor = 0; 8 | 9 | for(int i: arr) 10 | xor = xor^i; 11 | 12 | int set = xor & ~(xor-1); // finding the right most set bit; 13 | 14 | for(int i=0; i w) 50 | t[n][w] = helper(w, wt, val, n-1, t); 51 | 52 | 53 | return t[n][w]; 54 | } 55 | 56 | } 57 | 58 | 59 | // method 3 tabular form 60 | 61 | class Solution 62 | { 63 | //Function to return max value that can be put in knapsack of capacity W. 64 | static int knapSack(int W, int wt[], int val[], int n) 65 | { 66 | int t[][] = new int[n+1][W+1]; 67 | 68 | for(int i=0; i=0; i--) 8 | str2 += str1.charAt(i); 9 | 10 | return lcs(str1, str2); 11 | } 12 | 13 | private static int lcs(String str1, String str2){ 14 | int n = str1.length(); 15 | int m = str2.length(); 16 | 17 | int t[][] = new int[n+1][m+1]; 18 | 19 | for(int i=0; i<=n; i++){ 20 | for(int j=0; j<=m; j++){ 21 | if(i==0 || j==0) 22 | t[i][j] = 0; 23 | else if(str1.charAt(i-1) == str2.charAt(j-1)) 24 | t[i][j] = 1 + t[i-1][j-1]; 25 | else 26 | t[i][j] = Math.max(t[i][j-1], t[i-1][j]); 27 | } 28 | } 29 | 30 | return t[n][m]; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /DP/LCS/Palindrome/minDeletionToMakeStringIntoPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int minimumNumberOfDeletions(String str1) { 3 | int len = str1.length(); 4 | String str2 = ""; 5 | for(int i=len-1; i>=0; i--) 6 | str2 += str1.charAt(i); 7 | 8 | // length of lps = lcs(str1, str2); 9 | 10 | int lpsLength = lcs(str1, str2); 11 | return len - lpsLength; 12 | } 13 | 14 | private static int lcs(String str1, String str2){ 15 | int n = str1.length(); 16 | int m = str2.length(); 17 | 18 | int t[][] = new int[n+1][m+1]; 19 | 20 | for(int i=0; i<=n; i++){ 21 | for(int j=0; j<=m; j++){ 22 | if(i==0 || j==0) 23 | t[i][j] = 0; 24 | else if(str1.charAt(i-1) == str2.charAt(j-1)) 25 | t[i][j] = 1 + t[i-1][j-1]; 26 | else 27 | t[i][j] = Math.max(t[i-1][j], t[i][j-1]); 28 | } 29 | } 30 | 31 | return t[n][m]; 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /DP/LCS/Palindrome/minInsertionToMakeStringIntoPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int countMin(String str1) 3 | { 4 | int n = str1.length(); 5 | String str2 = ""; 6 | 7 | // reverse str1; 8 | for(int i=n-1; i>=0; i--) 9 | str2 += str1.charAt(i); 10 | 11 | 12 | int t[][] = new int[n+1][n+1]; 13 | 14 | for(int i=0; i<=n; i++) 15 | for(int j=0; j<=n; j++) 16 | t[i][j] = -1; 17 | 18 | // length of lps -> lcs(str1, reverse(str1)) 19 | // # of deletion = # of insertion 20 | return n - lcs(str1, str2, n, n, t); 21 | } 22 | 23 | private static int lcs(String str1, String str2, int n, int m, int t[][]){ 24 | if(n == 0 || m == 0) 25 | return 0; 26 | 27 | if(t[n][m] != -1) 28 | return t[n][m]; 29 | 30 | if(str1.charAt(n-1) == str2.charAt(m-1)) 31 | return t[n][m] = 1 + lcs(str1, str2, n-1, m-1, t); 32 | else 33 | return t[n][m] = Math.max(lcs(str1, str2, n-1, m, t), lcs(str1, str2, n, m-1, t)); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /DP/LCS/Pattern Matching/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DP/LCS/Pattern Matching/checkForSequence.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // using LCS 3 | // time o(n2) and space o(n2) 4 | 5 | class Solution{ 6 | boolean isSubSequence(String str1, String str2){ 7 | int n = str1.length(); 8 | int m = str2.length(); 9 | 10 | int t[][] = new int[n+1][m+1]; 11 | 12 | for(int i=0; i<=n; i++) 13 | for(int j=0; j<=m; j++) 14 | t[i][j] = -1; 15 | 16 | int val = lcs(str1, str2, n, m, t); 17 | // System.out.println(val); 18 | return val == n; 19 | } 20 | 21 | private static int lcs(String str1, String str2, int n, int m, int t[][]){ 22 | if(n == 0 || m == 0) 23 | return 0; 24 | 25 | if(t[n][m] != -1) 26 | return t[n][m]; 27 | 28 | if(str1.charAt(n-1) == str2.charAt(m-1)) 29 | return t[n][m] = 1 + lcs(str1, str2, n-1, m-1, t); 30 | else 31 | return t[n][m] = Math.max(lcs(str1, str2, n-1, m, t), lcs(str1, str2, n, m-1, t)); 32 | } 33 | 34 | } 35 | 36 | 37 | // method 2 38 | // using two pointers 39 | // time o(n) and space o(1) 40 | 41 | class Solution{ 42 | boolean isSubSequence(String str1, String str2){ 43 | int n = str1.length(); 44 | int m = str2.length(); 45 | 46 | int i=0, j=0; 47 | int count = 0; 48 | while(i max) 23 | max = t[i][j]; 24 | } 25 | 26 | return max; 27 | } 28 | } 29 | 30 | 31 | // memoized code 32 | // time o(n2) and space o(n2) 33 | 34 | class Solution{ 35 | int longestCommonSubstr(String s1, String s2, int x, int y){ 36 | 37 | int t[][] = new int[x+1][y+1]; 38 | for(int i=0; i<=x; i++) 39 | for(int j=0; j<=y; j++) 40 | t[i][j] = -1; 41 | 42 | helper(x, y, s1, s2, t); 43 | 44 | int max = -1; 45 | for(int i=0; i<=x; i++) 46 | for(int j=0; j<=y; j++) 47 | if(max < t[i][j]) 48 | max = t[i][j]; 49 | 50 | return max; 51 | } 52 | 53 | private static int helper(int x, int y, String s1, String s2, int t[][]){ 54 | if(x == 0 || y == 0) 55 | return 0; 56 | 57 | if(t[x][y] != -1) 58 | return t[x][y]; 59 | 60 | helper(x-1, y, s1, s2, t); 61 | helper(x, y-1, s1, s2, t); 62 | 63 | if(s1.charAt(x-1) == s2.charAt(y-1)) 64 | return t[x][y] = 1 + helper(x-1, y-1, s1, s2, t); 65 | 66 | return t[x][y] = 0; 67 | 68 | } 69 | 70 | } 71 | 72 | -------------------------------------------------------------------------------- /DP/LCS/longestRepeatingSequence.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int LongestRepeatingSubsequence(String str1) 4 | { 5 | String str2 = str1; 6 | int n = str1.length(); 7 | int m = n; 8 | 9 | int t[][] = new int[n+1][m+1]; 10 | 11 | for(int i=0; i<=n; i++){ 12 | for(int j=0; j<=m; j++){ 13 | if(i == 0 || j == 0) 14 | t[i][j] = 0; 15 | else if(i != j && str1.charAt(i-1) == str2.charAt(j-1)) 16 | t[i][j] = 1 + t[i-1][j-1]; 17 | else 18 | t[i][j] = Math.max(t[i-1][j], t[i][j-1]); 19 | } 20 | } 21 | 22 | return t[n][m]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DP/LCS/minNumberOfInsertionsAndDeletion.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int minOperations(String str1, String str2) 4 | { 5 | int n = str1.length(); 6 | int m = str2.length(); 7 | 8 | int t[][] = new int[n+1][m+1]; 9 | 10 | for(int i=0; i<=n; i++){ 11 | for(int j=0; j<=m; j++){ 12 | if(i==0 || j==0) 13 | t[i][j] = 0; 14 | else if(str1.charAt(i-1) == str2.charAt(j-1)) 15 | t[i][j] = 1 + t[i-1][j-1]; 16 | else 17 | t[i][j] = Math.max(t[i][j-1], t[i-1][j]); 18 | } 19 | } 20 | 21 | return m+n-2*t[n][m]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /DP/LCS/shortestCommonSuperSequence.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public static int shortestCommonSupersequence(String s1,String s2,int m,int n) 4 | { 5 | int t[][] = new int[m+1][n+1]; 6 | 7 | for(int i=0; i<=m; i++){ 8 | for(int j=0; j<=n; j++){ 9 | if(i == 0 || j == 0) 10 | t[i][j] = 0; 11 | else if(s1.charAt(i-1) == s2.charAt(j-1)) 12 | t[i][j] = 1 + t[i-1][j-1]; 13 | else 14 | t[i][j] = Math.max(t[i][j-1], t[i-1][j]); 15 | } 16 | } 17 | 18 | int max = -1; 19 | for(int i=1; i<=m; i++) 20 | for(int j=1; j<=n; j++) 21 | if(max < t[i][j]) 22 | max = t[i][j]; 23 | 24 | return m + n - max; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DP/MCM/Palindrome/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DP/MCM/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DP/MCM/matrixChainMultiplication.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // recursive soltuion 3 | // time o(2^N) and space o(1) 4 | 5 | 6 | class Solution{ 7 | static int matrixMultiplication(int n, int arr[]) 8 | { 9 | int i = 1; 10 | int j = n-1; 11 | 12 | return helper(arr, i, j); 13 | } 14 | 15 | private static int helper(int arr[], int i, int j){ 16 | if(i >= j) 17 | return 0; 18 | 19 | int ans = Integer.MAX_VALUE; 20 | for(int k=i; k<=j-1; k++){ 21 | int tempAns = helper(arr, i, k) + helper(arr, k+1, j) + arr[i-1]*arr[k]*arr[j]; 22 | 23 | if(tempAns < ans) 24 | ans = tempAns; 25 | } 26 | 27 | return ans; 28 | } 29 | 30 | } 31 | 32 | 33 | 34 | // method 2 35 | // memoized approach 36 | // time o(n^3) and space o(n^2) 37 | 38 | 39 | 40 | lass Solution{ 41 | static int matrixMultiplication(int n, int arr[]) 42 | { 43 | int t[][] = new int[n][n]; 44 | 45 | for(int i=0; i=j) 54 | return 0; 55 | 56 | if(t[i][j] != -1) 57 | return t[i][j]; 58 | 59 | int min = Integer.MAX_VALUE; 60 | for(int k=i; k<=j-1; k++){ 61 | int tempAns = helper(arr, i, k, t) + helper(arr, k+1, j, t) + arr[i-1]*arr[k]*arr[j]; 62 | 63 | if(min > tempAns) 64 | min = tempAns; 65 | } 66 | 67 | return t[i][j] = min; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /DP/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DP/Unbounded Knapsack/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DP/Unbounded Knapsack/coinChange.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public long count(int S[], int m, int n) 4 | { 5 | int sum = n; 6 | n = m; 7 | long t[][] = new long[n+1][sum+1]; 8 | 9 | for(int i=0; i<=n; i++) 10 | t[i][0] = 1; 11 | for(int i=1; i<=sum; i++) 12 | t[0][i] = 0; 13 | 14 | for(int i=1; i<=n; i++){ 15 | for(int j=1; j<=sum; j++){ 16 | if(S[i-1] <= j) 17 | t[i][j] = t[i][j-S[i-1]] + t[i-1][j]; 18 | else 19 | t[i][j] = t[i-1][j]; 20 | } 21 | } 22 | 23 | return t[n][sum]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /DP/Unbounded Knapsack/knapSackWithDuplicateItems.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int knapSack(int n, int w, int val[], int wt[]) 3 | { 4 | int t[][] = new int[n+1][w+1]; 5 | 6 | for(int i=0; i<=n; i++){ 7 | for(int j=0; j<=w; j++){ 8 | if(i == 0 || j == 0) 9 | t[i][j] = 0; 10 | else if(wt[i-1] <= j) 11 | t[i][j] = Math.max(val[i-1] + t[i][j-wt[i-1]], t[i-1][j]); 12 | else 13 | t[i][j] = t[i-1][j]; 14 | } 15 | } 16 | 17 | return t[n][w]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DP/Unbounded Knapsack/maximizeTheCutSegments.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to find the maximum number of cuts. 4 | public int maximizeCuts(int n, int x, int y, int z) 5 | { 6 | int size = n; 7 | n = 3; // denoting the count of cuts which we can do , like x, y and z total -> 3 8 | int arr[] = new int[3]; 9 | arr[0] = x; 10 | arr[1] = y; 11 | arr[2] = z; 12 | 13 | int t[][] = new int[n+1][size+1]; 14 | 15 | for(int i=0; i<=n; i++){ 16 | for(int j=0; j<=size; j++){ 17 | if(i == 0 || j == 0){ 18 | if(i == 0) 19 | t[i][j] = Integer.MIN_VALUE; 20 | else if(j == 0) 21 | t[i][j] = 0; 22 | } 23 | else if(arr[i-1] <= j) 24 | t[i][j] = Math.max(1+t[i][j-arr[i-1]], t[i-1][j]); 25 | else 26 | t[i][j] = t[i-1][j]; 27 | } 28 | } 29 | 30 | return t[n][size] <0?0:t[n][size]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /DP/Unbounded Knapsack/minNumberOfCoins.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int coinChange(int[] coins, int amount) { 3 | int sum = amount; 4 | int n = coins.length; 5 | int t[][] = new int[n+1][sum+1]; 6 | 7 | // initialization first row and column 8 | for(int i=0; i<=sum; i++) 9 | t[0][i] = Integer.MAX_VALUE - 1; 10 | for(int j=1; j<=n; j++) 11 | t[j][0] = 0; 12 | 13 | 14 | // initialize second row 15 | for(int j=1; j<=sum; j++){ 16 | if(j%coins[0] == 0) 17 | t[1][j] = coins[0]/j; 18 | else 19 | t[1][j] = Integer.MAX_VALUE-1; 20 | } 21 | 22 | // logic 23 | for(int i=1; i<=n; i++){ 24 | for(int j=1; j<=sum; j++){ 25 | if(coins[i-1] <= j) 26 | t[i][j] = Math.min(1 + t[i][j-coins[i-1]], t[i-1][j]); 27 | else 28 | t[i][j] = t[i-1][j]; 29 | } 30 | } 31 | 32 | return t[n][sum] != Integer.MAX_VALUE-1 ? t[n][sum] : -1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /DP/countSubsetSumWithAGivenSum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraySum(int[] arr, int sum) { 3 | int n = arr.length; 4 | int t[][] = new int[n+1][sum+1]; 5 | 6 | for(int i=0; i<=n; i++) 7 | t[i][0] = 1; 8 | for(int j=1; j<=sum; j++) 9 | t[0][j] = 0; 10 | 11 | for(int i=1; i<=n; i++){ 12 | for(int j=1; j<=sum; j++){ 13 | if(arr[i-1] <= j) 14 | t[i][j] = t[i-1][j-arr[i-1]] + t[i-1][j]; 15 | else 16 | t[i][j] = t[i-1][j]; 17 | } 18 | } 19 | return t[n][sum]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /DP/partitonEqualSum.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int equalPartition(int n, int arr[]) 3 | { 4 | int sum = 0; 5 | for(int i: arr) 6 | sum += i; 7 | 8 | if(sum%2 != 0) 9 | return 0; 10 | 11 | sum = sum/2; 12 | 13 | boolean t[][] = new boolean[n+1][sum+1]; 14 | for(int i=0; i<=n; i++) 15 | t[i][0] = true; 16 | for(int j=1; j<=sum; j++) 17 | t[0][j] = false; 18 | 19 | 20 | for(int i=1; i<=n; i++){ 21 | for(int j=1; j<=sum; j++){ 22 | if(arr[i-1] <= j) 23 | t[i][j] = t[i-1][j-arr[i-1]] || t[i-1][j]; 24 | else 25 | t[i][j] = t[i-1][j]; 26 | } 27 | } 28 | 29 | return t[n][sum] == true ? 1 : 0; 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /DP/subsetSumProblem.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | 4 | static Boolean isSubsetSum(int n, int arr[], int sum){ 5 | boolean t[][] = new boolean[n+1][sum+1]; 6 | 7 | // initialization 8 | for(int i=0; i<=n; i++) 9 | t[i][0] = true; 10 | 11 | for(int i=1; i<=sum; i++) 12 | t[0][i] = false; 13 | 14 | // logic -> similar with 01 knapsack 15 | for(int i=1; i<=n; i++){ 16 | for(int j=1; j<=sum; j++){ 17 | if(arr[i-1] <= j) 18 | t[i][j] = t[i-1][j-arr[i-1]] || t[i-1][j]; 19 | else 20 | t[i][j] = t[i-1][j]; 21 | } 22 | } 23 | 24 | return t[n][sum]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DP/targetSum.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int findTargetSumWays(int[] arr, int target) { 4 | 5 | if(arr.length == 1) 6 | if(arr[0] < target) 7 | return 0; 8 | 9 | 10 | int n = arr.length; 11 | int sum = 0; 12 | int zero = 0; 13 | for(int i: arr){ 14 | sum += i; 15 | if(i == 0) 16 | zero++; 17 | } 18 | 19 | if(target > sum) 20 | return 0; 21 | else if((target+sum)%2 != 0) 22 | return 0; 23 | 24 | int key = (sum + target)/2; 25 | int t[][] = new int[n+1][key+1]; 26 | 27 | for(int i=0; i bfsOfGraph(int V,ArrayList> adj) 4 | { 5 | ArrayList bfs = new ArrayList<>(); 6 | boolean vis[] = new boolean[V+1]; 7 | 8 | for(int i=0; i> adj, ArrayList bfs, int sI){ 18 | Queue queue = new LinkedList<>(); 19 | 20 | queue.add(sI); 21 | vis[sI] = true; 22 | 23 | while(!queue.isEmpty()){ 24 | Integer node = queue.poll(); 25 | bfs.add(node); 26 | 27 | // traversing adjacent nodes 28 | for(Integer i: adj.get(node)) { 29 | if(!vis[i]){ 30 | queue.add(i); 31 | vis[i] = true; 32 | } 33 | } 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Graph/BFS_BipartiteGraph.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public boolean isBipartite(int V, ArrayList>adj) 4 | { 5 | int color[] = new int[V]; 6 | Arrays.fill(color, -1); 7 | 8 | for(int i=0; i>adj){ 18 | color[node] = 1; 19 | Queue queue = new LinkedList<>(); 20 | queue.add(node); 21 | 22 | while(!queue.isEmpty()){ 23 | int front = queue.poll(); 24 | 25 | for(Integer i: adj.get(front)){ 26 | if(color[i] == -1){ 27 | // assigning opposite color to the adjacent nodes 28 | color[i] = 1 - color[front]; 29 | queue.add(i); 30 | } 31 | else if(color[i] == color[front]) 32 | return false; 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Graph/DFS.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to return a list containing the DFS traversal of the graph. 4 | public ArrayList dfsOfGraph(int V, ArrayList> adj) 5 | { 6 | boolean vis[] = new boolean[V]; 7 | ArrayList storeDFS = new ArrayList<>(); 8 | for(int i=0; i> adj, boolean vis[], ArrayList storeDFS){ 17 | storeDFS.add(node); 18 | vis[node] = true; 19 | 20 | for(Integer i: adj.get(node)){ 21 | if(!vis[i]) 22 | dfs(i, adj, vis, storeDFS); 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Graph/DFS_bipartitiGraph.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public boolean isBipartite(int v, ArrayList>adj) 4 | { 5 | int color[] = new int[v]; 6 | Arrays.fill(color, -1); 7 | 8 | for(int i=0; i>adj){ 18 | if(color[node] == -1) 19 | color[node] = 1; 20 | 21 | for(Integer i: adj.get(node)){ 22 | if(color[i] == -1){ 23 | color[i] = 1 - color[node]; 24 | 25 | if(!dfsCheck(color, i, adj)) 26 | return false; 27 | } else if(color[i] == color[node]) 28 | return false; 29 | } 30 | 31 | return true; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Graph/DFS_detectCycleInUndirectedGraph.java: -------------------------------------------------------------------------------- 1 | class Node{ 2 | int node; 3 | int parent; 4 | 5 | Node(int node, int parent){ 6 | this.node = node; 7 | this.parent = parent; 8 | } 9 | } 10 | 11 | class Solution 12 | { 13 | //Function to detect cycle in an undirected graph. 14 | public boolean isCycle(int V, ArrayList> adj) 15 | { 16 | boolean vis[] = new boolean[V]; 17 | for(int i=0; i> adj, boolean vis[]){ 29 | vis[node] = true; 30 | 31 | for(Integer i: adj.get(node)){ 32 | if(!vis[i]){ 33 | // I am returning true becasuse once we find a cycle contains in the graph 34 | // then we simply return true; 35 | if(dfsHasCycle(i, node, adj, vis)) 36 | return true; 37 | } 38 | else if(i != par) 39 | return true; 40 | } 41 | 42 | return false; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Graph/DFS_topoSort.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to return list containing vertices in Topological order. 4 | static int[] topoSort(int v, ArrayList> adj) 5 | { 6 | Stack st = new Stack(); 7 | int vis[] = new int[v]; 8 | 9 | for(int i=0; i> adj, Stack st){ 22 | vis[node] = 1; 23 | for(Integer i: adj.get(node)) 24 | if(vis[i] == 0) 25 | findTopoSort(i, vis, adj, st); 26 | 27 | st.push(node); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Graph/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Graph/detectCycleInDirectedGraph.java: -------------------------------------------------------------------------------- 1 | // this question can be solved using topological sorting algo 2 | 3 | 4 | 5 | class Solution { 6 | // Function to detect cycle in a directed graph. 7 | public boolean isCyclic(int v, ArrayList> adj) { 8 | int indegree[] = new int[v]; 9 | // int topo[] = new int[v]; 10 | 11 | // calculating indegrees 12 | for(int i=0; i q = new LinkedList<>(); 18 | // nodes with indegre 0; 19 | for(int i=0; i> adj) 15 | { 16 | boolean vis[] = new boolean[V]; 17 | for(int i=0; i> adj, boolean vis[]){ 29 | Queue queue = new LinkedList<>(); 30 | queue.add(new Node(node, -1)); 31 | vis[node] = true; 32 | 33 | while(!queue.isEmpty()){ 34 | int child = queue.peek().node; 35 | int par = queue.peek().parent; 36 | queue.poll(); 37 | 38 | for(Integer i: adj.get(child)){ 39 | if(!vis[i]){ 40 | vis[i] = true; 41 | queue.add(new Node(i, child)); 42 | } 43 | 44 | else if(i != par) 45 | return true; 46 | } 47 | } 48 | 49 | return false; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Graph/shortestDistanceInUnidirectedGraphWithUnitDistance.java: -------------------------------------------------------------------------------- 1 | private void shortestPath(ArrayList> adj,int N,int src) 2 | { 3 | 4 | int[] dist = new int[N]; 5 | for(int i = 0; i < N; i++) 6 | dist[i] = 1000000000; 7 | 8 | Queue q=new LinkedList<>(); 9 | 10 | 11 | dist[src] = 0; 12 | q.add(src); 13 | 14 | while(q.isEmpty()==false) 15 | { 16 | int node = q.poll(); 17 | 18 | for(int it:adj.get(u)){ 19 | if(dist[node] + 1 < dist[it]){ 20 | dist[it] = dist[node] + 1; 21 | q.add(it); 22 | } 23 | } 24 | } 25 | 26 | for(int i = 0;i < N;i++) { 27 | System.out.print(dist[i] + " "); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Graph/shortestPathInDirectedGraph.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | class GFG 5 | { 6 | public static void main(String[] args) throws IOException 7 | { 8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 9 | int T = Integer.parseInt(br.readLine().trim()); 10 | while(T-->0) 11 | { 12 | String[] s = br.readLine().trim().split(" "); 13 | int V = Integer.parseInt(s[0]); 14 | int E = Integer.parseInt(s[1]); 15 | ArrayList>adj = new ArrayList<>(); 16 | for(int i = 0; i < V; i++) 17 | adj.add(i, new ArrayList()); 18 | for(int i = 0; i < E; i++){ 19 | String[] S = br.readLine().trim().split(" "); 20 | int u = Integer.parseInt(S[0]); 21 | int v = Integer.parseInt(S[1]); 22 | adj.get(u).add(v); 23 | adj.get(v).add(u); 24 | } 25 | Solution obj = new Solution(); 26 | boolean ans = obj.isCycle(V, adj); 27 | if(ans) 28 | System.out.println("1"); 29 | else 30 | System.out.println("0"); 31 | } 32 | } 33 | }// } Driver Code Ends 34 | 35 | class Node { 36 | int first; 37 | int second; 38 | public Node(int first, int second) { 39 | this.first = first; 40 | this.second = second; 41 | } 42 | } 43 | class Solution 44 | { 45 | static boolean checkForCycle(ArrayList> adj, int s, 46 | boolean vis[], int parent[]) 47 | { 48 | Queue q = new LinkedList<>(); //BFS 49 | q.add(new Node(s, -1)); 50 | vis[s] =true; 51 | 52 | while(!q.isEmpty()) 53 | { 54 | int node = q.peek().first; 55 | int par = q.peek().second; 56 | q.remove(); 57 | 58 | for(Integer it: adj.get(node)) 59 | { 60 | if(vis[it]==false) 61 | { 62 | q.add(new Node(it, node)); 63 | vis[it] = true; 64 | } 65 | 66 | else if(par != it) return true; 67 | } 68 | } 69 | 70 | return false; 71 | } 72 | public boolean isCycle(int V, ArrayList> adj) 73 | { 74 | boolean vis[] = new boolean[V]; 75 | Arrays.fill(vis,false); 76 | int parent[] = new int[V]; 77 | Arrays.fill(parent,-1); 78 | 79 | for(int i=0;i> adj) 5 | { 6 | int topo[] = new int[v]; 7 | int indegree[] = new int[v]; 8 | 9 | // calculating indegree 10 | for(int i=0; i q = new LinkedList<>(); 15 | for(int i=0; i> adj) 5 | { 6 | Stack st = new Stack<>(); 7 | int vis[] = new int[v]; 8 | 9 | for(int i=0; i st, ArrayList> adj){ 22 | 23 | vis[node] = 1; 24 | for(Integer it: adj.get(node)){ 25 | if(vis[it] == 0){ 26 | vis[it] = 1; 27 | findTopoSort(it, vis, st, adj); 28 | } 29 | } 30 | 31 | st.push(node); 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Greedy Algo/Nmeetings.java: -------------------------------------------------------------------------------- 1 | package greedyAlgo; 2 | import java.util.*; 3 | public class Nmeetings { 4 | 5 | 6 | public static void main(String arg[]) { 7 | int N = 8; 8 | int S[] = {75250, 50074, 43659, 8931, 11273, 9 | 27545, 50879, 77924}; 10 | int F[] = {112960, 114515, 81825, 93424, 54316, 11 | 35533, 73383, 160252}; 12 | System.out.println(maxMeetings(S, F, N)); 13 | } 14 | 15 | public static int maxMeetings(int start[], int end[], int n) 16 | { 17 | int arr[][] = new int[n][2]; 18 | 19 | for(int i=0; i (a[1] == b[1])? a[0]-b[0] : a[1]-b[1]); 25 | 26 | ArrayList list = new ArrayList<>(); 27 | list.add(arr[0][1]); 28 | int k=0; 29 | for(int i=1; i(){ 6 | public int compare(Item a, Item b){ 7 | double val1 = (double)a.value/a.weight; 8 | double val2 = (double)b.value/b.weight; 9 | 10 | if(val2 > val1) 11 | return 1; 12 | else if(val2 < val1) 13 | return -1; 14 | else 15 | return 0; 16 | } 17 | }); 18 | 19 | 20 | // for(Item i: arr){ 21 | // System.out.println(i.value + " " + i.weight); 22 | // } 23 | 24 | 25 | double ans = 0; 26 | for(Item i: arr){ 27 | int val = i.value; 28 | int wei = i.weight; 29 | 30 | if(w - wei >= 0){ 31 | ans += val; 32 | w -= wei; 33 | } else{ 34 | double fraction = ((double)w/(double)wei); 35 | ans = ans + val * fraction; 36 | break; 37 | } 38 | } 39 | 40 | 41 | return ans; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Greedy Algo/jobSequencing.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | 4 | int[] JobScheduling(Job arr[], int n) 5 | { 6 | Arrays.sort(arr, new Comparator(){ 7 | public int compare(Job a, Job b){ 8 | if(b.profit > a.profit) 9 | return 1; 10 | else if(b.profit < a.profit) 11 | return -1; 12 | else 13 | return 0; 14 | } 15 | }); 16 | 17 | 18 | // 3 1 40 19 | // 4 1 30 20 | // 1 4 20 21 | // 2 1 10 22 | 23 | // array for storing all profits 24 | int ans[] = new int[n]; 25 | int job = 0; 26 | int profit = 0; 27 | 28 | for(int i=0; i=1; j--){ // second loop for back traversing in the ans array; 30 | if(ans[j-1] == 0){ 31 | ans[j-1] = 1; 32 | profit += arr[i].profit; 33 | job++; 34 | break; 35 | } 36 | } 37 | } 38 | 39 | ans = new int[2]; 40 | ans[0] = job; 41 | ans[1] = profit; 42 | 43 | 44 | return ans; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Greedy Algo/minimumPlatform.java: -------------------------------------------------------------------------------- 1 | 2 | // brute force 3 | 4 | int plat_needed = 1, result = 1; 5 | 6 | // run a nested loop to find overlap 7 | for (int i = 0; i < n; i++) { 8 | // minimum platform 9 | plat_needed = 1; 10 | 11 | for (int j = i + 1; j < n; j++) { 12 | // check for overlap 13 | if ((arr[i] >= arr[j] && arr[i] <= dep[j]) || (arr[j] >= arr[i] && arr[j] <= dep[i])) 14 | plat_needed++; 15 | } 16 | 17 | // update result 18 | result = Math.max(result, plat_needed); 19 | } 20 | 21 | return result; 22 | 23 | 24 | 25 | // method 2; 26 | 27 | class Solution 28 | { 29 | //Function to find the minimum number of platforms required at the 30 | //railway station such that no train waits. 31 | static int findPlatform(int arr[], int dep[], int n) 32 | { 33 | Arrays.sort(arr); 34 | Arrays.sort(dep); 35 | 36 | int i = 1, j = 0; 37 | 38 | int platform_needed = 1; 39 | int res = 0; 40 | while(i < n && j < n){ 41 | if(arr[i] <= dep[j]){ 42 | platform_needed++; 43 | i++; 44 | } else if(arr[i] > dep[j]){ 45 | platform_needed--; 46 | j++; 47 | } 48 | 49 | if(platform_needed > res) 50 | res = platform_needed; 51 | } 52 | 53 | return res; 54 | } 55 | 56 | } 57 | 58 | -------------------------------------------------------------------------------- /Greedy Algo/numberOfCoins.java: -------------------------------------------------------------------------------- 1 | 2 | // Greedy approach 3 | 4 | class Solution{ 5 | 6 | public int minCoins(int coins[], int n, int amount) 7 | { 8 | Arrays.sort(coins); 9 | 10 | int res = 0; 11 | for(int i=n-1; i>=0; i--){ 12 | if(coins[i] <= amount){ 13 | int c = amount/coins[i]; 14 | res = res + c; 15 | amount = amount - (c*coins[i]); 16 | } 17 | 18 | if(amount == 0) 19 | break; 20 | } 21 | 22 | return res; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LinkedList/ClonelLinkedListWithNextAndRandomPointer.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // using hashMap 3 | // time o(n) && space o(n) 4 | 5 | 6 | 7 | class Clone { 8 | //Function to clone a linked list with next and random pointer. 9 | Node copyList(Node head) { 10 | if(head == null) 11 | return null; 12 | 13 | HashMap map = new HashMap<>(); 14 | Node currNode = head; 15 | 16 | // creating another list and copying original list's data; 17 | while(currNode != null){ 18 | map.put(currNode, new Node(currNode.data)); 19 | currNode = currNode.next; 20 | } 21 | 22 | // copying and linking next and random pointer 23 | for(Map.Entry entry: map.entrySet()){ 24 | Node node = entry.getValue(); 25 | 26 | node.next = map.get(entry.getKey().next); 27 | node.arb = map.get(entry.getKey().arb); 28 | } 29 | 30 | return map.get(head); 31 | } 32 | } 33 | 34 | 35 | 36 | // method 2 37 | // two pointer approach 38 | // time o(n) && space o(1) 39 | 40 | 41 | class Solution { 42 | public Node copyRandomList(Node head) { 43 | Node iter = head; 44 | Node front = head; 45 | 46 | // connecting copy nodes just after to respective original nodes; 47 | while(iter != null){ 48 | front = iter.next; 49 | Node copyNode = new Node(iter.val); 50 | iter.next = copyNode; 51 | copyNode.next = front; 52 | iter = front; 53 | } 54 | 55 | 56 | // delaing with random pointer 57 | iter = head; 58 | while(iter != null){ 59 | if(iter.random != null) 60 | iter.next.random = iter.random.next; 61 | 62 | iter = iter.next.next; 63 | } 64 | 65 | 66 | // separating copy linked list and orignial linked list; 67 | iter = head; 68 | Node pseudoHead = new Node(0); 69 | Node copy = pseudoHead; 70 | while(iter != null){ 71 | front = iter.next.next; 72 | copy.next = iter.next; 73 | 74 | iter.next = front; 75 | iter = iter.next; 76 | copy = copy.next; 77 | } 78 | 79 | 80 | return pseudoHead.next; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /LinkedList/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LinkedList/addTwoNumbers.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | 3 | class Solution { 4 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 5 | ListNode ans = new ListNode(0); 6 | int carry = 0; 7 | ListNode temp = ans; 8 | 9 | while(l1 != null && l2 != null){ 10 | int sum = l1.val + l2.val + carry; 11 | carry = sum/10; 12 | sum = sum%10; 13 | 14 | ListNode newNode = new ListNode(sum); 15 | temp.next = newNode; 16 | temp = newNode; 17 | 18 | l1 = l1.next; 19 | l2 = l2.next; 20 | } 21 | 22 | int sum = 0; 23 | while(l1 != null){ 24 | sum = l1.val + carry; 25 | carry = sum/10; 26 | sum = sum%10; 27 | 28 | ListNode newNode = new ListNode(sum); 29 | temp.next = newNode; 30 | temp = newNode; 31 | 32 | l1 = l1.next; 33 | } 34 | 35 | sum = 0; 36 | while(l2 != null){ 37 | sum = l2.val + carry; 38 | carry = sum/10; 39 | sum = sum%10; 40 | 41 | ListNode newNode = new ListNode(sum); 42 | temp.next = newNode; 43 | temp = newNode; 44 | 45 | l2 = l2.next; 46 | 47 | } 48 | 49 | if(carry > 0) 50 | temp.next = new ListNode(carry); 51 | 52 | return ans.next; 53 | } 54 | } 55 | 56 | 57 | 58 | // method 2 59 | 60 | class Solution { 61 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 62 | ListNode ans = new ListNode(0); 63 | int carry = 0; 64 | ListNode temp = ans; 65 | 66 | while(l1 != null || l2 != null){ 67 | int x = l1 != null ? l1.val : 0; 68 | int y = l2 != null ? l2.val : 0; 69 | int sum = x + y + carry; 70 | carry = sum/10; 71 | sum = sum%10; 72 | 73 | ListNode newNode = new ListNode(sum); 74 | temp.next = newNode; 75 | temp = newNode; 76 | 77 | if(l1 != null) 78 | l1 = l1.next; 79 | if(l2 != null) 80 | l2 = l2.next; 81 | } 82 | 83 | if(carry > 0) 84 | temp.next = new ListNode(carry); 85 | 86 | return ans.next; 87 | } 88 | } 89 | 90 | 91 | -------------------------------------------------------------------------------- /LinkedList/deleteNodeInLL.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void deleteNode(ListNode node) { 3 | node.val = node.next.val; 4 | node.next = node.next.next; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /LinkedList/detectLoopInLL.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // used hashing 3 | // time o(n) && space o(n) 4 | 5 | public class Solution { 6 | public boolean hasCycle(ListNode head) { 7 | HashSet hs = new HashSet<>(); 8 | 9 | while(head!= null){ 10 | if(hs.contains(null)) 11 | break; 12 | else if(hs.contains(head)) 13 | return true; 14 | else 15 | hs.add(head); 16 | 17 | head = head.next; 18 | } 19 | 20 | return false; 21 | } 22 | } 23 | 24 | 25 | // method 2 26 | // using two pointers 27 | // time o(n) && space o(1) 28 | 29 | 30 | public class Solution { 31 | public boolean hasCycle(ListNode head) { 32 | if(head == null || head.next == null) 33 | return false; 34 | 35 | ListNode slow = head; 36 | ListNode fast = head; 37 | 38 | while(fast.next != null && fast.next.next != null){ 39 | slow = slow.next; 40 | fast = fast.next.next; 41 | 42 | if(slow == fast) 43 | return true; 44 | } 45 | 46 | return false; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /LinkedList/findStartingPointOfTheCycle.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // used hashing 3 | // time o(n) && space o(n) 4 | 5 | 6 | public class Solution { 7 | public ListNode detectCycle(ListNode head) { 8 | HashSet hs = new HashSet<>(); 9 | 10 | while(head != null){ 11 | if(hs.contains(head)) 12 | return head; 13 | 14 | hs.add(head); 15 | head = head.next; 16 | } 17 | return null; 18 | } 19 | } 20 | 21 | 22 | // method 2 23 | // using two pointers 24 | // time 0(n ) && space o(1) 25 | 26 | public class Solution { 27 | public ListNode detectCycle(ListNode head) { 28 | ListNode slow = head; 29 | ListNode fast = head; 30 | ListNode entry = head; 31 | 32 | while(fast != null && fast.next != null){ 33 | slow = slow.next; 34 | fast = fast.next.next; 35 | 36 | if(fast == slow){ 37 | while(slow != entry){ 38 | slow = slow.next; 39 | entry = entry.next; 40 | } 41 | return entry; 42 | } 43 | } 44 | 45 | return null; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /LinkedList/flatteningALL.java: -------------------------------------------------------------------------------- 1 | class GfG 2 | { 3 | Node flatten(Node root) 4 | { 5 | // base case - when root is null or when we are standing on the last pointer 6 | if(root == null || root.next == null) 7 | return root; 8 | 9 | // traversing in order to move to last pointer i.e. moving right 10 | root.next = flatten(root.next); 11 | 12 | // merging 13 | root = mergeTwoLL(root, root.next); 14 | 15 | 16 | return root; 17 | } 18 | 19 | private Node mergeTwoLL(Node a, Node b){ 20 | Node temp = new Node(0); 21 | Node res = temp; 22 | 23 | while(a != null && b != null){ 24 | if(a.data < b.data){ 25 | temp.bottom = a; 26 | temp = a; 27 | a = a.bottom; 28 | } else{ 29 | temp.bottom = b; 30 | temp = b; 31 | b = b.bottom; 32 | } 33 | } 34 | 35 | if(a != null) 36 | temp.bottom = a; 37 | 38 | if(b != null) 39 | temp.bottom = b; 40 | 41 | return res.bottom; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /LinkedList/lengthOfLL.java: -------------------------------------------------------------------------------- 1 | lass Solution 2 | { 3 | 4 | static int countNodesinLoop(Node head) 5 | { 6 | Node slow = head, fast = head; 7 | while(fast!= null && fast.next != null){ 8 | slow = slow.next; 9 | fast = fast.next.next; 10 | if(slow == fast) 11 | break; 12 | } 13 | 14 | if(fast == null || fast.next == null) 15 | return 0; 16 | 17 | Node temp = slow; 18 | int len = 1; 19 | while(temp != null && temp.next != slow){ 20 | temp = temp.next; 21 | len++; 22 | } 23 | return len; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LinkedList/mergeTwoSortedLL.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 | ListNode tail = null, head = null; 4 | 5 | if(l1 == null) return l2; 6 | if(l2 == null) return l1; 7 | 8 | 9 | while(l1 != null && l2 != null){ 10 | if(l1.val <= l2.val){ 11 | if(head == null){ 12 | head = l1; 13 | tail = l1; 14 | l1 = l1.next; 15 | } else{ 16 | tail.next = l1; 17 | tail = l1; 18 | l1 = l1.next; 19 | } 20 | } 21 | else { 22 | if(head == null){ 23 | head = l2; 24 | tail = l2; 25 | l2 = l2.next; 26 | } else{ 27 | tail.next = l2; 28 | tail = l2; 29 | l2 = l2.next; 30 | } 31 | } 32 | } 33 | 34 | if(l1 != null) 35 | tail.next = l1; 36 | if(l2 != null) 37 | tail.next = l2; 38 | 39 | return head; 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /LinkedList/middleOfLinkedList.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode middleNode(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | 6 | while(fast != null && fast.next != null){ 7 | slow = slow.next; 8 | fast = fast.next.next; 9 | } 10 | 11 | return slow; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /LinkedList/nthNodeFromEndOfLL.java: -------------------------------------------------------------------------------- 1 | 2 | class GfG 3 | { 4 | 5 | int getNthFromLast(Node head, int n) 6 | { 7 | int len = length(head); 8 | if(len < n) 9 | return -1; 10 | 11 | n = len-n; 12 | 13 | Node temp = head; 14 | for(int i=0; i#0.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList NBitBinary(int n) { 3 | ArrayList list = new ArrayList<>(); 4 | helper(n, "", 0, 0, list); 5 | 6 | return list; 7 | } 8 | 9 | private static void helper(int n , String op, int ones, int zeroes, ArrayList list){ 10 | if(n == 0){ 11 | list.add(op); 12 | return; 13 | } 14 | 15 | 16 | if(ones == zeroes){ 17 | helper(n-1, op+"1", ones+1, zeroes, list); 18 | } else if(ones > zeroes){ 19 | helper(n-1, op+"1", ones+1, zeroes, list); 20 | helper(n-1, op+"0", ones, zeroes+1, list); 21 | } 22 | 23 | return; 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /RECURSION/Good_question_KthSymbolInGrammar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthGrammar(int N, int K) { 3 | // base case which is given in the question; 4 | if(N == 1 && K == 1) 5 | return 0; 6 | 7 | /* 8 | length of the grammer depends on the value of N, it is of the order 2^N-1 9 | so we are calculating the mid of the grammar; 10 | */ 11 | int mid = (int)Math.pow(2, N-1)/2; 12 | /* 13 | suppose N=4, K=3 then grammar would be 14 | 0 15 | 0 1 16 | 0 1 1 0 17 | 0 1 1 0 1 0 0 1 18 | and the answer would be 1; 19 | 20 | it is to be noted the first half of grammar is exactly similar to the grammar of N-1 21 | 0 1 1 0 N=3 22 | 0 1 1 0 first half of N=4 23 | and the grammar of other half is the first compliment to the grammar of N-1. 24 | 0 1 1 0 N=3 25 | 1 0 0 1 first complement of N=3 26 | 27 | it means if the value of K lies in the first half i.e. K<=mid then we simply return the value; 28 | if K>mid then we pass value of K as K-mid in order to map with the corresponding index of N-1 grammer 29 | and return the complement value which we get through recursive call. 30 | */ 31 | if(K<=mid) 32 | return kthGrammar(N-1, K); 33 | else{ 34 | int k = kthGrammar(N-1, K-mid); 35 | return k==1?0:1; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /RECURSION/Good_question_generateBalancedParanthesis.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public List AllParenthesis(int n) 4 | { 5 | int open = n; 6 | int close = n; 7 | ArrayList list = new ArrayList<>(); 8 | generateParenthesis(open, close, "", list); 9 | 10 | return list; 11 | } 12 | 13 | private static void generateParenthesis(int open, int close, String op, ArrayList list){ 14 | if(open == 0 && close == 0){ 15 | list.add(op); 16 | return; 17 | } 18 | 19 | if(open == close) 20 | generateParenthesis(open-1, close, op+'(', list); 21 | else if(open == 0) 22 | generateParenthesis(open, close-1, op+')', list); 23 | else if(open < close){ 24 | generateParenthesis(open-1, close, op+'(', list); 25 | generateParenthesis(open, close-1, op+')', list); 26 | } 27 | 28 | return; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /RECURSION/M2_printAllPermutations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> permute(int[] nums) { 3 | List> ans = new ArrayList<>(); 4 | solve(0, nums, ans); 5 | 6 | return ans; 7 | } 8 | 9 | private void solve(int index, int arr[], List> ans){ 10 | if(index == arr.length){ 11 | List list = new ArrayList<>(); 12 | for(int i: arr) 13 | list.add(i); 14 | 15 | ans.add(new ArrayList<>(list)); 16 | return; 17 | } 18 | 19 | 20 | for(int i=index; i> permute(int[] nums) { 5 | List> ans = new ArrayList<>(); 6 | List list = new ArrayList<>(); 7 | boolean map[] = new boolean[nums.length]; 8 | 9 | int n = nums.length; 10 | 11 | getAllPermuatation(ans, nums, list, map); 12 | return ans; 13 | } 14 | 15 | 16 | private void getAllPermuatation(List> ans, int nums[], List list, boolean map[]){ 17 | // base case 18 | if(list.size() == map.length){ 19 | ans.add(new ArrayList<>(list)); 20 | return; 21 | } 22 | 23 | // traversing and generating every permutations; 24 | int n = nums.length; 25 | for(int i=0; i> combinationSum(int[] arr, int target) { 3 | List> output = new ArrayList<>(); 4 | List list = new ArrayList<>(); 5 | 6 | helper(arr, target, 0, list, output); 7 | return output; 8 | } 9 | 10 | private void helper(int arr[], int target, int sI, List list, List> output){ 11 | if(target == 0){ 12 | output.add(new ArrayList(list)); 13 | return; 14 | } 15 | else if(arr.length == sI) 16 | return; 17 | 18 | 19 | // pick the candidate 20 | if(arr[sI] <= target){ 21 | list.add(arr[sI]); 22 | helper(arr, target-arr[sI], sI, list, output); 23 | list.remove(list.size()-1); 24 | } 25 | // don't pick the candidate 26 | helper(arr, target, sI+1, list, output); 27 | 28 | return; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /RECURSION/combinationsSumSDE.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> combinationSum2(int[] arr, int target) { 3 | Arrays.sort(arr); 4 | Set> set = new HashSet<>(); 5 | List list = new ArrayList<>(); 6 | 7 | helper(arr, target, 0, set, list); 8 | return new ArrayList<>(set); 9 | } 10 | 11 | private void helper(int arr[], int target, int sI, Set> set, List list){ 12 | if(target == 0){ 13 | set.add(new ArrayList(list)); 14 | return; 15 | } 16 | else if(sI == arr.length) 17 | return; 18 | 19 | // include an candidate 20 | if(arr[sI] <= target){ 21 | list.add(arr[sI]); 22 | helper(arr, target-arr[sI], sI+1, set, list); 23 | list.remove(list.size()-1); 24 | } 25 | 26 | // not include an candidate 27 | helper(arr, target, sI+1, set, list); 28 | 29 | return; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /RECURSION/deleteMiddleElementInStack.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public void deleteMid(Stacks,int size){ 4 | if(size == 0){ 5 | return; 6 | } 7 | 8 | int mid = size/2 + 1; 9 | 10 | solve(s, mid); 11 | return; 12 | } 13 | 14 | private void solve(Stack s, int k){ 15 | if(k == 1){ 16 | s.pop(); 17 | return; 18 | } 19 | 20 | int val = s.pop(); 21 | solve(s, k-1); 22 | s.push(val); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /RECURSION/generateAllSubsetsOfString.java: -------------------------------------------------------------------------------- 1 | public class Main 2 | { 3 | public static void main(String[] args) { 4 | printSubsets("abc", ""); 5 | } 6 | 7 | private static void printSubsets(String str, String op){ 8 | if(str.length() == 0){ 9 | System.out.println(op); 10 | return; 11 | } 12 | 13 | String op1 = op; 14 | String op2 = op + str.charAt(0); 15 | str = str.substring(1); 16 | 17 | printSubsets(str, op1); 18 | printSubsets(str, op2); 19 | 20 | return; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /RECURSION/letterCasePermutations.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List letterCasePermutation(String str) { 3 | ArrayList list = new ArrayList(); 4 | caseCombinations(str, "", list); 5 | 6 | return list; 7 | } 8 | 9 | private void caseCombinations(String str, String op, ArrayList list){ 10 | if(str.length() == 0){ 11 | list.add(op); 12 | return; 13 | } 14 | 15 | char ch = str.charAt(0); 16 | 17 | if(Character.isDigit(ch)) 18 | caseCombinations(str.substring(1), op+ch, list); 19 | else{ 20 | caseCombinations(str.substring(1), op+Character.toUpperCase(ch), list); 21 | caseCombinations(str.substring(1), op+Character.toLowerCase(ch), list); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /RECURSION/permutationWithSpaces.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | 4 | ArrayList permutation(String str){ 5 | ArrayList list = new ArrayList<>(); 6 | helper(str.substring(1), str.charAt(0)+"", list); 7 | 8 | return list; 9 | } 10 | 11 | private static void helper(String str, String op, ArrayList list){ 12 | if(str.length() == 0){ 13 | list.add(op); 14 | return; 15 | } 16 | 17 | String op1 = op + " " + str.charAt(0); 18 | String op2 = op + str.charAt(0); 19 | 20 | helper(str.substring(1), op1, list); 21 | helper(str.substring(1), op2, list); 22 | 23 | return; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /RECURSION/sortArrayUsingRecursion.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int[] sortArr(int[] arr, int n) 4 | { 5 | sort(arr, n); 6 | return arr; 7 | } 8 | 9 | private static void sort(int arr[], int n){ 10 | if(n == 1) 11 | return; 12 | 13 | int val = arr[n-1]; 14 | 15 | sort(arr, n-1); 16 | insert(arr, val, n-1); 17 | } 18 | 19 | private static void insert(int arr[], int val, int n){ 20 | if(n == 0 || arr[n-1] <= val){ 21 | arr[n] = val; 22 | return; 23 | } 24 | 25 | int temp = arr[n-1]; 26 | 27 | insert(arr, val, n-1); 28 | 29 | arr[n] = temp; 30 | return; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /RECURSION/sortStackUsingRecursion.java: -------------------------------------------------------------------------------- 1 | class GfG{ 2 | public Stack sort(Stack s) 3 | { 4 | if(s.size() == 1) 5 | return s; 6 | 7 | int val = s.pop(); 8 | s = sort(s); 9 | s = insert(s, val); 10 | 11 | return s; 12 | } 13 | 14 | 15 | 16 | 17 | private static Stack insert(Stack s, int val){ 18 | if(s.isEmpty() || s.peek() <= val){ 19 | s.push(val); 20 | return s; 21 | } 22 | 23 | int element = s.pop(); 24 | s = insert(s, val); 25 | s.push(element); 26 | 27 | return s; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Sliding Window/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Sliding Window/fixed size window/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Sliding Window/fixed size window/firstNegativeIntegerWindowOfSizeK.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // time o(n2), space o(1) 3 | 4 | 5 | class Compute { 6 | 7 | public long[] printFirstNegativeInteger(long arr[], int n, int k) 8 | { 9 | long ans[] = new long[n-k+1]; 10 | 11 | int t=0; 12 | for(int i=0; i queue = new LinkedList<>(); 38 | 39 | int i=0, j=0, t=0; 40 | long nonNeg = 0; 41 | while(j Arr,int N){ 6 | 7 | int max = Integer.MIN_VALUE; 8 | for(int i=0; i arr,int n){ 25 | 26 | int max = Integer.MIN_VALUE; 27 | int sum = 0; 28 | int i=0, j=0; 29 | while(j n-1 checks 8 | // 2nd iteration -> n-2 checks 9 | // 3rd iteration -> n-3 checks 10 | // so on.... 11 | // ith iteration -> n-i checks 12 | public static void bubbleSort(int arr[], int n) 13 | { 14 | int counter = 1; 15 | while(counter < n){ 16 | for(int i=0; i arr[i+1]) 18 | swap(arr, i, i+1); 19 | } 20 | counter++; 21 | } 22 | } 23 | 24 | private static void swap(int arr[], int i, int j){ 25 | int temp = arr[i]; 26 | arr[i] = arr[j]; 27 | arr[j] = temp; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Sorting/COUNT_SORT.java: -------------------------------------------------------------------------------- 1 | // Time o(n) 2 | // space o(max(arr)) -> o(n) 3 | 4 | class Solution { 5 | public int[] sortArray(int[] arr) { 6 | int n = arr.length; 7 | int max = Integer.MIN_VALUE; 8 | int min = Integer.MAX_VALUE; 9 | 10 | for(int i: arr){ 11 | max = Math.max(max, i); 12 | min = Math.min(min, i); 13 | } 14 | 15 | int range = max - min + 1; 16 | int countArray[] = new int[range]; 17 | int output[] = new int[n]; 18 | 19 | // find the count of every element from the original array 20 | /* 21 | Note: 22 | Here I am subtracting with min, in order to deal with all -ve values 23 | */ 24 | for(int i: arr) 25 | countArray[i-min]++; 26 | 27 | 28 | // modify the countArray by adding current index value with its previous index vlaues 29 | for(int i=1; i=0; i--){ 35 | // int val = countArray[arr[i]-min]-1; 36 | output[countArray[arr[i]-min]-1] = arr[i]; 37 | countArray[arr[i]-min]--; 38 | } 39 | 40 | 41 | // copying output array to arr 42 | for(int i=0; i=0 && arr[j] > currentElement){ 13 | arr[j+1] = arr[j]; 14 | j--; 15 | } 16 | arr[j+1] = currentElement; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Sorting/MERGE_SORT.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | void merge(int[] nums, int start, int mi, int end) 4 | { 5 | int lp = start; 6 | int rp = mi + 1; 7 | int[] buffer = new int[end-start+1]; 8 | int t = 0; //buffer pointer 9 | 10 | while (lp <= mi && rp <= end){ 11 | if (nums[lp] < nums[rp]){ 12 | buffer[t++] = nums[lp++]; 13 | }else{ 14 | buffer[t++] = nums[rp++]; 15 | } 16 | } 17 | 18 | while (lp <= mi) buffer[t++] = nums[lp++]; 19 | while (rp <= end) buffer[t++] = nums[rp++]; 20 | //Now copy sorted buffer into original array 21 | for (int i = start; i <= end; i++){ 22 | nums[i] = buffer[i-start]; 23 | } 24 | 25 | } 26 | void mergeSort(int[] nums, int start, int end) 27 | { 28 | if (start >= end) return; //Already sorted. 29 | 30 | int mi = start + (end - start)/ 2; 31 | mergeSort(nums, start, mi); 32 | mergeSort(nums, mi+1, end); 33 | merge(nums, start,mi, end); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Sorting/QUICK_SORT.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static void quickSort(int arr[], int low, int high) 4 | { 5 | if(low < high){ 6 | int pit = partition(arr, low, high); 7 | quickSort(arr, low, pit-1); 8 | quickSort(arr, pit+1, high); 9 | } 10 | } 11 | static int partition(int arr[], int low, int high) 12 | { 13 | int i = low-1; 14 | int pivot = arr[high]; 15 | for(int j=low; j<=high; j++){ 16 | 17 | // swap(arr[i], arr[j]) 18 | if(arr[j] < pivot){ 19 | i++; 20 | swap(arr, i, j); 21 | } 22 | } 23 | 24 | // swap(arr[high], swap[i+1]) 25 | swap(arr, high, i+1); // Here the significance of i, last number which is smaller to pivot 26 | 27 | return i+1; 28 | } 29 | 30 | private static void swap(int arr[], int a, int b){ 31 | int temp = arr[a]; 32 | arr[a] = arr[b]; 33 | arr[b] = temp; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Sorting/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Sorting/SELECTION_SORT.java: -------------------------------------------------------------------------------- 1 | // Find the min element from the sorted array and swap it with the element at the 2 | // begining of the array 3 | 4 | class Solution 5 | { 6 | void selectionSort(int arr[], int n) 7 | { 8 | for(int i=0; i arr[i-1]) 7 | swap(arr, i, i-1); 8 | 9 | if(i <= n-2 && arr[i] > arr[i+1]) 10 | swap(arr, i, i+1); 11 | } 12 | 13 | } 14 | 15 | private static void swap(int arr[], int i, int j){ 16 | int temp = arr[i]; 17 | arr[i] = arr[j]; 18 | arr[j] = temp; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Sorting/countInversions.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // brute force 3 | // time o(n2) and space o(1) 4 | 5 | 6 | class Solution 7 | { 8 | static long inversionCount(long arr[], long n) 9 | { 10 | long ans = 0; 11 | for(int i=0; i arr[j]) 14 | ans++; 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | } 21 | 22 | 23 | 24 | // method 2 25 | // using merge sort idea 26 | // time o(nlogn) and space o(n) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Sorting/intersectionOfTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | // brute force 2 | // time o(n2) and space o(1) 3 | 4 | class Solution { 5 | public int[] intersection(int[] nums1, int[] nums2) { 6 | int n1 = nums1.length; 7 | int n2 = nums2.length; 8 | 9 | ArrayList list = new ArrayList<>(); 10 | 11 | for(int i=0; i0 && nums1[i] == nums1[i-1]) 13 | continue; 14 | for(int j=0; j0 && nums2[j] == nums2[j-1]) 16 | continue; 17 | 18 | if(nums1[i] == nums2[j]){ 19 | list.add(nums2[j]); 20 | // break; 21 | } 22 | } 23 | } 24 | 25 | int n = list.size(); 26 | int ans[] = new int[n]; 27 | for(int i=0; i map = new HashMap<>(); 43 | 44 | ArrayList output = new ArrayList<>(); 45 | 46 | for(int i: nums1) 47 | map.put(i, map.getOrDefault(i, 0) + 1); 48 | 49 | for(int i: nums2){ 50 | if(map.containsKey(i)){ 51 | output.add(i); 52 | map.remove(i); 53 | } 54 | } 55 | 56 | int l = output.size(); 57 | int ans[] = new int[l]; 58 | for(int i=0; i list = new ArrayList<>(); 75 | 76 | int i = 0, j = 0; 77 | while(i0 && nums1[i] == nums1[i-1]){i++; continue;} 79 | 80 | if(nums1[i] < nums2[j]) 81 | i++; 82 | else if(nums1[i] > nums2[j]) 83 | j++; 84 | else{ 85 | list.add(nums1[i]); 86 | i++; 87 | j++; 88 | } 89 | } 90 | 91 | int n = list.size(); 92 | int ans[] = new int[n]; 93 | for(i=0; i map = new HashMap<>(); 38 | for(int i=0; i0 && a[i] == a[i-1]) {i++; continue;} 78 | if(j>0 && b[j] == b[j-1]) {j++; continue;} 79 | 80 | if(a[i] < b[j]){ 81 | i++; 82 | count++; 83 | } else if(a[i] > b[j]){ 84 | j++; 85 | count++; 86 | } else{ 87 | i++; 88 | j++; 89 | count++; 90 | } 91 | } 92 | 93 | while(i < n){ 94 | if(i == 0 || a[i] != a[i-1]) 95 | count++; 96 | i++; 97 | } 98 | 99 | while(j < m){ 100 | if(j == 0 || b[j] != b[j-1]) 101 | count++; 102 | j++; 103 | } 104 | 105 | 106 | 107 | return count; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /Stack/BFS.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public ArrayList bfsOfGraph(int V,ArrayList> adj) 4 | { 5 | ArrayList bfs = new ArrayList<>(); 6 | boolean vis[] = new boolean[V+1]; 7 | 8 | for(int i=0; i> adj, ArrayList bfs, int sI){ 18 | Queue queue = new LinkedList<>(); 19 | 20 | queue.add(sI); 21 | vis[sI] = true; 22 | 23 | while(!queue.isEmpty()){ 24 | Integer node = queue.poll(); 25 | bfs.add(node); 26 | 27 | // traversing adjacent nodes 28 | for(Integer i: adj.get(node)) { 29 | if(!vis[i]){ 30 | queue.add(i); 31 | vis[i] = true; 32 | } 33 | } 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Stack/QueueUsingArray.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | public class QueueUsingArray { 4 | private int data[]; 5 | private int front; 6 | private int rear; 7 | private int size; 8 | 9 | QueueUsingArray() { 10 | data = new int[10]; 11 | front = -1; 12 | rear = -1; 13 | size = 0; 14 | } 15 | 16 | QueueUsingArray(int capacity){ 17 | data = new int[capacity]; 18 | front = -1; 19 | rear = -1; 20 | size = 0; 21 | } 22 | 23 | public int size() { 24 | return size; 25 | } 26 | 27 | public boolean isEmpty() { 28 | return size == 0; 29 | } 30 | public int front() { 31 | if(size == 0) 32 | return -1; 33 | return data[front]; 34 | } 35 | 36 | public int rear() { 37 | if(size() == 0) 38 | return -1; 39 | 40 | return data[rear]; 41 | } 42 | 43 | public void enqueue(int val) { 44 | if(size == 0) 45 | front = 0; 46 | 47 | rear = (rear+1)%data.length; 48 | size++; 49 | data[rear] = val; 50 | } 51 | 52 | public int dequeue() { 53 | if(size == 0) 54 | return -1; 55 | 56 | int temp = data[front]; 57 | 58 | front = (front+1)%data.length; 59 | size--; 60 | if(size == 0) { 61 | rear = -1; 62 | front = -1; 63 | } 64 | 65 | return temp; 66 | } 67 | } 68 | 69 | class QueueUse{ 70 | public static void main(String args[]) { 71 | QueueUsingArray q = new QueueUsingArray(); 72 | for(int i=0; i<10; i++) 73 | q.enqueue(i); 74 | 75 | while(!q.isEmpty()) 76 | System.out.println(q.dequeue()); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Stack/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Stack/StackUseArray.java: -------------------------------------------------------------------------------- 1 | package stacks; 2 | 3 | public class StackUseArray { 4 | private int data[]; 5 | private int top; 6 | 7 | public StackUseArray() { 8 | data = new int[10]; 9 | top = -1; 10 | } 11 | 12 | public StackUseArray(int capacity) { 13 | data = new int[capacity]; 14 | top = -1; 15 | } 16 | 17 | public int size() { 18 | return top + 1; 19 | } 20 | 21 | public int top() { 22 | if(top == -1) 23 | return -1; 24 | 25 | return data[top]; 26 | } 27 | 28 | public boolean isEmpty() { 29 | return top == -1; 30 | } 31 | 32 | public int pop() { 33 | if(size() == 0) 34 | return -1; 35 | 36 | return data[top--]; 37 | } 38 | 39 | public void push(int val) { 40 | if(size() == data.length) 41 | doubleSize(); 42 | 43 | data[++top] = val; 44 | } 45 | 46 | private void doubleSize() { 47 | int temp[] = data; 48 | data = new int[2*data.length]; 49 | for(int i=0; is,int size){ 4 | if(size == 0){ 5 | return; 6 | } 7 | 8 | int mid = size/2 + 1; 9 | 10 | solve(s, mid); 11 | return; 12 | } 13 | 14 | private void solve(Stack s, int k){ 15 | if(k == 1){ 16 | s.pop(); 17 | return; 18 | } 19 | 20 | int val = s.pop(); 21 | solve(s, k-1); 22 | s.push(val); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Stack/implementStackUsingQueue.java: -------------------------------------------------------------------------------- 1 | // method 1 (Using 2 queues) 2 | // push O(1) && pop O(n), Space o(n). for extra queue; 3 | 4 | class MyStack { 5 | 6 | private Queue queue = new LinkedList<>(); 7 | private Queue tempQueue = new LinkedList<>(); 8 | private int top; 9 | 10 | public void push(int x) { 11 | queue.add(x); 12 | top = x; 13 | } 14 | 15 | public int top() { 16 | return top; 17 | } 18 | 19 | public int pop() { 20 | while(queue.size() != 1){ 21 | top = queue.poll(); 22 | tempQueue.add(top); 23 | } 24 | int ans = queue.poll(); 25 | Queue temp = queue; 26 | queue = tempQueue; 27 | tempQueue = temp; 28 | 29 | return ans; 30 | } 31 | 32 | public boolean empty() { 33 | return queue.size() == 0; 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | // method 2 (Using 1 queue) 41 | // Pop O(1), push O(n) && O(1), Space o(1) 42 | 43 | 44 | 45 | class Queues 46 | { 47 | Queue q1 = new LinkedList(); 48 | 49 | 50 | void push(int a) 51 | { 52 | q1.add(a); 53 | int size = q1.size(); 54 | 55 | while(size != 1){ 56 | q1.add(q1.poll()); 57 | size--; 58 | } 59 | } 60 | 61 | 62 | int pop() 63 | { 64 | if(q1.size() == 0) 65 | return -1; 66 | return q1.remove(); 67 | } 68 | 69 | } 70 | 71 | 72 | -------------------------------------------------------------------------------- /Stack/minStack.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // time push and pop o(1) && space o(n) 3 | 4 | class GfG{ 5 | Stack min = new Stack<>(); 6 | public void push(int a,Stack s) 7 | { 8 | if(min.isEmpty()) 9 | min.add(a); 10 | 11 | if(min.peek() > a) 12 | min.add(a); 13 | 14 | s.add(a); 15 | } 16 | public int pop(Stack s) 17 | { 18 | if(s.peek() == min.peek()) 19 | s.pop(); 20 | 21 | return s.pop(); 22 | } 23 | public int min(Stack s) 24 | { 25 | return min.peek(); 26 | } 27 | public boolean isFull(Stacks, int n) 28 | { 29 | return s.size() == n; 30 | } 31 | public boolean isEmpty(Stacks) 32 | { 33 | return s.isEmpty(); 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | // method 2 41 | // push and pop time O(1) && space O(1) 42 | 43 | 44 | class GfG{ 45 | 46 | private int min = Integer.MAX_VALUE; 47 | public void push(int a,Stack s) 48 | { 49 | if(s.size() == 0){ 50 | s.add(a); 51 | min = a; 52 | }else{ 53 | if(min <= a) 54 | s.add(a); 55 | else{ 56 | s.push(2*a-min); 57 | min = a; 58 | } 59 | } 60 | } 61 | public int pop(Stack s) 62 | { 63 | if(s.size() == 0) return -1; 64 | 65 | if(s.peek() >= min){ 66 | return s.pop(); 67 | }else{ 68 | min = 2*min - s.peek(); 69 | return s.pop(); 70 | } 71 | } 72 | public int min(Stack s) 73 | { 74 | return min; 75 | } 76 | public boolean isFull(Stacks, int n) 77 | { 78 | return s.size() == n; 79 | } 80 | public boolean isEmpty(Stacks) 81 | { 82 | return s.isEmpty(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Stack/nextGreaterElement.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // brute force 3 | // time o(n2) && space o(1) 4 | 5 | class Solution 6 | { 7 | public static long[] nextLargerElement(long[] arr, int n) 8 | { 9 | long ans[] = new long[n]; 10 | 11 | for(int i=0; i st = new Stack<>(); 46 | 47 | for(int i = n-1; i >= 0 ; i--){ 48 | if(st.size() == 0) 49 | ans[k--] = -1; 50 | 51 | else if(st.size() > 0 && st.peek() > arr[i]) 52 | ans[k--] = st.peek(); 53 | 54 | else if(st.size() > 0 && st.peek() <= arr[i]){ 55 | while(st.size() > 0 && st.peek() <= arr[i]){ 56 | st.pop(); 57 | } 58 | 59 | if(st.size() == 0) 60 | ans[k--] = -1; 61 | else 62 | ans[k--] = st.peek(); 63 | } 64 | 65 | st.push(arr[i]); 66 | } 67 | 68 | return ans; 69 | 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Stack/nextSmallerElement.java: -------------------------------------------------------------------------------- 1 | // VARIANT OF NEXT SMALLER ELEMENT 2 | // LEETCODE 1475 3 | 4 | 5 | 6 | // method 1 7 | // brute force 8 | // time o(n2) && space o(1) 9 | 10 | class Solution { 11 | public int[] finalPrices(int[] arr) { 12 | int n = arr.length; 13 | int ans[] = new int[n]; 14 | int j = 0; 15 | for(int i=0; i= arr[j]) 21 | ans[i] = arr[i] - arr[j]; 22 | else 23 | ans[i] = arr[i]; 24 | } 25 | 26 | return ans; 27 | } 28 | } 29 | 30 | 31 | 32 | 33 | 34 | // method 2 35 | // using stack 36 | // time o(n) && space o(n) 37 | 38 | class Solution { 39 | public int[] finalPrices(int[] arr) { 40 | int n = arr.length; 41 | int ans[] = new int[n]; 42 | Stack st = new Stack<>(); 43 | int pseudoValue = 0; 44 | 45 | int k = n-1; 46 | for(int i=n-1; i>=0; i--){ 47 | if(st.size() == 0) 48 | ans[k--] = arr[i]; 49 | 50 | else if(st.size() > 0 && st.peek() < arr[i]) 51 | ans[k--] = arr[i] - st.peek(); 52 | else if(st.size() > 0 && st.peek() >= arr[i]){ 53 | while(st.size() > 0 && st.peek() > arr[i]) 54 | st.pop(); 55 | 56 | if(st.size() == 0) 57 | ans[k--] = arr[i]; 58 | else 59 | ans[k--] = arr[i] - st.peek(); 60 | } 61 | st.add(arr[i]); 62 | } 63 | 64 | return ans; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Stack/queueUsingStack.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // push O(1) , pop O(n) && space O(n) 3 | 4 | class StackQueue 5 | { 6 | Stack s1 = new Stack(); 7 | Stack s2 = new Stack(); 8 | 9 | 10 | void Push(int x) 11 | { 12 | s1.push(x); 13 | } 14 | 15 | 16 | int Pop() 17 | { 18 | if(s1.size() == 0) 19 | return -1; 20 | 21 | while(s1.size() != 0) 22 | s2.add(s1.pop()); 23 | 24 | int ans = s2.pop(); 25 | 26 | while(s2.size() != 0) 27 | s1.add(s2.pop()); 28 | 29 | return ans; 30 | } 31 | } 32 | 33 | 34 | 35 | // methdo 2 36 | // (Two Stacks) Push - O(n)O(n) per operation, Pop - O(1)O(1) per operation. 37 | 38 | class MyQueue { 39 | 40 | Stack s1 = new Stack<>(); 41 | Stack s2 = new Stack<>(); 42 | private int front; 43 | 44 | public void push(int x) { 45 | if(s1.isEmpty()) 46 | front = x; 47 | 48 | while(!s1.isEmpty()) 49 | s2.add(s1.pop()); 50 | 51 | s1.add(x); 52 | 53 | while(!s2.isEmpty()) 54 | s1.add(s2.pop()); 55 | } 56 | 57 | 58 | public int pop() { 59 | return s1.pop(); 60 | } 61 | 62 | 63 | public int peek() { 64 | return s1.peek(); 65 | } 66 | 67 | 68 | public boolean empty() { 69 | return s1.size() == 0; 70 | } 71 | } 72 | 73 | 74 | // method 3 75 | // (Two Stacks) Push - O(1)O(1) per operation, Pop - Amortized O(1)O(1) per operation. 76 | 77 | class MyQueue { 78 | 79 | Stack s1 = new Stack<>(); 80 | Stack s2 = new Stack<>(); 81 | private int front; 82 | 83 | public void push(int x) { 84 | if(s1.size() == 0) 85 | front = x; 86 | s1.add(x); 87 | } 88 | 89 | public int pop() { 90 | if(s2.isEmpty()){ 91 | while(!s1.isEmpty()) 92 | s2.add(s1.pop()); 93 | } 94 | 95 | return s2.pop(); 96 | } 97 | 98 | 99 | public int peek() { 100 | if(s2.size() != 0) 101 | return s2.peek(); 102 | return front; 103 | } 104 | 105 | 106 | public boolean empty() { 107 | return s1.isEmpty() && s2.isEmpty(); 108 | } 109 | } 110 | 111 | -------------------------------------------------------------------------------- /Stack/rainWaterTrapping.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] arr) { 3 | int n = arr.length; 4 | if(n == 0) return 0; 5 | 6 | int l = 0, r = n-1; 7 | int leftMax = 0, rightMax = 0; 8 | int ans = 0; 9 | 10 | while(l <= r){ 11 | if(arr[l] <= arr[r]){ 12 | if(arr[l] >= leftMax) 13 | leftMax = arr[l]; 14 | else 15 | ans += leftMax - arr[l]; 16 | 17 | l++; 18 | } 19 | else{ 20 | if(arr[r] >= rightMax) 21 | rightMax = arr[r]; 22 | else 23 | ans += rightMax - arr[r]; 24 | 25 | r--; 26 | } 27 | } 28 | 29 | return ans; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Stack/slidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] maxSlidingWindow(int[] arr, int k) { 3 | int n = arr.length; 4 | ArrayList list = new ArrayList<>(); 5 | Deque deque = new LinkedList<>(); 6 | 7 | int i=0; 8 | int j=0; 9 | while(j 0 && deque.getLast() < arr[j]) 11 | deque.pollLast(); 12 | deque.add(arr[j]); 13 | 14 | if(j-i+1 < k) 15 | j++; 16 | 17 | else if(j-i+1 == k){ 18 | list.add(deque.peek()); 19 | 20 | if(deque.peek() == arr[i]) 21 | deque.pollFirst(); 22 | 23 | i++; 24 | j++; 25 | } 26 | } 27 | 28 | int ans[] = new int[list.size()]; 29 | for(i=0; i st = new Stack<>(); 7 | 8 | int ans[] = new int[n]; 9 | int k = 0; 10 | 11 | for(int i=0; i0 && st.peek()[0] > arr[i]) 16 | ans[k++] = st.peek()[1]; 17 | 18 | else if(st.size()>0 && st.peek()[0] <= arr[i]){ 19 | while(st.size()>0 && st.peek()[0] <= arr[i]) 20 | st.pop(); 21 | 22 | if(st.size() == 0) 23 | ans[k++] = -1; 24 | else 25 | ans[k++] = st.peek()[1]; 26 | } 27 | 28 | st.add(new int[]{arr[i], i}); 29 | } 30 | 31 | for(int i=0; i st = new Stack<>(); 8 | 9 | int i = 0; 10 | while(i find_permutation(String str) { 3 | List ans = new ArrayList<>(); 4 | permutate(ans, str, 0, str.length()-1); 5 | 6 | Collections.sort(ans); 7 | return ans; 8 | } 9 | 10 | 11 | private static void permutate(List ans, String str, int l, int r){ 12 | // base case 13 | if(l == r){ 14 | ans.add(str); 15 | return; 16 | } 17 | 18 | for(int i=l; i<=r; i++){ 19 | // swap characters 20 | str = swap(str, l, i); // abc -> cba; 21 | permutate(ans, str, l+1, r); // A KO FIX RAKHKE REMAINING CHARACTERS KA PERMUTATIONS LENA HAI 22 | // backtrack 23 | str = swap(str, l, i); // cba -> abc 24 | } 25 | 26 | 27 | } 28 | 29 | 30 | private static String swap(String str, int l, int r){ 31 | 32 | char charArray[] = str.toCharArray(); 33 | char temp = charArray[l]; 34 | charArray[l] = charArray[r]; 35 | charArray[r] = temp; 36 | 37 | return String.valueOf(charArray); 38 | } 39 | 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Strings/removeCharacters.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static String removeChars(String string1, String string2){ 3 | int arr[] = new int[26]; 4 | Arrays.fill(arr, 0); 5 | 6 | int l1 = string1.length(); 7 | int l2 = string2.length(); 8 | 9 | for(int i=0; i=0; i--) 11 | s += str[i] + " "; 12 | 13 | 14 | return s.trim(); 15 | } 16 | } 17 | 18 | 19 | 20 | // method 2 21 | // without using built in function; 22 | 23 | 24 | class Solution { 25 | public String reverseWords(String S) { 26 | String str[] = S.split(" +"); 27 | 28 | str = reverse(str, str.length); 29 | String s = String.join(" ", str); 30 | 31 | 32 | return s.trim(); 33 | } 34 | 35 | 36 | private String[] reverse(String str[], int n){ 37 | if(n%2 == 0){ 38 | int mid = n/2; 39 | 40 | while(mid = 0; 8 | } 9 | } 10 | 11 | 12 | -------------------------------------------------------------------------------- /Strings/runLengthEncoding.java: -------------------------------------------------------------------------------- 1 | 2 | class GfG 3 | { 4 | String encode(String str) 5 | { 6 | StringBuilder ans = new StringBuilder(); 7 | int count = 1; 8 | int len = str.length(); 9 | 10 | for(int i=0; i txtLen) return false; 10 | 11 | for(int i=0; i 4) 7 | return false; 8 | 9 | 10 | for(String a: str) { 11 | try{ 12 | if(Integer.parseInt(a)>255 || (a.charAt(0)=='0' && a.length()!=1)) return false; 13 | } catch (NumberFormatException e) { return false; } 14 | } 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Two pointer/ClonelLinkedListWithNextAndRandomPointer.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // using hashMap 3 | // time o(n) && space o(n) 4 | 5 | 6 | 7 | class Clone { 8 | //Function to clone a linked list with next and random pointer. 9 | Node copyList(Node head) { 10 | if(head == null) 11 | return null; 12 | 13 | HashMap map = new HashMap<>(); 14 | Node currNode = head; 15 | 16 | // creating another list and copying original list's data; 17 | while(currNode != null){ 18 | map.put(currNode, new Node(currNode.data)); 19 | currNode = currNode.next; 20 | } 21 | 22 | // copying and linking next and random pointer 23 | for(Map.Entry entry: map.entrySet()){ 24 | Node node = entry.getValue(); 25 | 26 | node.next = map.get(entry.getKey().next); 27 | node.arb = map.get(entry.getKey().arb); 28 | } 29 | 30 | return map.get(head); 31 | } 32 | } 33 | 34 | 35 | 36 | // method 2 37 | // two pointer approach 38 | // time o(n) && space o(1) 39 | 40 | 41 | class Solution { 42 | public Node copyRandomList(Node head) { 43 | Node iter = head; 44 | Node front = head; 45 | 46 | // connecting copy nodes just after to respective original nodes; 47 | while(iter != null){ 48 | front = iter.next; 49 | Node copyNode = new Node(iter.val); 50 | iter.next = copyNode; 51 | copyNode.next = front; 52 | iter = front; 53 | } 54 | 55 | 56 | // delaing with random pointer 57 | iter = head; 58 | while(iter != null){ 59 | if(iter.random != null) 60 | iter.next.random = iter.random.next; 61 | 62 | iter = iter.next.next; 63 | } 64 | 65 | 66 | // separating copy linked list and orignial linked list; 67 | iter = head; 68 | Node pseudoHead = new Node(0); 69 | Node copy = pseudoHead; 70 | while(iter != null){ 71 | front = iter.next.next; 72 | copy.next = iter.next; 73 | 74 | iter.next = front; 75 | iter = iter.next; 76 | copy = copy.next; 77 | } 78 | 79 | 80 | return pseudoHead.next; 81 | } 82 | } 83 | 84 | -------------------------------------------------------------------------------- /Two pointer/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Two pointer/maxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMaxConsecutiveOnes(int[] arr) { 3 | int n = arr.length; 4 | int count = 0; 5 | int max = 0; 6 | 7 | for(int i=0; i=0; j--) 14 | leftMax = Math.max(leftMax, arr[j]); 15 | 16 | // find max from right; 17 | int rightMax = Integer.MIN_VALUE; 18 | for(int j=i; j=0; j--) 51 | rightMax[j] = Math.max(arr[j], rightMax[j+1]); 52 | 53 | // calculating the total water tapped 54 | int ans = 0; 55 | for(int i=0; i= leftMax) 79 | leftMax = arr[l]; 80 | else 81 | ans += leftMax - arr[l]; 82 | 83 | l++; 84 | } 85 | else{ 86 | if(arr[r] >= rightMax) 87 | rightMax = arr[r]; 88 | else 89 | ans += rightMax - arr[r]; 90 | 91 | r--; 92 | } 93 | } 94 | 95 | return ans; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /binary search/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /binary search/elementAppearsOnlyOnceInSortedArray.java: -------------------------------------------------------------------------------- 1 | lass Sol 2 | { 3 | public static int search(int a[], int n) 4 | { 5 | int start = 0; 6 | int end = n-1; 7 | 8 | if(end == 0) 9 | return a[end]; 10 | 11 | if(a[0] != a[1]) 12 | return a[0]; 13 | 14 | if(a[n-1] != a[n-2]) 15 | return a[n-1]; 16 | 17 | while(start <= end){ 18 | int mid = start + (end - start)/2; 19 | 20 | if(a[mid] != a[mid+1] && a[mid] != a[mid-1]) 21 | return a[mid]; 22 | 23 | if((mid%2 == 0 && (a[mid] == a[mid+1])) || (mid%2 != 0 && (a[mid] == a[mid-1]))) 24 | start = mid+1; 25 | else 26 | end = mid - 1; 27 | } 28 | return -1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /binary search/indexOfAnExtraElement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findExtra(int a[], int b[], int n) { 3 | int left = 0; 4 | int right = n-1; 5 | int ans = -1; 6 | 7 | while(left <= right){ 8 | int mid = left + (right-left)/2; 9 | 10 | 11 | // If middle element is same 12 | // of both arrays, it means 13 | // that extra element is after 14 | // mid so we update left to mid+1 15 | if(mid < b.length && a[mid] == b[mid]) 16 | left = mid + 1; 17 | 18 | // If middle element is different 19 | // of the arrays, it means that 20 | // the index we are searching for 21 | // is either mid, or before mid. 22 | // Hence we update right to mid-1. 23 | else{ 24 | ans = mid; 25 | right = mid-1; 26 | } 27 | } 28 | 29 | return ans; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /foundation/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /foundation/allPrime.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | 4 | public class Solution { 5 | 6 | public static void main(String[] args) { 7 | 8 | Scanner sc = new Scanner(System.in); 9 | int n = sc.nextInt(); 10 | for(int i=2; i<=n; i++){ 11 | boolean isPrime = true; 12 | for(int j=2; j=0 && rowStart=0){ 22 | 23 | // print elements from colStart to colEnd; 24 | for(int i=colStart; i<=colEnd; i++){ 25 | System.out.print(arr[rowStart][i] + " "); 26 | count++; 27 | } 28 | rowStart++; 29 | 30 | // print elements from rowStart to rowEnd; 31 | for(int i=rowStart; i<=rowEnd; i++){ 32 | System.out.print(arr[i][colEnd] + " "); 33 | count++; 34 | } 35 | colEnd--; 36 | 37 | // print elements from colEnd to colStart; 38 | for(int i=colEnd; i>=colStart; i--){ 39 | System.out.print(arr[rowEnd][i] + " "); 40 | count++; 41 | } 42 | rowEnd--; 43 | 44 | // print elements form rowEnd to rowStart; 45 | for(int i=rowEnd; i>=rowStart; i--){ 46 | System.out.print(arr[i][colStart] + " "); 47 | count++; 48 | } 49 | colStart++; 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /foundation/matrix/setMatricesZero.java: -------------------------------------------------------------------------------- 1 | // method 1 2 | // time o(mn) and space o(m+n) 3 | 4 | class Solution { 5 | public void setZeroes(int[][] mat) { 6 | int row[] = new int[mat.length]; 7 | int col[] = new int[mat[0].length]; 8 | 9 | int m = row.length; 10 | int n = col.length; 11 | 12 | Arrays.fill(row, -1); 13 | Arrays.fill(col, -1); 14 | 15 | for(int i=0; i= 0; i--) { 53 | for (int j = cols - 1; j >= 1; j--) 54 | if (matrix[i][0] == 0 || matrix[0][j] == 0) 55 | matrix[i][j] = 0; 56 | if (col0 == 0) matrix[i][0] = 0; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /foundation/string/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /foundation/string/checkPermutations.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | 5 | public static boolean isPermutation(String str1, String str2) { 6 | if(str1.length()!=str2.length()){ 7 | return false; 8 | } 9 | int a[]=new int[256]; 10 | 11 | for(int i=0;i 1){ 16 | //answer += str.charAt(i); 17 | answer += currentCharCount; 18 | currentCharCount = 1; 19 | } 20 | 21 | answer += str.charAt(i); 22 | } 23 | } 24 | 25 | if(currentCharCount > 1) 26 | answer += currentCharCount; 27 | 28 | return answer; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /foundation/string/isPalindrome.java: -------------------------------------------------------------------------------- 1 | public static boolean isPalindrome(String str) { 2 | int l = str.length(); 3 | int k = l-1; 4 | for(int i=0; i=0){ 7 | // taking care of spaces 8 | while(i>=0 && s.charAt(i) == ' ') 9 | i--; 10 | 11 | int j = i; 12 | if(i<0) 13 | break; 14 | 15 | // main logic 16 | while(i>=0 && s.charAt(i) != ' ') 17 | i--; 18 | if(ans.isEmpty()) 19 | ans = ans.concat(s.substring(i+1, j+1)); 20 | else{ 21 | ans = ans.concat(" " + s.substring(i+1, j+1)); 22 | } 23 | } 24 | 25 | return ans; 26 | } 27 | } 28 | 29 | 30 | 31 | // by using string builder 32 | 33 | public class Solution { 34 | public static String reverseWordWise(String s) { 35 | 36 | int i = s.length() - 1; 37 | StringBuilder ans = new StringBuilder(); 38 | while(i>=0){ 39 | // taking care of spaces 40 | while(i>=0 && s.charAt(i) == ' ') 41 | i--; 42 | 43 | int j = i; 44 | if(i<0) 45 | break; 46 | 47 | // main logic 48 | while(i>=0 && s.charAt(i) != ' ') 49 | i--; 50 | if(ans.capacity() == 0) 51 | ans.append(s.substring(i+1, j+1)); 52 | else{ 53 | ans.append(" " + s.substring(i+1, j+1)); 54 | } 55 | } 56 | 57 | return ans.toString().trim(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /matrix/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /matrix/rotateMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] mat) { 3 | int n = mat.length; 4 | 5 | // finding transpose of matrix; 6 | for(int i=0; i=0){ 8 | if(key == mat[i][j]) 9 | return true; 10 | else if( key > mat[i][j]) 11 | i++; 12 | else 13 | j--; 14 | } 15 | 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /matrix/spiralMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List spiralOrder(int[][] mat) { 3 | int m = mat.length; 4 | int n = mat[0].length; 5 | List list = new ArrayList(); 6 | 7 | int top = 0, left = 0, bottom = m-1, right = n-1; 8 | while(top <= bottom && left <= right){ 9 | for(int i=left; i<=right; i++) 10 | list.add(mat[top][i]); 11 | top++; 12 | 13 | for(int i=top; i<=bottom; i++) 14 | list.add(mat[i][right]); 15 | right--; 16 | 17 | if(top <= bottom){ 18 | for(int i=right; i>=left; i--) 19 | list.add(mat[bottom][i]); 20 | bottom--; 21 | } 22 | 23 | if(left <= right){ 24 | for(int i=bottom; i>=top; i--) 25 | list.add(mat[i][left]); 26 | left++; 27 | } 28 | } 29 | 30 | return list; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /matrix/transposeMatrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] transpose(int[][] mat) { 3 | int m = mat.length; 4 | int n = mat[0].length; 5 | 6 | if(m == n){ 7 | for(int i=0; i