├── Class11 ├── AggressiveCows.java └── FirstBadVersion.java ├── Class16 ├── CountNicePairs.java ├── FreqArray.java ├── GroupAnagrams.java ├── TwoSumOnePass.java └── TwoSumTwoPass.java ├── MaximalRectangel.java ├── README.md ├── class1 ├── Factorial.java ├── PrintDecreasing.java ├── PrintIncreasing.java ├── PrintReverse.java └── VoidReturnDemo.java ├── class10 ├── EditDistance.java ├── LCS.java ├── MinPathSum.java └── UncrossedLines.java ├── class12 ├── BookAllocationProblem.java ├── StackClassDemo.java ├── StockSpanBrute.java └── StockSpanUsingStack.java ├── class13 ├── FormMinNumber.java ├── IsBalancedParenthesis.java └── NextGreaterElement.java ├── class14 ├── MaxAreaUnderHistogram.java ├── NextSmallerElement.java ├── PreviousGreaterElement.java └── PreviousSmallerElement.java ├── class15 ├── GroupAnagrams.java ├── HashMapDemo.java ├── MajorityElement.java ├── MiscMapFunctions.java └── merge.java ├── class17 ├── BinarySearchUtility.java ├── BusyMan.java ├── Car.java └── IndianCoinChange.java ├── class18 ├── BinaryTree.java └── BinaryTreeClient.java ├── class19 ├── BinaryTree.java ├── BinaryTreeClient.java └── PathSum.java ├── class2 ├── AllIndices.java ├── FibonacciNumber.java ├── FirstOccurence.java └── StairWays.java ├── class20 ├── ArrayListDemo.java ├── DiameterOne.java ├── DiameterTwo.java └── PathSum2.java ├── class21 ├── BalancedBTBottomUp.java ├── BalancedBinaryTree.java ├── BinaryTree.java ├── BinaryTreeClient.java └── RightView.java ├── class22 ├── BinaryTree.java ├── PreInBuild.java └── VerticalOrderTraversal.java ├── class23 ├── BSTClient.java └── BinarySearchTree.java ├── class24 ├── AddInBST.java ├── BinarySearchTree.java ├── DeleteInBST.java ├── PrintInRangeClient.java └── ValidateBST.java ├── class25 ├── AlienDictionary.java ├── CourseScheduleOne.java └── Graph.java ├── class28 ├── CycleInDirectedGraph.java ├── Main.java └── ValidTree.java ├── class29 ├── DisjointSetUnionUnoptimised.java └── KruskalAlgorithm.java ├── class3 ├── Permutations.java ├── SubsequenceGenerate.java └── SubstringDemo.java ├── class30 ├── DisjointSetOptimised.java └── PrimsAlgorithm.java ├── class31 ├── DjikstraAlgorithm.java ├── MergeTwoSortedLists.java └── MiddleOfLinkedList.java ├── class32 ├── IntersectionOfTwoLinkedList.java ├── OddEvenLinkedList.java ├── ReverseInKPairs.java ├── ReverseLLBetween.java ├── ReverseLinkedList.java └── SwapNodesInPairs.java ├── class33 └── SegmentTree.java ├── class34 ├── SegmentTree.java └── SegmentTreeRangeSum.java ├── class35 └── FenwickTree.java ├── class36 └── FenwickTree.java ├── class37 ├── FormBiggestNumber.java └── Trie.java ├── class38 ├── CbNumber.java └── SieveOfEratosthenes.java ├── class4 ├── GenerateBrackets.java └── LexicoCounting.java ├── class5 ├── BlockedMaze.java ├── MazePathFour.java └── MazePathTwoDir.java ├── class6 ├── LetterCombinations.java └── NQueen2.java ├── class7 ├── FibonacciNumber.java └── MinCostClimbingStairs.java ├── class8 ├── DeleteAndEarn.java ├── HouseRobber.java └── LIS.java └── class9 ├── CoinChange2.java ├── DistinctSubsequences.java └── KnapsackZeroOne.java /Class11/AggressiveCows.java: -------------------------------------------------------------------------------- 1 | package Class11; 2 | 3 | import java.util.Arrays; 4 | 5 | public class AggressiveCows { 6 | 7 | private static boolean isPlaced(int[] stalls, int cows, int mid) { 8 | // TODO Auto-generated method stub 9 | 10 | int placedPos = stalls[0]; 11 | int numPlaced = 1; 12 | 13 | for(int stallNum = 1; stallNum < stalls.length; stallNum++) { 14 | 15 | if(numPlaced == cows) { 16 | return true; 17 | } 18 | int currStall = stalls[stallNum]; 19 | if(currStall - placedPos >= mid) { 20 | numPlaced++; 21 | placedPos = currStall; 22 | } 23 | } 24 | return false; 25 | } 26 | public static void main(String[] args) { 27 | // TODO Auto-generated method stub 28 | 29 | int[] stalls = {1, 2, 8, 4, 9}; 30 | int n = 5, c = 3; 31 | Arrays.sort(stalls); 32 | System.out.println(Arrays.toString(stalls)); 33 | int l = 0, r = stalls[n - 1] - stalls[0]; //r = 8 34 | 35 | while(r > l + 1) { 36 | int mid = l + (r - l) / 2; //kya main 3 cows ko mid distance pr place kr pa rahah hun? 37 | 38 | if(isPlaced(stalls, c, mid)) { 39 | l = mid; 40 | } else { 41 | r = mid; 42 | } 43 | } 44 | 45 | System.out.println(l); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Class11/FirstBadVersion.java: -------------------------------------------------------------------------------- 1 | package Class11; 2 | 3 | public class FirstBadVersion { 4 | 5 | private static boolean isBad(char version) { 6 | // TODO Auto-generated method stub 7 | if(version == 'B') { 8 | return true; 9 | } 10 | 11 | return false; 12 | } 13 | public static void main(String[] args) { 14 | // TODO Auto-generated method stub 15 | 16 | char[] version = {'G', 'G', 'G', 'G', 'B'}; 17 | 18 | int l = -1, r = version.length - 1; 19 | 20 | while(r > l + 1) { 21 | int mid = (l + r) / 2; 22 | 23 | if(isBad(version[mid])) { 24 | r = mid; 25 | } else { 26 | l = mid; 27 | } 28 | } 29 | 30 | System.out.println(r); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Class16/CountNicePairs.java: -------------------------------------------------------------------------------- 1 | package Class16; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class CountNicePairs { 8 | 9 | private static int rev(int num) { 10 | // TODO Auto-generated method stub 11 | 12 | int revNum = 0; 13 | 14 | while(num > 0) { 15 | int digit = num % 10; 16 | num = num / 10; 17 | 18 | revNum = revNum * 10 + digit; 19 | } 20 | 21 | //System.out.println(revNum); 22 | 23 | return revNum; 24 | } 25 | public static void main(String[] args) { 26 | // TODO Auto-generated method stub 27 | 28 | int[] arr = { 42, 11, 1, 97, 97}; 29 | 30 | // Hashmap key -> element, value -> corresponding index 31 | 32 | Map map = new HashMap<>(); 33 | 34 | int ans = 0; 35 | 36 | //Searching 37 | for(int i = 0; i < arr.length; i++) { 38 | int searchInMap = arr[i] - rev(arr[i]); //element as a key 39 | 40 | if(map.containsKey(searchInMap)) { 41 | ans += map.get(searchInMap); 42 | } 43 | 44 | map.put(searchInMap, map.getOrDefault(searchInMap, 0) + 1); 45 | 46 | } 47 | 48 | System.out.println(ans); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Class16/FreqArray.java: -------------------------------------------------------------------------------- 1 | package Class16; 2 | 3 | public class FreqArray { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | 9 | int[] freq = new int[26]; 10 | String str = "eat"; 11 | for(int i = 0; i < str.length(); i++) { 12 | char cc = str.charAt(i); //e 13 | int index = cc - 'a';//'e' - 'a' -> index = 4 14 | freq[index]++; 15 | } 16 | 17 | for(int e : freq) { 18 | System.out.print(e + " "); 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Class16/GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | package Class16; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public class GroupAnagrams { 10 | 11 | public static List> groupAnagrams(String[] strs) { 12 | 13 | Map> map = new HashMap<>(); 14 | 15 | for(String currString : strs) { 16 | int[] freq = new int[26]; 17 | 18 | for(int i = 0; i < currString.length(); i++) { 19 | char cc = currString.charAt(i); //e 20 | int index = cc - 'a';//'e' - 'a' -> index = 4 21 | freq[index]++; 22 | } 23 | 24 | 25 | //System.out.print(currString + "->"); 26 | StringBuilder sb = new StringBuilder(); 27 | for(int e : freq) { 28 | sb.append(e); 29 | sb.append('|'); 30 | } 31 | 32 | String key = sb.toString(); 33 | 34 | 35 | //System.out.println(); 36 | /* 37 | if(map.containsKey(sortedStringKey)) { 38 | List anaList = map.get(sortedStringKey); 39 | anaList.add(currString); 40 | map.put(sortedStringKey, anaList); 41 | } else { 42 | List anaList = new ArrayList<>(); 43 | anaList.add(currString); 44 | map.put(sortedStringKey, anaList); 45 | } 46 | 47 | */ 48 | 49 | List anaList = map.getOrDefault(key, new ArrayList<>()); 50 | anaList.add(currString); 51 | map.put(key, anaList); 52 | 53 | 54 | } 55 | 56 | System.out.println(map); 57 | 58 | 59 | List> ans = new ArrayList<>(); 60 | ans.addAll(map.values()); 61 | 62 | return ans; 63 | } 64 | 65 | public static void main(String[] args) { 66 | // TODO Auto-generated method stub 67 | 68 | String[] arr = {"aaaaaaaaaab", "acccccccccc"}; 69 | groupAnagrams(arr); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /Class16/TwoSumOnePass.java: -------------------------------------------------------------------------------- 1 | package Class16; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class TwoSumOnePass { 8 | 9 | public static void main(String[] args) { 10 | // TODO Auto-generated method stub 11 | 12 | int[] arr = { 11, 15, 7, 2 }; 13 | int target = 14; 14 | // Hashmap key -> element, value -> corresponding index 15 | 16 | Map map = new HashMap<>(); 17 | 18 | 19 | //Searching 20 | for(int i = 0; i < arr.length; i++) { 21 | int searchInMap = target - arr[i]; //element as a key 22 | 23 | if(map.containsKey(searchInMap)) { 24 | int[] pair = new int[2]; 25 | pair[0] = i; 26 | pair[1] = map.get(searchInMap); //index as a value 27 | System.out.println(Arrays.toString(pair)); 28 | break; 29 | } 30 | 31 | map.put(arr[i], i); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Class16/TwoSumTwoPass.java: -------------------------------------------------------------------------------- 1 | package Class16; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class TwoSumTwoPass { 8 | 9 | public static void main(String[] args) { 10 | // TODO Auto-generated method stub 11 | 12 | int[] arr = { 7, 7, 7 }; 13 | int target = 14; 14 | // Hashmap key -> element, value -> corresponding index 15 | 16 | Map map = new HashMap<>(); 17 | 18 | for(int i = 0; i < arr.length; i++) { 19 | map.put(arr[i], i); 20 | } 21 | 22 | System.out.println(map); 23 | 24 | //Searching 25 | for(int i = 0; i < arr.length; i++) { 26 | int searchInMap = target - arr[i]; //element as a key 27 | 28 | if(map.containsKey(searchInMap) && i != map.get(searchInMap)) { 29 | int[] pair = new int[2]; 30 | pair[0] = i; 31 | pair[1] = map.get(searchInMap); //index as a value 32 | System.out.println(Arrays.toString(pair)); 33 | break; 34 | } 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /MaximalRectangel.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maximalRectangle(char[][] matrix) { 3 | 4 | if(matrix.length == 0) { 5 | return 0; 6 | } 7 | int maxA = Integer.MIN_VALUE; 8 | int[] ht = new int[matrix[0].length]; 9 | for(int i = 0; i < matrix.length; i++) { 10 | 11 | for(int j = 0; j < matrix[0].length; j++) { 12 | if(matrix[i][j] == '1') { 13 | ht[j] = ht[j] + 1; 14 | } else { 15 | ht[j] = 0; 16 | } 17 | // ht[j] = matrix[i][j] == 1 ? ht[j] + 1 : 0; 18 | } 19 | System.out.println(Arrays.toString(ht)); 20 | maxA = Math.max(maxA, sol(ht, ht.length)); 21 | } 22 | 23 | return maxA; 24 | } 25 | 26 | public int sol(int[] arr, int n) { 27 | Stack st = new Stack<>(); 28 | 29 | int[] nse = new int[n]; 30 | st.push(0); 31 | 32 | for (int curr = 1; curr < arr.length; curr++) { 33 | 34 | // is curr building nse of top building? 35 | while (!st.isEmpty() && arr[st.peek()] > arr[curr]) { 36 | nse[st.pop()] = curr; 37 | // System.out.println(st.pop() + "->" + arr[curr]); 38 | } 39 | 40 | st.push(curr); 41 | } 42 | 43 | while (!st.isEmpty()) { 44 | nse[st.pop()] = n; 45 | // System.out.println(st.pop() + "->" + -1); 46 | } 47 | 48 | 49 | int[] pse = new int[n]; 50 | st.push(0); // height 51 | pse[0] = -1; 52 | // System.out.println(arr[0] + "->" + -1); 53 | for (int curr = 1; curr < n; curr++) { 54 | 55 | while (!st.isEmpty() && arr[curr] <= arr[st.peek()]) { 56 | 57 | st.pop(); 58 | } 59 | 60 | if (!st.isEmpty()) { 61 | pse[curr] = st.peek(); 62 | } else { 63 | pse[curr] = -1; 64 | } 65 | 66 | st.push(curr); 67 | } 68 | 69 | 70 | 71 | int maxArea = Integer.MIN_VALUE; 72 | for(int i = 0; i < n; i++) { 73 | //ith building width 74 | int width = nse[i] - pse[i] - 1; 75 | int area = width * arr[i]; 76 | 77 | maxArea = Math.max(maxArea, area); 78 | } 79 | 80 | 81 | return maxArea; 82 | } 83 | } 84 | 85 | class Solution { 86 | public int validSubarrays(int[] ht) { 87 | 88 | Stack st = new Stack<>(); 89 | 90 | int[] nse = new int[ht.length]; 91 | st.push(0); 92 | 93 | for(int curr = 1; curr < ht.length; curr++) { 94 | 95 | while(!st.isEmpty() && ht[st.peek()] > ht[curr]) { 96 | nse[st.pop()] = curr; 97 | } 98 | st.push(curr); 99 | } 100 | 101 | while(!st.isEmpty()) { 102 | nse[st.pop()] = ht.length; 103 | //System.out.println(st.pop() + " ka nge hai " + -1); 104 | } 105 | 106 | int ans = 0; 107 | for(int i = 0; i < ht.length; i++) { 108 | ans += (nse[i] - i); 109 | } 110 | 111 | return ans; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GLAJava 2 | This repository contains all the codes for the sessions. Extra content other then codes will also be added here. 3 | -------------------------------------------------------------------------------- /class1/Factorial.java: -------------------------------------------------------------------------------- 1 | package class1; 2 | 3 | public class Factorial { 4 | 5 | private static void fact2(int n, int ans) { 6 | // TODO Auto-generated method stub 7 | 8 | if(n == 0 || n == 1) { 9 | System.out.println(ans); 10 | return; 11 | } 12 | fact2(n - 1, ans * n); 13 | } 14 | private static int fact(int n) { 15 | // TODO Auto-generated method stub 16 | 17 | if(n == 0 || n == 1) {//1 18 | return 1; 19 | } 20 | 21 | 22 | int recAns = fact(n - 1);//2 23 | int meraAns = n * recAns;//3 24 | 25 | return meraAns; 26 | } 27 | public static void main(String[] args) { 28 | // TODO Auto-generated method stub 29 | fact2(4, 1); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /class1/PrintDecreasing.java: -------------------------------------------------------------------------------- 1 | package class1; 2 | 3 | public class PrintDecreasing { 4 | 5 | private static void printDec(int n) { 6 | if(n == 0) { 7 | return; 8 | } 9 | System.out.println(n); 10 | printDec(n - 1); 11 | 12 | } 13 | public static void main(String[] args) { 14 | // TODO Auto-generated method stub 15 | printDec(5); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /class1/PrintIncreasing.java: -------------------------------------------------------------------------------- 1 | package class1; 2 | 3 | public class PrintIncreasing { 4 | 5 | private static void printInc(int n) { 6 | if(n == 0) { 7 | return; 8 | } 9 | 10 | printInc(n - 1); 11 | System.out.println(n); 12 | return; 13 | } 14 | public static void main(String[] args) { 15 | // TODO Auto-generated method stub 16 | printInc(5); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /class1/PrintReverse.java: -------------------------------------------------------------------------------- 1 | package class1; 2 | 3 | public class PrintReverse { 4 | 5 | private static void reverse(int[]arr, int n, int ci) { 6 | // TODO Auto-generated method stub 7 | 8 | if(ci == n) { 9 | return; 10 | } 11 | reverse(arr, n, ci + 1); 12 | System.out.println(arr[ci]); 13 | } 14 | public static void main(String[] args) { 15 | // TODO Auto-generated method stub 16 | 17 | int[] arr = {1, 2, 3, 4, 5}; 18 | int n = 5; 19 | reverse(arr, n, 0); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /class1/VoidReturnDemo.java: -------------------------------------------------------------------------------- 1 | package class1; 2 | 3 | public class VoidReturnDemo { 4 | private static void tester() { 5 | // TODO Auto-generated method stub 6 | System.out.println("Hello friends"); 7 | return; 8 | } 9 | public static void main(String[] args) { 10 | // TODO Auto-generated method stub 11 | System.out.println("Hi amigos!"); 12 | tester(); 13 | System.out.println("bye amigos!"); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /class10/EditDistance.java: -------------------------------------------------------------------------------- 1 | package class10; 2 | 3 | public class EditDistance { 4 | 5 | private static int sol(String s1, String s2, int n, int m) { 6 | // TODO Auto-generated method stub 7 | 8 | if(n == 0 && m == 0) { 9 | return 0; 10 | } 11 | 12 | if(n == 0) { 13 | return m; 14 | } 15 | 16 | if(m == 0) { 17 | return n; 18 | } 19 | 20 | if(s1.charAt(n - 1) == s2.charAt(m - 1)) { 21 | return sol(s1, s2, n - 1, m - 1); 22 | } 23 | 24 | int ins = sol(s1, s2, n, m - 1); 25 | int rep = sol(s1, s2, n - 1, m - 1); 26 | int del = sol(s1, s2, n - 1, m); 27 | 28 | return 1 + Math.min(ins, Math.min(rep, del)); 29 | } 30 | public static void main(String[] args) { 31 | // TODO Auto-generated method stub 32 | 33 | System.out.println(sol("intention", "execution", 9, 9)); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /class10/LCS.java: -------------------------------------------------------------------------------- 1 | package class10; 2 | 3 | public class LCS { 4 | 5 | private static int sol(String s1, String s2, int n, int m) { 6 | // TODO Auto-generated method stub 7 | 8 | if(n == 0 || m == 0) { 9 | return 0; 10 | } 11 | if(s1.charAt(n - 1) == s2.charAt(m - 1)) { 12 | return 1 + sol(s1, s2, n - 1, m - 1); 13 | } 14 | 15 | int c1 = sol(s1, s2, n - 1, m); 16 | int c2 = sol(s1, s2, n, m - 1); 17 | 18 | return Math.max(c1, c2); 19 | } 20 | public static void main(String[] args) { 21 | // TODO Auto-generated method stub 22 | 23 | String s1 = "abcde"; 24 | String s2 = "aec"; 25 | 26 | System.out.println(sol(s1, s2, s1.length(), s2.length())); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /class10/MinPathSum.java: -------------------------------------------------------------------------------- 1 | package class10; 2 | 3 | public class MinPathSum { 4 | 5 | private static int sol(int[][] grid, int cr, int cc, int er, int ec) { 6 | // TODO Auto-generated method stub 7 | 8 | if(cr > er || cc > ec) { 9 | return 0; 10 | } 11 | 12 | if(cr == er && cc == ec) { 13 | return grid[cr][cc]; 14 | } 15 | int c1 = sol(grid, cr, cc + 1, er, ec); //right 16 | int c2 = sol(grid, cr + 1, cc, er, ec); //down 17 | int minAns = Math.min(c1, c2); 18 | return grid[cr][cc] + minAns; 19 | } 20 | public static void main(String[] args) { 21 | // TODO Auto-generated method stub 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /class10/UncrossedLines.java: -------------------------------------------------------------------------------- 1 | package class10; 2 | 3 | public class UncrossedLines { 4 | 5 | private static int sol(int[] s1, int[] s2, int n, int m) { 6 | // TODO Auto-generated method stub 7 | 8 | if(n == 0 || m == 0) { 9 | return 0; 10 | } 11 | if(s1[n - 1] == s2[m - 1]) { 12 | return 1 + sol(s1, s2, n - 1, m - 1); 13 | } 14 | 15 | int c1 = sol(s1, s2, n - 1, m); 16 | int c2 = sol(s1, s2, n, m - 1); 17 | 18 | return Math.max(c1, c2); 19 | } 20 | public static void main(String[] args) { 21 | // TODO Auto-generated method stub 22 | 23 | int[] s1 = {1, 4, 2}; 24 | int[] s2 = {1, 2, 4}; 25 | 26 | System.out.println(sol(s1, s2, s1.length, s2.length)); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /class12/BookAllocationProblem.java: -------------------------------------------------------------------------------- 1 | package class12; 2 | 3 | public class BookAllocationProblem { 4 | 5 | private static boolean canReadForCapacity(int[] pages, int numSt, int maxCap) { 6 | // TODO Auto-generated method stub 7 | 8 | int stNum = 1; 9 | int pagesRead = 0; 10 | 11 | int bookNum = 0; 12 | 13 | while(bookNum < pages.length) { 14 | 15 | if(pages[bookNum] + pagesRead <= maxCap) { 16 | pagesRead += pages[bookNum]; 17 | bookNum++; 18 | } else { 19 | stNum++; 20 | pagesRead = 0; 21 | } 22 | 23 | if(stNum > numSt) { 24 | return false; 25 | } 26 | } 27 | 28 | return true; 29 | } 30 | public static void main(String[] args) { 31 | // TODO Auto-generated method stub 32 | 33 | int[] pages = {10, 20, 30, 40}; 34 | int n = 4; 35 | int numSt = 2; 36 | int sum = 10 + 20 + 30 + 40 ; 37 | 38 | int l = 0, r = sum; 39 | 40 | while(r > l + 1) { 41 | int mid = (l + r) / 2; //maxCapacity 42 | 43 | if(canReadForCapacity(pages, numSt, mid)) { 44 | r = mid; 45 | } else { 46 | l = mid; 47 | } 48 | } 49 | 50 | System.out.println(r); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /class12/StackClassDemo.java: -------------------------------------------------------------------------------- 1 | package class12; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackClassDemo { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | Stack st = new Stack<>(); 11 | System.out.println(st.isEmpty()); 12 | st.push(1); 13 | st.push(3); 14 | st.push(5); 15 | 16 | 17 | System.out.println(st.peek()); 18 | System.out.println(st.pop()); 19 | 20 | System.out.println(st.peek()); 21 | 22 | System.out.println(st.isEmpty()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /class12/StockSpanBrute.java: -------------------------------------------------------------------------------- 1 | package class12; 2 | 3 | public class StockSpanBrute { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | int[] prices = {31, 27, 14, 21, 30, 22}; 9 | int days = 6; 10 | 11 | int[] span = new int[days]; 12 | span[0] = 1; 13 | 14 | for(int curr = 1; curr < days; curr++) { 15 | span[curr] = 1; 16 | 17 | for(int prev = curr - 1; prev >= 0; prev--) { 18 | if(prices[prev] < prices[curr]) { 19 | span[curr]++; 20 | } else { 21 | break; //prev greater element mila to break out 22 | } 23 | } 24 | } 25 | 26 | for(int val : span) { 27 | System.out.print(val + " "); 28 | } 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /class12/StockSpanUsingStack.java: -------------------------------------------------------------------------------- 1 | package class12; 2 | 3 | import java.util.Stack; 4 | 5 | public class StockSpanUsingStack { 6 | 7 | //prev greater element 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | int[] prices = {10, 20, 30, 40}; 12 | int days = 4; 13 | 14 | int[] span = new int[days]; 15 | span[0] = 1; 16 | 17 | Stack st = new Stack<>(); 18 | 19 | st.push(0); 20 | 21 | for(int curr = 1; curr < days; curr++) { 22 | 23 | //jb tk prev greater element ni milta tb tk varna stack se break out 24 | while(!st.isEmpty() && prices[curr] > prices[st.peek()]) { 25 | st.pop(); 26 | } 27 | 28 | span[curr] = st.isEmpty() ? curr + 1: curr - st.peek(); 29 | st.push(curr); 30 | } 31 | 32 | for(int val : span) { 33 | System.out.print(val + " "); 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /class13/FormMinNumber.java: -------------------------------------------------------------------------------- 1 | package class13; 2 | import java.util.Stack; 3 | 4 | public class FormMinNumber { 5 | 6 | //Friends And Games 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | String inp = "IDIIIIDD"; 11 | int n = inp.length(); 12 | 13 | Stack st = new Stack<>(); 14 | for(int i = 0; i <= n; i++) { 15 | st.push(i + 1); 16 | 17 | if(i == n || inp.charAt(i) == 'I') { 18 | while(!st.isEmpty()) { 19 | System.out.print(st.pop()); 20 | } 21 | } 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /class13/IsBalancedParenthesis.java: -------------------------------------------------------------------------------- 1 | package class13; 2 | 3 | import java.util.Stack; 4 | 5 | public class IsBalancedParenthesis { 6 | 7 | private static boolean sol(String parenthesis) { 8 | // TODO Auto-generated method stub 9 | 10 | Stack s = new Stack<>(); 11 | for(int i = 0; i < parenthesis.length(); i++) { 12 | char ci = parenthesis.charAt(i); 13 | 14 | if(ci == '[' || ci == '{' || ci == '(') { 15 | s.push(ci); 16 | } else if(ci == ')' || ci == '}' || ci == ']'){ 17 | 18 | if(s.isEmpty()) { 19 | return false; 20 | } 21 | 22 | char topCh = s.pop(); 23 | 24 | if(topCh == '(' && ci == ')') { 25 | continue; 26 | } 27 | 28 | if(topCh == '{' && ci == '}') { 29 | continue; 30 | } 31 | 32 | if(topCh == '[' && ci == ']') { 33 | continue; 34 | } 35 | 36 | return false; 37 | } 38 | } 39 | 40 | if(s.isEmpty()) { 41 | return true; 42 | } else { 43 | return false; 44 | } 45 | 46 | } 47 | public static void main(String[] args) { 48 | // TODO Auto-generated method stub 49 | 50 | System.out.println(sol("}}}")); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /class13/NextGreaterElement.java: -------------------------------------------------------------------------------- 1 | package class13; 2 | 3 | import java.util.Stack; 4 | 5 | public class NextGreaterElement { 6 | 7 | //previous greater element -> same as stock span 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | int[] prices = {31, 14, 15, 20}; 12 | int days = 4; 13 | 14 | int[] nge = new int[days]; 15 | // span[0] = 1; 16 | 17 | Stack st = new Stack<>(); 18 | 19 | st.push(0); 20 | 21 | for(int curr = 1; curr < days; curr++) { 22 | 23 | //jb tk prev greater element ni milta tb tk varna stack se break out 24 | while(!st.isEmpty() && prices[curr] > prices[st.peek()]) { 25 | nge[st.pop()] = prices[curr]; 26 | //System.out.println(prices[st.pop()] + "->" + prices[curr]); 27 | } 28 | 29 | //span[curr] = st.isEmpty() ? curr + 1: curr - st.peek(); 30 | st.push(curr); 31 | } 32 | 33 | while(!st.isEmpty()) { 34 | nge[st.pop()] = -1; 35 | //System.out.println(prices[st.pop()] + "->" + -1); 36 | } 37 | for(int i = 0; i < days; i++) { 38 | System.out.println(prices[i] + "->" + nge[i]); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /class14/MaxAreaUnderHistogram.java: -------------------------------------------------------------------------------- 1 | package class14; 2 | 3 | import java.util.Stack; 4 | 5 | public class MaxAreaUnderHistogram { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | int[] arr = { 2, 1, 5, 6, 2, 3 }; 11 | int n = 6; 12 | 13 | Stack st = new Stack<>(); 14 | 15 | st.push(0); // 1 value 16 | 17 | int[] nse = new int[n]; 18 | for (int curr = 1; curr < arr.length; curr++) { 19 | 20 | while (!st.isEmpty() && arr[st.peek()] > arr[curr]) { 21 | nse[st.pop()] = curr; 22 | } 23 | 24 | st.push(curr); 25 | } 26 | 27 | while (!st.isEmpty()) { 28 | nse[st.pop()] = n; 29 | } 30 | 31 | for (int i = 0; i < n; i++) { 32 | System.out.println(arr[i] + "->" + nse[i]); 33 | } 34 | 35 | st = new Stack<>(); 36 | 37 | st.push(0); // 1 value 38 | 39 | int[] pse = new int[n]; 40 | 41 | pse[0] = -1; 42 | 43 | for(int curr = 1; curr < n; curr++) { 44 | 45 | while(!st.isEmpty() && arr[st.peek()] >= arr[curr]) { 46 | st.pop(); 47 | } 48 | 49 | if(!st.isEmpty()) { 50 | pse[curr] = st.peek(); 51 | } else { 52 | pse[curr] = -1; 53 | } 54 | 55 | st.push(curr); 56 | } 57 | 58 | for(int i = 0; i < n; i++) { 59 | System.out.println(arr[i] + "->" + pse[i]); 60 | } 61 | 62 | int maxArea = Integer.MIN_VALUE; 63 | 64 | for(int i = 0; i < n; i++) { 65 | int width = nse[i] - pse[i] - 1; 66 | int height = arr[i]; 67 | 68 | int area = width * height; 69 | 70 | maxArea = Math.max(area, maxArea); 71 | } 72 | 73 | System.out.println(maxArea); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /class14/NextSmallerElement.java: -------------------------------------------------------------------------------- 1 | package class14; 2 | 3 | import java.util.Stack; 4 | 5 | public class NextSmallerElement { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | int[] arr = {1, 5, 6, 2, 3}; 11 | 12 | int n = 5; 13 | 14 | Stack st = new Stack<>(); 15 | 16 | st.push(0); //1 value 17 | 18 | int[] nse = new int[n]; 19 | for(int curr = 1; curr < arr.length; curr++) { 20 | 21 | while(!st.isEmpty() && arr[st.peek()] > arr[curr]) { 22 | nse[st.pop()] = arr[curr]; 23 | } 24 | 25 | st.push(curr); 26 | } 27 | 28 | while(!st.isEmpty()) { 29 | nse[st.pop()] = -1; 30 | } 31 | 32 | for(int i = 0; i < n; i++) { 33 | System.out.println(arr[i] + "->" + nse[i]); 34 | } 35 | 36 | System.out.println(st.isEmpty()); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /class14/PreviousGreaterElement.java: -------------------------------------------------------------------------------- 1 | package class14; 2 | 3 | import java.util.Stack; 4 | 5 | public class PreviousGreaterElement { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | int[] arr = { 31, 14, 22, 20, 50}; 11 | 12 | int n = 5; 13 | 14 | Stack st = new Stack<>(); 15 | 16 | st.push(0); // 1 value 17 | 18 | int[] pse = new int[n]; 19 | 20 | pse[0] = -1; 21 | 22 | for (int curr = 1; curr < n; curr++) { 23 | 24 | while (!st.isEmpty() && arr[st.peek()] <= arr[curr]) { 25 | st.pop(); 26 | } 27 | 28 | if (!st.isEmpty()) { 29 | pse[curr] = arr[st.peek()]; 30 | } else { 31 | pse[curr] = -1; 32 | } 33 | 34 | st.push(curr); 35 | } 36 | 37 | for (int i = 0; i < n; i++) { 38 | System.out.println(arr[i] + "->" + pse[i]); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /class14/PreviousSmallerElement.java: -------------------------------------------------------------------------------- 1 | package class14; 2 | 3 | import java.util.Stack; 4 | 5 | public class PreviousSmallerElement { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | int[] arr = { 1, 5, 6, 2, 3, 0}; 11 | 12 | int n = 6; 13 | 14 | Stack st = new Stack<>(); 15 | 16 | st.push(0); // 1 value 17 | 18 | int[] pse = new int[n]; 19 | 20 | pse[0] = -1; 21 | 22 | for(int curr = 1; curr < n; curr++) { 23 | 24 | while(!st.isEmpty() && arr[st.peek()] >= arr[curr]) { 25 | st.pop(); 26 | } 27 | 28 | if(!st.isEmpty()) { 29 | pse[curr] = arr[st.peek()]; 30 | } else { 31 | pse[curr] = -1; 32 | } 33 | 34 | st.push(curr); 35 | } 36 | 37 | for(int i = 0; i < n; i++) { 38 | System.out.println(arr[i] + "->" + pse[i]); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /class15/GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | package class15; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public class GroupAnagrams { 10 | 11 | public static List> groupAnagrams(String[] strs) { 12 | 13 | Map> map = new HashMap<>(); 14 | 15 | for(String currString : strs) { 16 | char[] currStringArray = currString.toCharArray(); 17 | Arrays.sort(currStringArray); 18 | String sortedStringKey = new String(currStringArray); 19 | System.out.println(currString + "->" + sortedStringKey); 20 | if(map.containsKey(sortedStringKey)) { 21 | List anaList = map.get(sortedStringKey); 22 | anaList.add(currString); 23 | map.put(sortedStringKey, anaList); 24 | } else { 25 | List anaList = new ArrayList<>(); 26 | anaList.add(currString); 27 | map.put(sortedStringKey, anaList); 28 | } 29 | } 30 | 31 | System.out.println(map); 32 | 33 | 34 | List> ans = new ArrayList<>(); 35 | ans.addAll(map.values()); 36 | 37 | return ans; 38 | } 39 | 40 | public static void main(String[] args) { 41 | // TODO Auto-generated method stub 42 | 43 | String[] arr = {"eat","tea","tan","ate","nat","bat"}; 44 | groupAnagrams(arr); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /class15/HashMapDemo.java: -------------------------------------------------------------------------------- 1 | package class15; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class HashMapDemo { 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | // country - population 12 | Map freqMap = new HashMap<>(); 13 | 14 | freqMap.put("India", 10); 15 | freqMap.put("Australia", 5); 16 | freqMap.put("England", 4); 17 | 18 | System.out.println(freqMap); 19 | freqMap.put("India", 20);// update(key will be unique) 20 | System.out.println(freqMap); 21 | 22 | // what is the population of india? 23 | // get(key), key = "India" 24 | System.out.println(freqMap.get("India")); 25 | System.out.println(freqMap.get("USA"));// if key is not present then value hai that is null 26 | freqMap.put("USA", 6); 27 | System.out.println(freqMap.get("USA")); 28 | System.out.println(freqMap); 29 | 30 | if (freqMap.containsKey("Russia")) { 31 | System.out.println(freqMap.get("Russia")); 32 | } else { 33 | System.out.println("Russia to hai hi ni!"); 34 | } 35 | 36 | System.out.println(freqMap.keySet()); 37 | for(var entry : freqMap.entrySet()) { 38 | //System.out.println(entry); 39 | System.out.println("entry's key is : " + entry.getKey()); 40 | System.out.println("entry's value is : " + entry.getValue()); 41 | } 42 | 43 | System.out.println("Bringing key set!"); 44 | System.out.println(freqMap.keySet()); 45 | 46 | System.out.println("Iterating over keySet!"); 47 | 48 | for(var key : freqMap.keySet()) { 49 | System.out.println(key + " " + freqMap.get(key)); 50 | } 51 | 52 | System.out.println(freqMap.values()); 53 | 54 | for(var value : freqMap.values()) { 55 | System.out.println(value); 56 | } 57 | 58 | freqMap.remove("USA"); 59 | System.out.println(freqMap); 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /class15/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package class15; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MajorityElement { 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | int[] arr = {2, 2, 1, 1, 1, 2, 2}; 12 | 13 | int n = arr.length; 14 | Map freqMap = new HashMap<>(); 15 | 16 | 17 | for(int e : arr) { 18 | 19 | int value = freqMap.getOrDefault(e, 0); 20 | value++; 21 | freqMap.put(e, value); 22 | // if(freqMap.containsKey(e)) { 23 | // int value = freqMap.get(e); 24 | // value++; 25 | // freqMap.put(e, value); 26 | // } else { 27 | // freqMap.put(e, 1); 28 | // } 29 | } 30 | 31 | System.out.println(freqMap); 32 | 33 | int minVal = n / 2; 34 | 35 | for(int key : freqMap.keySet()) { 36 | if(freqMap.get(key) > minVal) { 37 | System.out.println(key); 38 | } 39 | } 40 | 41 | for(var entry : freqMap.entrySet()) { 42 | if(entry.getValue() > minVal) 43 | System.out.println(entry.getKey()); 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /class15/MiscMapFunctions.java: -------------------------------------------------------------------------------- 1 | package class15; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MiscMapFunctions { 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | //getOrDefault 12 | 13 | Map freqMap = new HashMap<>(); 14 | System.out.println(freqMap.get("USA")); 15 | 16 | if (freqMap.containsKey("USA")) { 17 | System.out.println(freqMap.get("USA")); 18 | } else { 19 | System.out.println("USA to hai hi ni!"); 20 | } 21 | 22 | System.out.println(freqMap.getOrDefault("USA", 0)); 23 | 24 | freqMap.put("USA", 100); 25 | System.out.println(freqMap.getOrDefault("USA", 0)); 26 | freqMap.put("USA", 200); 27 | 28 | System.out.println(freqMap.get("USA"));//200 29 | //putIfAbsent 30 | freqMap.putIfAbsent("USA", 300); 31 | System.out.println(freqMap.get("USA"));//200 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /class15/merge.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 13 | 14 | if(l1 == null && l2 == null) { 15 | return null; 16 | } 17 | 18 | if(l1 == null) { 19 | return l2; 20 | } 21 | 22 | if(l2 == null) { 23 | return l1; 24 | } 25 | ListNode head = new ListNode(); 26 | 27 | ListNode temp = head; 28 | 29 | while(l1 != null && l2 != null) { 30 | if(l1.val < l2.val) { 31 | temp.next = l1; 32 | l1 = l1.next; 33 | } else { 34 | temp.next = l2; 35 | l2 = l2.next; 36 | } 37 | 38 | temp = temp.next; 39 | } 40 | 41 | if(l1 == null) { 42 | temp.next = l2; 43 | } 44 | 45 | if(l2 == null) { 46 | temp.next = l1; 47 | } 48 | 49 | return head.next; 50 | } 51 | } 52 | 53 | 54 | /** 55 | * Definition for singly-linked list. 56 | * public class ListNode { 57 | * int val; 58 | * ListNode next; 59 | * ListNode() {} 60 | * ListNode(int val) { this.val = val; } 61 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 62 | * } 63 | */ 64 | class Solution { 65 | public ListNode removeNthFromEnd(ListNode head, int n) { 66 | ListNode slow = head; 67 | ListNode fast = head; 68 | for (int i = 1; i <= n; i++) {// kth distance 69 | fast = fast.next; 70 | } 71 | 72 | if(fast == null) { 73 | return head.next; 74 | } 75 | // slow and fast ko Same Speed se 76 | while (fast.next != null) { 77 | slow = slow.next; 78 | fast = fast.next; 79 | } 80 | 81 | slow.next = slow.next.next; 82 | 83 | return head; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /class17/BinarySearchUtility.java: -------------------------------------------------------------------------------- 1 | package class17; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BinarySearchUtility { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | int[] arr = {1, 2, 2, 5, 7}; 11 | 12 | int search = 4; 13 | 14 | 15 | int idx = Arrays.binarySearch(arr, search); 16 | //if elem not present 17 | // immediate smaller -> |idx| - 2 L.B 18 | //immediate greater -> |idx| - 1 U.B 19 | if(idx < 0) { 20 | idx = Math.abs(idx) - 2; //Lower bound 21 | } 22 | 23 | System.out.println(arr[idx]); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /class17/BusyMan.java: -------------------------------------------------------------------------------- 1 | package class17; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | import java.util.Scanner; 8 | 9 | public class BusyMan { 10 | 11 | static class Pair { 12 | int startTime; 13 | int endTime; 14 | 15 | public Pair(int startTime, int endTime) { 16 | this.startTime = startTime; 17 | this.endTime = endTime; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | // TODO Auto-generated method stub 23 | return this.startTime + " " + this.endTime; 24 | } 25 | } 26 | public static void main(String[] args) { 27 | // TODO Auto-generated method stub 28 | 29 | 30 | Scanner s = new Scanner(System.in); 31 | int n = s.nextInt(); 32 | 33 | List activities = new ArrayList<>(); 34 | while(n-- != 0) { 35 | 36 | int startTime = s.nextInt(); 37 | int endTime = s.nextInt(); 38 | 39 | Pair activity = new Pair(startTime, endTime); 40 | 41 | activities.add(activity); 42 | } 43 | 44 | //sort activity list on basis of end time 45 | System.out.println(activities); 46 | Collections.sort(activities, new Comparator() { 47 | 48 | @Override 49 | public int compare(Pair o1, Pair o2) { //o1 -> this/current pair, o2 -> current + 1 50 | // TODO Auto-generated method stub 51 | return o1.endTime - o2.endTime; //+ve 52 | } 53 | 54 | }); 55 | 56 | 57 | System.out.println(activities); 58 | //4 5, 5 7, 7 9, 8 9, 0 10, 4 10 59 | int currActivityEnd = activities.get(0).endTime; 60 | int count = 1; 61 | 62 | for(int i = 1; i < activities.size(); i++) { 63 | if(activities.get(i).startTime >= currActivityEnd) { 64 | count++; 65 | currActivityEnd = activities.get(i).endTime; 66 | } 67 | } 68 | 69 | System.out.println(count); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /class17/Car.java: -------------------------------------------------------------------------------- 1 | package class17; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | public class Car { 9 | 10 | int price; 11 | String brand; 12 | int mileage; 13 | 14 | public Car(int price, String brand, int mileage) { 15 | this.price = price; 16 | this.brand = brand; 17 | this.mileage = mileage; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | // TODO Auto-generated method stub 23 | return this.price + " " + this.brand + " " + this.mileage; 24 | } 25 | 26 | 27 | public static void main(String[] args) { 28 | // TODO Auto-generated method stub 29 | 30 | Car c1 = new Car(20000, "Maruti 800", 20); 31 | Car c2 = new Car(20000000, "Audi R8", 5); 32 | Car c3 = new Car(2000000, "Mercedes", 10); 33 | 34 | List carList = new ArrayList<>(); 35 | carList.add(c1); 36 | carList.add(c2); 37 | carList.add(c3); 38 | 39 | System.out.println(carList); 40 | 41 | Collections.sort(carList, new Comparator() { 42 | 43 | @Override 44 | public int compare(Car o1, Car o2) { //o1 -> curr, o2 -> agli 45 | // TODO Auto-generated method stub 46 | return o1.price - o2.price; //+ve -> swap, -ve -> swap ni, 0 -> equal 47 | } 48 | }); 49 | 50 | System.out.println(carList); 51 | Collections.sort(carList, new Comparator() { 52 | 53 | @Override 54 | public int compare(Car o1, Car o2) { //o1 -> curr, o2 -> agli 55 | // TODO Auto-generated method stub 56 | return o2.price - o1.price; //+ve -> swap, -ve -> swap ni, 0 -> equal 57 | } 58 | }); 59 | System.out.println(carList); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /class17/IndianCoinChange.java: -------------------------------------------------------------------------------- 1 | package class17; 2 | 3 | import java.util.Arrays; 4 | 5 | public class IndianCoinChange { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | 10 | int[] currency = {1, 2, 5, 10, 20, 50, 100, 200, 500, 2000}; 11 | 12 | int amount = 39; 13 | 14 | int count = 0; 15 | while(amount > 0) { 16 | int indx = Arrays.binarySearch(currency, amount); 17 | 18 | if(indx < 0) { 19 | 20 | //immediate chota 21 | indx = Math.abs(indx) - 2; 22 | } 23 | 24 | //System.out.print(currency[indx] + "+"); 25 | amount = amount - currency[indx]; 26 | count++; 27 | } 28 | 29 | System.out.println(count); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /class18/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package class18; 2 | 3 | import java.util.Scanner; 4 | 5 | public class BinaryTree { 6 | //3 true 6 true 7 false false true 8 false false true 5 false false 7 | private Scanner sc = new Scanner(System.in); 8 | 9 | private class Node { 10 | int val; 11 | Node left; 12 | Node right; 13 | } 14 | 15 | private Node root; 16 | 17 | public BinaryTree() { 18 | this.root = this.construct(null, true);// 3k 19 | } 20 | 21 | // ilc -> true (left child) 22 | // ilc -> false (right child) 23 | private Node construct(Node parent, boolean ilc) { 24 | 25 | if (parent == null) { 26 | System.out.println("Enter the data for root node!"); 27 | } else { 28 | if (ilc) { 29 | System.out.println("Enter the data for left child of " + parent.val); 30 | } else { 31 | System.out.println("Enter the data for right child of " + parent.val); 32 | } 33 | } 34 | 35 | int data = sc.nextInt(); 36 | 37 | Node node = new Node(); 38 | node.val = data; 39 | 40 | System.out.println("Kya " + node.val + " ka left child hai?"); // 3 41 | boolean kyaLeftHai = sc.nextBoolean(); // true 42 | 43 | if (kyaLeftHai) 44 | node.left = construct(node, true); 45 | 46 | System.out.println("Kya " + node.val + " ka right child hai?"); // 3 47 | boolean kyaRightHai = sc.nextBoolean(); // true 48 | 49 | if (kyaRightHai) 50 | node.right = construct(node, false); 51 | 52 | return node; // 3k 53 | } 54 | 55 | public void display() { 56 | this.display(this.root); 57 | } 58 | 59 | private void display(Node node) { 60 | if (node == null) { 61 | return; 62 | } 63 | 64 | String str = ""; 65 | if (node.left == null) { 66 | str += '_'; 67 | } else { 68 | str += node.left.val; 69 | } 70 | 71 | str += " -> " + node.val + " <- "; 72 | 73 | if (node.right == null) { 74 | str += '_'; 75 | } else { 76 | str += node.right.val; 77 | } 78 | 79 | System.out.println(str); 80 | 81 | display(node.left); 82 | display(node.right); 83 | } 84 | 85 | public int height() { 86 | 87 | return this.height(this.root); 88 | } 89 | 90 | private int height(Node root) { 91 | 92 | if (root == null) { 93 | 94 | return 0; 95 | } 96 | int leftSubTreeKiHeight = height(root.left); 97 | int rightSubTreeKiHeight = height(root.right); 98 | 99 | int max = Math.max(leftSubTreeKiHeight, rightSubTreeKiHeight); 100 | 101 | return max + 1; 102 | } 103 | 104 | public int max() { 105 | 106 | return this.max(this.root); 107 | } 108 | 109 | private int max(Node root) { 110 | 111 | if(root == null) { 112 | return Integer.MIN_VALUE; 113 | } 114 | int leftMax = max(root.left); 115 | int rightMax = max(root.right); 116 | 117 | return Math.max(root.val, Math.max(leftMax, rightMax)); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /class18/BinaryTreeClient.java: -------------------------------------------------------------------------------- 1 | package class18; 2 | 3 | public class BinaryTreeClient { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | BinaryTree bt = new BinaryTree(); 9 | bt.display(); 10 | int height = bt.height(); 11 | System.out.println(height); 12 | 13 | int maxValue = bt.max(); 14 | System.out.println(maxValue); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /class19/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package class19; 2 | 3 | import java.util.Scanner; 4 | 5 | public class BinaryTree { 6 | //3 true 6 true 7 false false true 8 false false true 5 false false 7 | private Scanner sc = new Scanner(System.in); 8 | 9 | private class Node { 10 | int val; 11 | Node left; 12 | Node right; 13 | } 14 | 15 | private Node root; 16 | 17 | public BinaryTree() { 18 | this.root = this.construct(null, true);// 3k 19 | } 20 | 21 | // ilc -> true (left child) 22 | // ilc -> false (right child) 23 | private Node construct(Node parent, boolean ilc) { 24 | 25 | if (parent == null) { 26 | System.out.println("Enter the data for root node!"); 27 | } else { 28 | if (ilc) { 29 | System.out.println("Enter the data for left child of " + parent.val); 30 | } else { 31 | System.out.println("Enter the data for right child of " + parent.val); 32 | } 33 | } 34 | 35 | int data = sc.nextInt(); 36 | 37 | Node node = new Node(); 38 | node.val = data; 39 | 40 | System.out.println("Kya " + node.val + " ka left child hai?"); // 3 41 | boolean kyaLeftHai = sc.nextBoolean(); // true 42 | 43 | if (kyaLeftHai) 44 | node.left = construct(node, true); 45 | 46 | System.out.println("Kya " + node.val + " ka right child hai?"); // 3 47 | boolean kyaRightHai = sc.nextBoolean(); // true 48 | 49 | if (kyaRightHai) 50 | node.right = construct(node, false); 51 | 52 | return node; // 3k 53 | } 54 | 55 | public void display() { 56 | this.display(this.root); 57 | } 58 | 59 | private void display(Node node) { 60 | if (node == null) { 61 | return; 62 | } 63 | 64 | String str = ""; 65 | if (node.left == null) { 66 | str += '_'; 67 | } else { 68 | str += node.left.val; 69 | } 70 | 71 | str += " -> " + node.val + " <- "; 72 | 73 | if (node.right == null) { 74 | str += '_'; 75 | } else { 76 | str += node.right.val; 77 | } 78 | 79 | System.out.println(str); 80 | 81 | display(node.left); 82 | display(node.right); 83 | } 84 | 85 | public int height() { 86 | 87 | return this.height(this.root); 88 | } 89 | 90 | private int height(Node root) { 91 | 92 | if (root == null) { 93 | 94 | return 0; 95 | } 96 | int leftSubTreeKiHeight = height(root.left); 97 | int rightSubTreeKiHeight = height(root.right); 98 | 99 | int max = Math.max(leftSubTreeKiHeight, rightSubTreeKiHeight); 100 | 101 | return max + 1; 102 | } 103 | 104 | public int max() { 105 | 106 | return this.max(this.root); 107 | } 108 | 109 | private int max(Node root) { 110 | 111 | if(root == null) { 112 | return Integer.MIN_VALUE; 113 | } 114 | int leftMax = max(root.left); 115 | int rightMax = max(root.right); 116 | 117 | return Math.max(root.val, Math.max(leftMax, rightMax)); 118 | } 119 | 120 | public void preOrder() { 121 | // TODO Auto-generated method stub 122 | 123 | this.preOrder(this.root); 124 | } 125 | 126 | private void preOrder(Node root) { 127 | // TODO Auto-generated method stub 128 | 129 | if(root == null) { 130 | return; 131 | } 132 | System.out.println(root.val); 133 | preOrder(root.left); 134 | preOrder(root.right); 135 | } 136 | 137 | public void inOrder() { 138 | // TODO Auto-generated method stub 139 | 140 | this.inOrder(this.root); 141 | } 142 | 143 | private void inOrder(Node root) { 144 | // TODO Auto-generated method stub 145 | 146 | if(root == null) { 147 | return; 148 | } 149 | 150 | inOrder(root.left); 151 | System.out.println(root.val); 152 | inOrder(root.right); 153 | } 154 | 155 | public void postOrder() { 156 | // TODO Auto-generated method stub 157 | 158 | this.postOrder(this.root); 159 | } 160 | 161 | private void postOrder(Node root) { 162 | // TODO Auto-generated method stub 163 | 164 | if(root == null) { 165 | return; 166 | } 167 | 168 | postOrder(root.left); 169 | 170 | postOrder(root.right); 171 | System.out.println(root.val); 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /class19/BinaryTreeClient.java: -------------------------------------------------------------------------------- 1 | package class19; 2 | 3 | public class BinaryTreeClient { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | BinaryTree bt = new BinaryTree(); 9 | //bt.display(); 10 | //int height = bt.height(); 11 | // System.out.println(height); 12 | // 13 | // int maxValue = bt.max(); 14 | // System.out.println(maxValue); 15 | bt.preOrder(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /class19/PathSum.java: -------------------------------------------------------------------------------- 1 | package class19; 2 | 3 | public class PathSum { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | 25 | public boolean hasPathSum(TreeNode root, int targetSum) { 26 | 27 | if (root == null) { 28 | return false; 29 | } 30 | 31 | if (root.left == null && root.right == null && (targetSum - root.val == 0)) { 32 | return true; 33 | } 34 | boolean left = hasPathSum(root.left, targetSum - root.val); 35 | boolean right = hasPathSum(root.right, targetSum - root.val); 36 | 37 | return left || right; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /class2/AllIndices.java: -------------------------------------------------------------------------------- 1 | package class2; 2 | 3 | public class AllIndices { 4 | 5 | public static int[] sol(int[] arr, int ci, int n, int search, int count) { 6 | 7 | if(ci == n) { 8 | int[] bca = new int[count]; 9 | return bca; 10 | } 11 | 12 | if(arr[ci] == search) { 13 | int[] ra = sol(arr, ci + 1, n, search, count + 1); 14 | ra[count] = ci; 15 | return ra; 16 | } else { 17 | int[] ra = sol(arr, ci + 1, n, search, count); 18 | return ra; 19 | } 20 | 21 | } 22 | public static void main(String[] args) { 23 | // TODO Auto-generated method stub 24 | 25 | int[] arr = { 1, 2, 4, 2, 6 }; 26 | int n = 5; 27 | int[] ans = sol(arr, 0, n, 7, 0); 28 | if(ans.length == 0) { 29 | System.out.println(-1); 30 | return; 31 | } 32 | for(int index : ans) { 33 | System.out.print(index + " "); 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /class2/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package class2; 2 | 3 | public class FibonacciNumber { 4 | 5 | private static int sol(int n) { 6 | // TODO Auto-generated method stub 7 | 8 | if(n == 0 || n == 1) { 9 | return n; 10 | } 11 | 12 | int c1 = sol(n - 1); 13 | int c2 = sol(n - 2); 14 | 15 | int meraAnswer = c1 + c2; 16 | return meraAnswer; 17 | } 18 | public static void main(String[] args) { 19 | // TODO Auto-generated method stub 20 | System.out.println(sol(4)); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /class2/FirstOccurence.java: -------------------------------------------------------------------------------- 1 | package class2; 2 | 3 | public class FirstOccurence { 4 | 5 | private static int sol(int[] arr, int ci, int search, int n) { 6 | // TODO Auto-generated method stub 7 | 8 | if (ci == n) { 9 | return -1; 10 | } 11 | if (arr[ci] == search) { 12 | return ci; 13 | } 14 | 15 | int recAns = sol(arr, ci + 1, search, n); 16 | return recAns; 17 | } 18 | 19 | public static void main(String[] args) { 20 | // TODO Auto-generated method stub 21 | int[] arr = { 1, 2, 4, 2, 6 }; 22 | int n = 5; 23 | 24 | System.out.println(sol(arr, 0, 7, n)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /class2/StairWays.java: -------------------------------------------------------------------------------- 1 | package class2; 2 | 3 | public class StairWays { 4 | 5 | private static int sol(int n) { 6 | // TODO Auto-generated method stub 7 | 8 | if(n == 0 || n == 1) { 9 | return 1; 10 | } 11 | int c1 = sol(n - 1); 12 | int c2 = sol(n - 2); 13 | 14 | int totalWays = c1 + c2; 15 | return totalWays; 16 | } 17 | public static void main(String[] args) { 18 | // TODO Auto-generated method stub 19 | System.out.println(sol(2)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /class20/ArrayListDemo.java: -------------------------------------------------------------------------------- 1 | package class20; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ArrayListDemo { 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | List ram = new ArrayList<>(); 12 | ram.add(1); 13 | ram.add(2); 14 | List shyam = ram; 15 | System.out.println(shyam); 16 | System.out.println(ram); 17 | ram.remove(ram.size() - 1); 18 | System.out.println(shyam); 19 | System.out.println(ram); 20 | 21 | 22 | List> badi = new ArrayList<>(); 23 | 24 | List list1 = new ArrayList<>(); 25 | 26 | List list2 = new ArrayList<>(); 27 | 28 | badi.add(list1); 29 | badi.add(list2); 30 | 31 | System.out.println(list1); 32 | System.out.println(list2); 33 | System.out.println(badi); 34 | 35 | list1.add(10); 36 | 37 | list1.add(20); 38 | System.out.println(list1); 39 | System.out.println(list2); 40 | System.out.println(badi); 41 | 42 | List list3 = new ArrayList<>(list1); 43 | badi.add(list3); 44 | list1.remove(list1.size() - 1); 45 | System.out.println(list1); 46 | System.out.println(list2); 47 | System.out.println(badi); 48 | 49 | 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /class20/DiameterOne.java: -------------------------------------------------------------------------------- 1 | package class20; 2 | 3 | public class DiameterOne { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | 25 | class Pair { 26 | int height; 27 | int diameter; 28 | 29 | public Pair(int height, int diameter) { 30 | this.height = height; 31 | this.diameter = diameter; 32 | } 33 | } 34 | 35 | public int diameterOfBinaryTree(TreeNode root) { 36 | 37 | Pair ansPair = diameterOfBinaryTreee(root); 38 | return ansPair.diameter; 39 | } 40 | 41 | public Pair diameterOfBinaryTreee(TreeNode root) { 42 | 43 | if (root == null) { 44 | return new Pair(0, 0); 45 | } 46 | 47 | Pair leftPair = diameterOfBinaryTreee(root.left);// 6 48 | Pair rightPair = diameterOfBinaryTreee(root.right);// 0 49 | 50 | int apniHeight = Math.max(leftPair.height, rightPair.height) + 1; 51 | int apnaDia = leftPair.height + rightPair.height; 52 | 53 | int maxDia = Math.max(apnaDia, Math.max(leftPair.diameter, rightPair.diameter)); 54 | 55 | return new Pair(apniHeight, maxDia); 56 | } 57 | 58 | public static void main(String[] args) { 59 | // TODO Auto-generated method stub 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /class20/DiameterTwo.java: -------------------------------------------------------------------------------- 1 | package class20; 2 | 3 | public class DiameterTwo { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | 25 | public int diameterOfBinaryTree(TreeNode root) { 26 | 27 | if (root == null) { 28 | return 0; 29 | } 30 | int currNodeLeftHeight = height(root.left); 31 | int currNodeRightHeight = height(root.right); 32 | 33 | int currPath = currNodeLeftHeight + currNodeRightHeight;// 5 34 | 35 | int leftPath = diameterOfBinaryTree(root.left);// 6 36 | int rightPath = diameterOfBinaryTree(root.right);// 0 37 | 38 | return Math.max(currPath, Math.max(leftPath, rightPath)); 39 | } 40 | 41 | private int height(TreeNode root) { 42 | 43 | if (root == null) { 44 | 45 | return 0; 46 | } 47 | int leftSubTreeKiHeight = height(root.left); 48 | int rightSubTreeKiHeight = height(root.right); 49 | 50 | int max = Math.max(leftSubTreeKiHeight, rightSubTreeKiHeight); 51 | 52 | return max + 1; 53 | } 54 | 55 | public static void main(String[] args) { 56 | // TODO Auto-generated method stub 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /class20/PathSum2.java: -------------------------------------------------------------------------------- 1 | package class20; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class PathSum2 { 7 | 8 | // Definition for a binary tree node. 9 | public class TreeNode { 10 | int val; 11 | TreeNode left; 12 | TreeNode right; 13 | 14 | TreeNode() { 15 | } 16 | 17 | TreeNode(int val) { 18 | this.val = val; 19 | } 20 | 21 | TreeNode(int val, TreeNode left, TreeNode right) { 22 | this.val = val; 23 | this.left = left; 24 | this.right = right; 25 | } 26 | } 27 | 28 | public List> pathSum(TreeNode root, int targetSum) { 29 | 30 | List currPath = new ArrayList<>(); 31 | 32 | List> allPaths = new ArrayList<>(); 33 | pathSum(root, targetSum, currPath, allPaths); 34 | return allPaths; 35 | } 36 | 37 | public void pathSum(TreeNode root, int targetSum, List currPath, List> allPaths) { 38 | 39 | if (root == null) { 40 | return; 41 | } 42 | 43 | if (root.left == null && root.right == null && targetSum - root.val == 0) { 44 | currPath.add(root.val); 45 | allPaths.add(new ArrayList<>(currPath)); 46 | currPath.remove(currPath.size() - 1); 47 | return; 48 | } 49 | 50 | currPath.add(root.val); 51 | pathSum(root.left, targetSum - root.val, currPath, allPaths); 52 | pathSum(root.right, targetSum - root.val, currPath, allPaths); 53 | currPath.remove(currPath.size() - 1); 54 | } 55 | 56 | public static void main(String[] args) { 57 | // TODO Auto-generated method stub 58 | 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /class21/BalancedBTBottomUp.java: -------------------------------------------------------------------------------- 1 | package class21; 2 | 3 | public class BalancedBTBottomUp { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | 25 | class Pair { 26 | int height; 27 | boolean isBalanced; 28 | 29 | public Pair(int height, boolean isBalanced) { 30 | this.height = height; 31 | this.isBalanced = isBalanced; 32 | } 33 | } 34 | 35 | public Pair isBalance(TreeNode root) { 36 | 37 | if (root == null) { 38 | return new Pair(0, true); 39 | } 40 | 41 | Pair left = isBalance(root.left); 42 | Pair right = isBalance(root.right); 43 | 44 | int apnaDiff = Math.abs(left.height - right.height); 45 | int apniHeight = Math.max(left.height, right.height) + 1; 46 | 47 | boolean kyaBalancedHai = apnaDiff <= 1 && left.isBalanced && right.isBalanced; 48 | return new Pair(apniHeight, kyaBalancedHai); 49 | } 50 | 51 | public static void main(String[] args) { 52 | // TODO Auto-generated method stub 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /class21/BalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | package class21; 2 | 3 | public class BalancedBinaryTree { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | 25 | private int height(TreeNode root) { 26 | 27 | if (root == null) { 28 | 29 | return 0; 30 | } 31 | int leftSubTreeKiHeight = height(root.left); 32 | int rightSubTreeKiHeight = height(root.right); 33 | 34 | int max = Math.max(leftSubTreeKiHeight, rightSubTreeKiHeight); 35 | 36 | return max + 1; 37 | } 38 | 39 | public boolean isBalanced(TreeNode root) { 40 | 41 | if (root == null) { 42 | return true; 43 | } 44 | int leftHeight = height(root.left); 45 | int rightHeight = height(root.right); 46 | 47 | int diff = Math.abs(leftHeight - rightHeight); 48 | 49 | // if(diff <= 1) { 50 | // boolean left = isBalanced(root.left); 51 | // boolean right = isBalanced(root.right); 52 | // 53 | // return left && right; 54 | // } else { 55 | // return false; 56 | // } 57 | 58 | return diff <= 1 && isBalanced(root.left) && isBalanced(root.right); 59 | } 60 | 61 | public static void main(String[] args) { 62 | // TODO Auto-generated method stub 63 | 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /class21/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package class21; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Queue; 7 | import java.util.Scanner; 8 | 9 | public class BinaryTree { 10 | //3 true 6 true 7 false false true 8 false false true 5 false false 11 | private Scanner sc = new Scanner(System.in); 12 | 13 | private class Node { 14 | int val; 15 | Node left; 16 | Node right; 17 | } 18 | 19 | private Node root; 20 | 21 | public BinaryTree() { 22 | this.root = this.construct(null, true);// 3k 23 | } 24 | 25 | // ilc -> true (left child) 26 | // ilc -> false (right child) 27 | private Node construct(Node parent, boolean ilc) { 28 | 29 | if (parent == null) { 30 | System.out.println("Enter the data for root node!"); 31 | } else { 32 | if (ilc) { 33 | System.out.println("Enter the data for left child of " + parent.val); 34 | } else { 35 | System.out.println("Enter the data for right child of " + parent.val); 36 | } 37 | } 38 | 39 | int data = sc.nextInt(); 40 | 41 | Node node = new Node(); 42 | node.val = data; 43 | 44 | System.out.println("Kya " + node.val + " ka left child hai?"); // 3 45 | boolean kyaLeftHai = sc.nextBoolean(); // true 46 | 47 | if (kyaLeftHai) 48 | node.left = construct(node, true); 49 | 50 | System.out.println("Kya " + node.val + " ka right child hai?"); // 3 51 | boolean kyaRightHai = sc.nextBoolean(); // true 52 | 53 | if (kyaRightHai) 54 | node.right = construct(node, false); 55 | 56 | return node; // 3k 57 | } 58 | 59 | public void display() { 60 | this.display(this.root); 61 | } 62 | 63 | private void display(Node node) { 64 | if (node == null) { 65 | return; 66 | } 67 | 68 | String str = ""; 69 | if (node.left == null) { 70 | str += '_'; 71 | } else { 72 | str += node.left.val; 73 | } 74 | 75 | str += " -> " + node.val + " <- "; 76 | 77 | if (node.right == null) { 78 | str += '_'; 79 | } else { 80 | str += node.right.val; 81 | } 82 | 83 | System.out.println(str); 84 | 85 | display(node.left); 86 | display(node.right); 87 | } 88 | 89 | public int height() { 90 | 91 | return this.height(this.root); 92 | } 93 | 94 | private int height(Node root) { 95 | 96 | if (root == null) { 97 | 98 | return 0; 99 | } 100 | int leftSubTreeKiHeight = height(root.left); 101 | int rightSubTreeKiHeight = height(root.right); 102 | int max = Math.max(leftSubTreeKiHeight, rightSubTreeKiHeight); 103 | 104 | return max + 1; 105 | } 106 | 107 | public int max() { 108 | 109 | return this.max(this.root); 110 | } 111 | 112 | private int max(Node root) { 113 | 114 | if(root == null) { 115 | return Integer.MIN_VALUE; 116 | } 117 | int leftMax = max(root.left); 118 | int rightMax = max(root.right); 119 | 120 | return Math.max(root.val, Math.max(leftMax, rightMax)); 121 | } 122 | 123 | public void lvlOrder() { 124 | this.lvlOrder(this.root); 125 | } 126 | 127 | private void lvlOrder(Node root) { 128 | 129 | Queue bfs = new LinkedList<>(); 130 | 131 | bfs.add(root); 132 | List> ans = new ArrayList<>(); 133 | while(!bfs.isEmpty()) { 134 | 135 | List currLvl = new ArrayList<>(); 136 | int numNodesAtCurrLvl = bfs.size();//2 137 | 138 | for(int i = 0; i < numNodesAtCurrLvl; i++) {//0, 1 139 | Node front = bfs.poll(); 140 | currLvl.add(front.val); 141 | 142 | if(front.left != null) { 143 | bfs.add(front.left); 144 | } 145 | 146 | if(front.right != null) { 147 | bfs.add(front.right); 148 | } 149 | } 150 | 151 | ans.add(currLvl); 152 | } 153 | 154 | System.out.println(ans); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /class21/BinaryTreeClient.java: -------------------------------------------------------------------------------- 1 | package class21; 2 | 3 | public class BinaryTreeClient { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | BinaryTree bt = new BinaryTree(); 9 | bt.display(); 10 | // int height = bt.height(); 11 | // System.out.println(height); 12 | // 13 | // int maxValue = bt.max(); 14 | // System.out.println(maxValue); 15 | bt.lvlOrder(); 16 | 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /class21/RightView.java: -------------------------------------------------------------------------------- 1 | package class21; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import class21.BalancedBinaryTree.TreeNode; 7 | 8 | public class RightView { 9 | 10 | static int maxLvl; 11 | 12 | public List rightSideView(TreeNode root) { 13 | 14 | maxLvl = 0; 15 | List ans = new ArrayList<>(); 16 | rightSideView(root, 1, ans); 17 | return ans; 18 | } 19 | 20 | public void rightSideView(TreeNode root, int lvl, List ans) { 21 | if (root == null) { 22 | return; 23 | } 24 | 25 | if (maxLvl < lvl) { 26 | ans.add(root.val); 27 | System.out.println(root.val); 28 | maxLvl = lvl; 29 | } 30 | 31 | rightSideView(root.right, lvl + 1, ans); 32 | rightSideView(root.left, lvl + 1, ans); 33 | } 34 | public static void main(String[] args) { 35 | // TODO Auto-generated method stub 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /class22/BinaryTree.java: -------------------------------------------------------------------------------- 1 | package class22; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.Queue; 8 | import java.util.Scanner; 9 | import java.util.TreeMap; 10 | 11 | public class BinaryTree { 12 | //3 true 6 true 7 false false true 8 false false true 5 false false 13 | private Scanner sc = new Scanner(System.in); 14 | 15 | private class Node { 16 | int val; 17 | Node left; 18 | Node right; 19 | } 20 | 21 | private Node root; 22 | 23 | public BinaryTree() { 24 | this.root = this.construct(null, true);// 3k 25 | } 26 | 27 | // ilc -> true (left child) 28 | // ilc -> false (right child) 29 | private Node construct(Node parent, boolean ilc) { 30 | 31 | if (parent == null) { 32 | System.out.println("Enter the data for root node!"); 33 | } else { 34 | if (ilc) { 35 | System.out.println("Enter the data for left child of " + parent.val); 36 | } else { 37 | System.out.println("Enter the data for right child of " + parent.val); 38 | } 39 | } 40 | 41 | int data = sc.nextInt(); 42 | 43 | Node node = new Node(); 44 | node.val = data; 45 | 46 | System.out.println("Kya " + node.val + " ka left child hai?"); // 3 47 | boolean kyaLeftHai = sc.nextBoolean(); // true 48 | 49 | if (kyaLeftHai) 50 | node.left = construct(node, true); 51 | 52 | System.out.println("Kya " + node.val + " ka right child hai?"); // 3 53 | boolean kyaRightHai = sc.nextBoolean(); // true 54 | 55 | if (kyaRightHai) 56 | node.right = construct(node, false); 57 | 58 | return node; // 3k 59 | } 60 | 61 | public void display() { 62 | this.display(this.root); 63 | } 64 | 65 | private void display(Node node) { 66 | if (node == null) { 67 | return; 68 | } 69 | 70 | String str = ""; 71 | if (node.left == null) { 72 | str += '_'; 73 | } else { 74 | str += node.left.val; 75 | } 76 | 77 | str += " -> " + node.val + " <- "; 78 | 79 | if (node.right == null) { 80 | str += '_'; 81 | } else { 82 | str += node.right.val; 83 | } 84 | 85 | System.out.println(str); 86 | 87 | display(node.left); 88 | display(node.right); 89 | } 90 | 91 | public int height() { 92 | 93 | return this.height(this.root); 94 | } 95 | 96 | private int height(Node root) { 97 | 98 | if (root == null) { 99 | 100 | return 0; 101 | } 102 | int leftSubTreeKiHeight = height(root.left); 103 | int rightSubTreeKiHeight = height(root.right); 104 | 105 | int max = Math.max(leftSubTreeKiHeight, rightSubTreeKiHeight); 106 | 107 | return max + 1; 108 | } 109 | 110 | public int max() { 111 | 112 | return this.max(this.root); 113 | } 114 | 115 | private int max(Node root) { 116 | 117 | if (root == null) { 118 | return Integer.MIN_VALUE; 119 | } 120 | int leftMax = max(root.left); 121 | int rightMax = max(root.right); 122 | 123 | return Math.max(root.val, Math.max(leftMax, rightMax)); 124 | } 125 | 126 | public void preOrder() { 127 | // TODO Auto-generated method stub 128 | 129 | this.preOrder(this.root); 130 | } 131 | 132 | private void preOrder(Node root) { 133 | // TODO Auto-generated method stub 134 | 135 | if (root == null) { 136 | return; 137 | } 138 | System.out.println(root.val); 139 | preOrder(root.left); 140 | preOrder(root.right); 141 | } 142 | 143 | public void inOrder() { 144 | // TODO Auto-generated method stub 145 | 146 | this.inOrder(this.root); 147 | } 148 | 149 | private void inOrder(Node root) { 150 | // TODO Auto-generated method stub 151 | 152 | if (root == null) { 153 | return; 154 | } 155 | 156 | inOrder(root.left); 157 | System.out.println(root.val); 158 | inOrder(root.right); 159 | } 160 | 161 | public void postOrder() { 162 | // TODO Auto-generated method stub 163 | 164 | this.postOrder(this.root); 165 | } 166 | 167 | private void postOrder(Node root) { 168 | // TODO Auto-generated method stub 169 | 170 | if (root == null) { 171 | return; 172 | } 173 | 174 | postOrder(root.left); 175 | 176 | postOrder(root.right); 177 | System.out.println(root.val); 178 | } 179 | 180 | public void verticalTraversal() { 181 | 182 | this.verticalTraversal(this.root); 183 | } 184 | 185 | class Pair { 186 | int stickLvl; 187 | Node node; 188 | 189 | public Pair(int stickLvl, Node node) { 190 | this.stickLvl = stickLvl; 191 | this.node = node; 192 | } 193 | } 194 | 195 | private void verticalTraversal(Node root) { 196 | 197 | Queue bfs = new LinkedList<>(); 198 | 199 | bfs.add(new Pair(0, root)); 200 | 201 | Map> map = new TreeMap<>(); 202 | 203 | while (!bfs.isEmpty()) { 204 | 205 | Pair front = bfs.poll(); 206 | 207 | int stickLvl = front.stickLvl; 208 | Node curr = front.node; 209 | 210 | List value = map.getOrDefault(stickLvl, new ArrayList<>()); 211 | value.add(curr.val); 212 | 213 | map.put(stickLvl, value); 214 | 215 | if (curr.left != null) { 216 | bfs.add(new Pair(stickLvl - 1, curr.left)); 217 | } 218 | 219 | if (curr.right != null) { 220 | bfs.add(new Pair(stickLvl + 1, curr.right)); 221 | } 222 | } 223 | 224 | System.out.println(map.values()); 225 | 226 | } 227 | 228 | public void verticalTraversalTop() { 229 | 230 | this.verticalTraversalTop(this.root); 231 | } 232 | 233 | private void verticalTraversalTop(Node root) { 234 | 235 | Queue bfs = new LinkedList<>(); 236 | 237 | bfs.add(new Pair(0, root)); 238 | 239 | Map> map = new TreeMap<>(); 240 | 241 | while (!bfs.isEmpty()) { 242 | 243 | Pair front = bfs.poll(); 244 | 245 | int stickLvl = front.stickLvl; 246 | Node curr = front.node; 247 | 248 | List value = map.getOrDefault(stickLvl, new ArrayList<>()); 249 | value.add(curr.val); 250 | 251 | map.put(stickLvl, value); 252 | 253 | if (curr.left != null) { 254 | bfs.add(new Pair(stickLvl - 1, curr.left)); 255 | } 256 | 257 | if (curr.right != null) { 258 | bfs.add(new Pair(stickLvl + 1, curr.right)); 259 | } 260 | } 261 | 262 | for (List lvl : map.values()) { 263 | System.out.println(lvl.get(lvl.size() - 1));// case bottom ka -> lvl.size() - 1 264 | } 265 | 266 | } 267 | 268 | } 269 | -------------------------------------------------------------------------------- /class22/PreInBuild.java: -------------------------------------------------------------------------------- 1 | package class22; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class PreInBuild { 7 | 8 | // Definition for a binary tree node. 9 | public class TreeNode { 10 | int val; 11 | TreeNode left; 12 | TreeNode right; 13 | 14 | TreeNode() { 15 | } 16 | 17 | TreeNode(int val) { 18 | this.val = val; 19 | } 20 | 21 | TreeNode(int val, TreeNode left, TreeNode right) { 22 | this.val = val; 23 | this.left = left; 24 | this.right = right; 25 | } 26 | } 27 | 28 | int preOrderIter; 29 | Map inOrdMapping; 30 | public TreeNode buildTree(int[] preorder, int[] inorder) { 31 | 32 | preOrderIter = 0; 33 | inOrdMapping = new HashMap<>(); 34 | 35 | for(int i = 0; i < inorder.length; i++) { 36 | inOrdMapping.put(inorder[i], i); //element - index pair 37 | } 38 | 39 | return buildTree(preorder, 0, preorder.length - 1); 40 | } 41 | //left -> 0, right -> preOrder.le - 1 42 | public TreeNode buildTree(int[] preorder, int left, int right) { 43 | 44 | if(left > right) { 45 | return null; 46 | } 47 | int rootVal = preorder[preOrderIter++]; 48 | TreeNode root = new TreeNode(rootVal); 49 | 50 | int rootIndex = inOrdMapping.get(rootVal); 51 | 52 | //left - [0, rootIndex - 1], right - [rootIndex + 1, ] 53 | 54 | root.left = buildTree(preorder, left, rootIndex - 1); 55 | root.right = buildTree(preorder, rootIndex + 1, right); 56 | 57 | return root; 58 | } 59 | 60 | public static void main(String[] args) { 61 | // TODO Auto-generated method stub 62 | 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /class22/VerticalOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package class22; 2 | 3 | public class VerticalOrderTraversal { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | 9 | BinaryTree bt = new BinaryTree(); 10 | bt.verticalTraversalTop(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /class23/BSTClient.java: -------------------------------------------------------------------------------- 1 | package class23; 2 | 3 | public class BSTClient { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | int[] in = {10, 20, 30, 40, 50, 60, 70}; 9 | 10 | BinarySearchTree bst = new BinarySearchTree(in); 11 | bst.display(); 12 | bst.replaceWithLarger(); 13 | System.out.println("_--------------------------"); 14 | 15 | 16 | bst.display(); 17 | //System.out.println(bst.max()); 18 | //System.out.println(bst.find(45)); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /class23/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package class23; 2 | 3 | public class BinarySearchTree { 4 | 5 | private class Node { 6 | int val; 7 | Node left; 8 | Node right; 9 | } 10 | 11 | private Node root; 12 | 13 | public BinarySearchTree(int[] in) { 14 | this.root = construct(in, 0, in.length - 1); 15 | } 16 | 17 | private Node construct(int[] in, int l, int r) { 18 | // TODO Auto-generated method stub 19 | 20 | if (l > r) { 21 | return null; 22 | } 23 | int mid = (l + r) / 2; 24 | Node node = new Node(); 25 | node.val = in[mid]; 26 | 27 | node.left = construct(in, l, mid - 1); // left sub tree 28 | 29 | node.right = construct(in, mid + 1, r); // right sub tree 30 | 31 | return node; 32 | } 33 | 34 | public void display() { 35 | this.display(this.root); 36 | } 37 | 38 | private void display(Node node) { 39 | if (node == null) { 40 | return; 41 | } 42 | 43 | String str = ""; 44 | if (node.left == null) { 45 | str += '_'; 46 | } else { 47 | str += node.left.val; 48 | } 49 | 50 | str += " -> " + node.val + " <- "; 51 | 52 | if (node.right == null) { 53 | str += '_'; 54 | } else { 55 | str += node.right.val; 56 | } 57 | 58 | System.out.println(str); 59 | 60 | display(node.left); 61 | display(node.right); 62 | } 63 | 64 | public int max() { 65 | return this.max(this.root); 66 | } 67 | 68 | private int max(Node root) { 69 | // TODO Auto-generated method stub 70 | 71 | if (root.right == null) { 72 | return root.val; 73 | } 74 | return max(root.right); 75 | } 76 | 77 | public boolean find(int target) { 78 | return this.find(this.root, target); 79 | } 80 | 81 | private boolean find(Node root, int target) { 82 | // TODO Auto-generated method stub 83 | 84 | if (root == null) { 85 | return false; 86 | } 87 | if (root.val > target) { 88 | return find(root.left, target); 89 | } else if (root.val < target) { 90 | return find(root.right, target); 91 | } else { 92 | return true; 93 | } 94 | } 95 | 96 | int sum = 0; 97 | 98 | public void replaceWithLarger() { 99 | // TODO Auto-generated method stub 100 | 101 | replaceWithLarger(this.root); 102 | } 103 | 104 | private void replaceWithLarger(Node root) { 105 | if (root == null) { 106 | return; 107 | } 108 | // right self left 109 | 110 | replaceWithLarger(root.right); 111 | 112 | int temp = root.val; 113 | root.val = sum; 114 | sum = sum + temp; 115 | 116 | replaceWithLarger(root.left); 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /class24/AddInBST.java: -------------------------------------------------------------------------------- 1 | package class24; 2 | 3 | public class AddInBST { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | 25 | public TreeNode insertIntoBST(TreeNode root, int val) { 26 | 27 | if(root == null) { 28 | TreeNode node = new TreeNode(val); 29 | root = node; 30 | } else { 31 | insert(root, val); 32 | } 33 | 34 | return root; 35 | } 36 | 37 | public void insert(TreeNode root, int val) { 38 | if (val < root.val) { 39 | 40 | if (root.left != null) { 41 | insert(root.left, val); 42 | } else { 43 | TreeNode node = new TreeNode(val); 44 | root.left = node; 45 | } 46 | } else if (val > root.val) { 47 | 48 | if (root.right != null) { 49 | insert(root.right, val); 50 | } else { 51 | TreeNode node = new TreeNode(val); 52 | root.right = node; 53 | } 54 | } 55 | } 56 | 57 | public static void main(String[] args) { 58 | // TODO Auto-generated method stub 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /class24/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package class24; 2 | 3 | public class BinarySearchTree { 4 | 5 | private class Node { 6 | int val; 7 | Node left; 8 | Node right; 9 | } 10 | 11 | private Node root; 12 | 13 | public BinarySearchTree(int[] in) { 14 | this.root = construct(in, 0, in.length - 1); 15 | } 16 | 17 | private Node construct(int[] in, int l, int r) { 18 | // TODO Auto-generated method stub 19 | 20 | if (l > r) { 21 | return null; 22 | } 23 | int mid = (l + r) / 2; 24 | Node node = new Node(); 25 | node.val = in[mid]; 26 | 27 | node.left = construct(in, l, mid - 1); // left sub tree 28 | 29 | node.right = construct(in, mid + 1, r); // right sub tree 30 | 31 | return node; 32 | } 33 | 34 | public void display() { 35 | this.display(this.root); 36 | } 37 | 38 | private void display(Node node) { 39 | if (node == null) { 40 | return; 41 | } 42 | 43 | String str = ""; 44 | if (node.left == null) { 45 | str += '_'; 46 | } else { 47 | str += node.left.val; 48 | } 49 | 50 | str += " -> " + node.val + " <- "; 51 | 52 | if (node.right == null) { 53 | str += '_'; 54 | } else { 55 | str += node.right.val; 56 | } 57 | 58 | System.out.println(str); 59 | 60 | display(node.left); 61 | display(node.right); 62 | } 63 | 64 | public int max() { 65 | return this.max(this.root); 66 | } 67 | 68 | private int max(Node root) { 69 | // TODO Auto-generated method stub 70 | 71 | if (root.right == null) { 72 | return root.val; 73 | } 74 | return max(root.right); 75 | } 76 | 77 | public boolean find(int target) { 78 | return this.find(this.root, target); 79 | } 80 | 81 | private boolean find(Node root, int target) { 82 | // TODO Auto-generated method stub 83 | 84 | if (root == null) { 85 | return false; 86 | } 87 | if (root.val > target) { 88 | return find(root.left, target); 89 | } else if (root.val < target) { 90 | return find(root.right, target); 91 | } else { 92 | return true; 93 | } 94 | } 95 | 96 | int sum = 0; 97 | 98 | public void replaceWithLarger() { 99 | // TODO Auto-generated method stub 100 | 101 | replaceWithLarger(this.root); 102 | } 103 | 104 | private void replaceWithLarger(Node root) { 105 | if (root == null) { 106 | return; 107 | } 108 | // right self left 109 | 110 | replaceWithLarger(root.right); 111 | 112 | int temp = root.val; 113 | root.val = sum; 114 | sum = sum + temp; 115 | 116 | replaceWithLarger(root.left); 117 | } 118 | 119 | public void printInRange(int low, int high) { 120 | // TODO Auto-generated method stub 121 | 122 | this.printInRange(this.root, low, high); 123 | } 124 | 125 | private void printInRange(Node root, int low, int high) { 126 | // TODO Auto-generated method stub 127 | 128 | if (root == null) { 129 | return; 130 | } 131 | if (root.val < low) { 132 | printInRange(root.right, low, high); 133 | } else if (root.val > high) { 134 | printInRange(root.left, low, high); 135 | } else {// inside range 136 | 137 | printInRange(root.left, low, high); 138 | System.out.println(root.val); 139 | printInRange(root.right, low, high); 140 | } 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /class24/DeleteInBST.java: -------------------------------------------------------------------------------- 1 | package class24; 2 | 3 | import class24.AddInBST.TreeNode; 4 | 5 | public class DeleteInBST { 6 | 7 | // Definition for a binary tree node. 8 | public class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | 13 | TreeNode() { 14 | } 15 | 16 | TreeNode(int val) { 17 | this.val = val; 18 | } 19 | 20 | TreeNode(int val, TreeNode left, TreeNode right) { 21 | this.val = val; 22 | this.left = left; 23 | this.right = right; 24 | } 25 | } 26 | 27 | private int min(TreeNode root) { 28 | // TODO Auto-generated method stub 29 | 30 | if (root.left == null) { 31 | return root.val; 32 | } 33 | return min(root.left); 34 | } 35 | 36 | public TreeNode deleteNode(TreeNode root, int key) { 37 | 38 | if (root == null) { 39 | return null; 40 | } 41 | 42 | if (key < root.val) { 43 | root.left = deleteNode(root.left, key); 44 | } else if (key > root.val) { 45 | root.right = deleteNode(root.right, key); 46 | } else { // key == root.val 47 | if (root.left == null && root.right == null) { 48 | return null; 49 | } else if (root.right == null) { 50 | return root.left; 51 | } else if (root.left == null) { 52 | return root.right; 53 | } else { 54 | int minVInRight = min(root.right);// 11 55 | root.val = minVInRight; 56 | root.right = deleteNode(root.right, minVInRight); 57 | } 58 | } 59 | 60 | return root; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /class24/PrintInRangeClient.java: -------------------------------------------------------------------------------- 1 | package class24; 2 | 3 | public class PrintInRangeClient { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | 8 | int[] arr = {10, 20, 30, 40, 50, 60, 70}; 9 | BinarySearchTree bst = new BinarySearchTree(arr); 10 | 11 | bst.printInRange(25, 55);//inclusive 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /class24/ValidateBST.java: -------------------------------------------------------------------------------- 1 | package class24; 2 | 3 | public class ValidateBST { 4 | 5 | // Definition for a binary tree node. 6 | public class TreeNode { 7 | int val; 8 | TreeNode left; 9 | TreeNode right; 10 | 11 | TreeNode() { 12 | } 13 | 14 | TreeNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | TreeNode(int val, TreeNode left, TreeNode right) { 19 | this.val = val; 20 | this.left = left; 21 | this.right = right; 22 | } 23 | } 24 | public boolean isValidBST(TreeNode root) { 25 | return isBST(root, Long.MIN_VALUE, Long.MAX_VALUE); 26 | } 27 | 28 | public boolean isBST(TreeNode root, long minRange, long maxRange) { 29 | 30 | if (root == null) { 31 | return true; 32 | } 33 | 34 | if (root.val <= minRange || root.val >= maxRange) { 35 | return false; 36 | } 37 | boolean left = isBST(root.left, minRange, root.val); 38 | boolean right = isBST(root.right, root.val, maxRange); 39 | return left && right; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /class25/AlienDictionary.java: -------------------------------------------------------------------------------- 1 | package class25; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Queue; 10 | 11 | public class AlienDictionary { 12 | 13 | 14 | static class Graph { 15 | Map> adjL; 16 | int numV; 17 | public Graph(int numV) { 18 | this.adjL = new HashMap<>(); 19 | this.numV = numV; 20 | } 21 | 22 | private void addEdge(String[] str, int n) { 23 | // TODO Auto-generated method stub 24 | 25 | for(int i = 0; i < n - 1; i++) { 26 | String s1 = str[i]; 27 | String s2 = str[i + 1]; 28 | 29 | for(int j = 0; j < Math.min(s1.length(), s2.length()); j++) { 30 | if(s1.charAt(j) != s2.charAt(j)) { 31 | //s1.charAt(j) -> s2.charAt(j) 32 | 33 | List neighbourL = this.adjL.getOrDefault(s1.charAt(j), new ArrayList<>()); 34 | neighbourL.add(s2.charAt(j)); 35 | adjL.put(s1.charAt(j), neighbourL); 36 | break; 37 | } 38 | } 39 | } 40 | } 41 | 42 | private void display() { 43 | // TODO Auto-generated method stub 44 | 45 | for(var entry : this.adjL.entrySet()) { 46 | char vertex = entry.getKey(); 47 | List neighbourL = entry.getValue(); 48 | 49 | System.out.println(vertex + " -> " + neighbourL); 50 | } 51 | } 52 | 53 | private Map indegree() { 54 | // TODO Auto-generated method stub 55 | 56 | Map indegree = new HashMap<>(); 57 | 58 | for(List neighbourL : this.adjL.values()) { 59 | 60 | for(char cc : neighbourL) { 61 | int value = indegree.getOrDefault(cc, 0); 62 | indegree.put(cc, value + 1); 63 | } 64 | } 65 | 66 | for(char key : this.adjL.keySet()) { 67 | if(!indegree.containsKey(key)) { 68 | indegree.put(key, 0); 69 | } 70 | } 71 | System.out.println(indegree); 72 | 73 | return indegree; 74 | } 75 | 76 | private void topologicalSorting() { 77 | // TODO Auto-generated method stub 78 | 79 | Map indegree = this.indegree(); 80 | 81 | Queue bfs = new LinkedList<>(); 82 | 83 | for(char vertex : indegree.keySet()) { 84 | int indV = indegree.get(vertex); 85 | if(indV == 0) { 86 | bfs.add(vertex); 87 | } 88 | } 89 | 90 | 91 | 92 | while(!bfs.isEmpty()) { 93 | char front = bfs.poll(); 94 | 95 | System.out.print(front); 96 | 97 | for(char neighbourChar : this.adjL.getOrDefault(front, new ArrayList<>())) { 98 | //indegree[neighbourChar - 'a']--; 99 | int indN = indegree.get(neighbourChar); 100 | indN--; 101 | indegree.put(neighbourChar, indN); 102 | 103 | if(indN == 0) { 104 | bfs.add(neighbourChar); 105 | } 106 | } 107 | } 108 | 109 | } 110 | } 111 | 112 | 113 | public static void main(String[] args) { 114 | // TODO Auto-generated method stub 115 | 116 | String[] str = {"wrt", 117 | "wrf", 118 | "er", 119 | "ett", 120 | "rftt"}; 121 | int n = 5; 122 | int k = 4; //a , b , c, d vertices 123 | 124 | Graph g = new Graph(k); 125 | 126 | g.addEdge(str, n); 127 | g.display(); 128 | g.indegree(); 129 | g.topologicalSorting(); 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /class25/CourseScheduleOne.java: -------------------------------------------------------------------------------- 1 | package class25; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Queue; 10 | 11 | public class CourseScheduleOne { 12 | 13 | static class Graph { 14 | 15 | // vertex - list of neighbours to that vertex 16 | Map> adjList; 17 | 18 | int numV; 19 | 20 | public Graph(int numV) { 21 | adjList = new HashMap<>(); 22 | this.numV = numV; 23 | } 24 | 25 | // u and v mein add edge 26 | // isBidir = true -> undirected edge, false -> directed edge 27 | private void addEdge(int u, int v, boolean isBidir) { 28 | // TODO Auto-generated method stub 29 | 30 | // u -> v edge 1 -> 2 31 | 32 | // 1 ki neighbour list 33 | List uNeighbour = this.adjList.getOrDefault(u, new ArrayList<>()); 34 | uNeighbour.add(v); 35 | this.adjList.put(u, uNeighbour); 36 | 37 | if (isBidir) { 38 | // v -> u edge 2 -> 1 39 | 40 | // 2 ki neighbour list 41 | List vNeighbour = this.adjList.getOrDefault(v, new ArrayList<>()); 42 | 43 | // 2 ka neighbour 1 44 | vNeighbour.add(u); 45 | 46 | this.adjList.put(v, vNeighbour); 47 | } 48 | 49 | } 50 | 51 | private void display() { 52 | // TODO Auto-generated method stub 53 | 54 | for (Map.Entry> entry : this.adjList.entrySet()) { 55 | int vertex = entry.getKey(); 56 | List neighbourList = entry.getValue(); 57 | System.out.println(vertex + " -> " + neighbourList); 58 | } 59 | } 60 | 61 | private int[] indegree() { 62 | // TODO Auto-generated method stub 63 | 64 | int[] indegree = new int[numV]; 65 | 66 | for (List neighbourList : this.adjList.values()) { 67 | 68 | for (int neighbour : neighbourList) { 69 | indegree[neighbour]++; 70 | } 71 | } 72 | 73 | System.out.println(Arrays.toString(indegree)); 74 | return indegree; 75 | } 76 | 77 | private boolean topologicalSorting(int numCourses) { 78 | // TODO Auto-generated method stub 79 | Queue bfs = new LinkedList<>(); 80 | int[] indegree = indegree(); 81 | 82 | int count = 0; 83 | for (int vertex = 0; vertex < numV; vertex++) { 84 | if (indegree[vertex] == 0) { 85 | count++; 86 | bfs.add(vertex); 87 | } 88 | } 89 | 90 | while (!bfs.isEmpty()) { 91 | int frontV = bfs.poll(); 92 | 93 | System.out.print(frontV + " "); 94 | 95 | List neighbourList = this.adjList.getOrDefault(frontV, new ArrayList<>()); 96 | 97 | for (int neighbour : neighbourList) { 98 | indegree[neighbour]--; 99 | 100 | if (indegree[neighbour] == 0) { 101 | count++; 102 | bfs.add(neighbour); 103 | } 104 | } 105 | } 106 | 107 | System.out.println(count); 108 | return count == numCourses ? true : false; 109 | } 110 | 111 | } 112 | 113 | public static void main(String[] args) { 114 | int[][] prerequisites = {{1, 0}, {2, 1}, {1, 2}}; 115 | int numCourses = 3; 116 | 117 | Graph g = new Graph(numCourses); 118 | for(int i = 0; i < prerequisites.length; i++) { 119 | int u = prerequisites[i][1]; 120 | int v = prerequisites[i][0]; 121 | 122 | //u -> v 123 | g.addEdge(u, v, false); 124 | } 125 | 126 | g.display(); 127 | System.out.println(g.topologicalSorting(numCourses)); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /class25/Graph.java: -------------------------------------------------------------------------------- 1 | package class25; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.LinkedList; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.Queue; 11 | import java.util.Set; 12 | 13 | //adjacency list implementation 14 | public class Graph { 15 | 16 | // vertex - list of neighbours to that vertex 17 | Map> adjList; 18 | 19 | int numV; 20 | public Graph(int numV) { 21 | adjList = new HashMap<>(); 22 | this.numV = numV; 23 | } 24 | 25 | // u and v mein add edge 26 | // isBidir = true -> undirected edge, false -> directed edge 27 | private void addEdge(int u, int v, boolean isBidir) { 28 | // TODO Auto-generated method stub 29 | 30 | // u -> v edge 1 -> 2 31 | 32 | // 1 ki neighbour list 33 | List uNeighbour = this.adjList.getOrDefault(u, new ArrayList<>()); 34 | uNeighbour.add(v); 35 | this.adjList.put(u, uNeighbour); 36 | 37 | if (isBidir) { 38 | // v -> u edge 2 -> 1 39 | 40 | // 2 ki neighbour list 41 | List vNeighbour = this.adjList.getOrDefault(v, new ArrayList<>()); 42 | 43 | // 2 ka neighbour 1 44 | vNeighbour.add(u); 45 | 46 | this.adjList.put(v, vNeighbour); 47 | } 48 | 49 | } 50 | 51 | private void display() { 52 | // TODO Auto-generated method stub 53 | 54 | for (Map.Entry> entry : this.adjList.entrySet()) { 55 | int vertex = entry.getKey(); 56 | List neighbourList = entry.getValue(); 57 | System.out.println(vertex + " -> " + neighbourList); 58 | } 59 | } 60 | 61 | private void bFS(int src) { 62 | // TODO Auto-generated method stub 63 | 64 | Queue bfs = new LinkedList<>(); 65 | 66 | bfs.add(src); 67 | Set vis = new HashSet<>(); 68 | vis.add(src); 69 | 70 | while (!bfs.isEmpty()) { 71 | int front = bfs.poll(); // vertex - 1 72 | System.out.print(front + " "); 73 | 74 | List neighbourList = this.adjList.get(front); // [2, 4] 75 | 76 | for (int neighbour : neighbourList) { 77 | if (!vis.contains(neighbour)) { 78 | bfs.add(neighbour); 79 | vis.add(neighbour); 80 | } 81 | } 82 | } 83 | } 84 | 85 | private void sSSP(int src) { 86 | // TODO Auto-generated method stub 87 | 88 | Queue bfs = new LinkedList<>(); 89 | 90 | bfs.add(src); 91 | Map dis = new HashMap<>(); // vertex - distance from source 92 | for (int vertex : adjList.keySet()) { 93 | dis.put(vertex, Integer.MAX_VALUE); 94 | } 95 | dis.put(src, 0); 96 | 97 | while (!bfs.isEmpty()) { 98 | int front = bfs.poll(); // vertex - 4 99 | // System.out.print(front + " "); 100 | 101 | List neighbourList = this.adjList.get(front); // [1, 3] 102 | 103 | for (int neighbour : neighbourList) { 104 | if (dis.get(neighbour) == Integer.MAX_VALUE) { // agar neigbhour infinite distance pr hai source se, so 105 | // it is unvisited 106 | bfs.add(neighbour); 107 | int distance = dis.get(front) + 1; // 4 ka distance + 1 = 0 + 1 = 1; 108 | dis.put(neighbour, distance); 109 | System.out.println("distance of " + neighbour + " from source " + src + " is " + distance); 110 | } 111 | } 112 | } 113 | } 114 | 115 | private void dfsHelper(int src, Set vis) { 116 | // TODO Auto-generated method stub 117 | System.out.print(src + " "); 118 | vis.add(src); 119 | 120 | List neighbourList = this.adjList.get(src); 121 | 122 | for(int neighbour : neighbourList) { 123 | if(!vis.contains(neighbour)) { 124 | dfsHelper(neighbour, vis); 125 | } 126 | } 127 | } 128 | 129 | private void dfs(int src) { 130 | // TODO Auto-generated method stub 131 | 132 | Set vis = new HashSet<>(); 133 | dfsHelper(src, vis); 134 | } 135 | 136 | private void connectedComponents() { 137 | // TODO Auto-generated method stub 138 | Set vis = new HashSet<>(); 139 | 140 | int count = 1; 141 | for(int vertex : this.adjList.keySet()) { 142 | if(!vis.contains(vertex)) { 143 | System.out.print("connected component " + count + " -> "); 144 | dfsHelper(vertex, vis); 145 | System.out.println(); 146 | count++; 147 | } 148 | 149 | } 150 | 151 | } 152 | 153 | private int[] indegree() { 154 | // TODO Auto-generated method stub 155 | 156 | int[] indegree = new int[numV]; 157 | 158 | for(List neighbourList : this.adjList.values()) { 159 | 160 | for(int neighbour : neighbourList) { 161 | indegree[neighbour]++; 162 | } 163 | } 164 | 165 | System.out.println(Arrays.toString(indegree)); 166 | return indegree; 167 | } 168 | 169 | private void topologicalSorting() { 170 | // TODO Auto-generated method stub 171 | Queue bfs = new LinkedList<>(); 172 | int[] indegree = indegree(); 173 | 174 | for(int vertex = 0; vertex < numV; vertex++) { 175 | if(indegree[vertex] == 0) { 176 | bfs.add(vertex); 177 | } 178 | } 179 | 180 | while(!bfs.isEmpty()) { 181 | int frontV = bfs.poll(); 182 | 183 | System.out.print(frontV + " "); 184 | 185 | List neighbourList = this.adjList.getOrDefault(frontV, new ArrayList<>()); 186 | 187 | for(int neighbour : neighbourList) { 188 | indegree[neighbour]--; 189 | 190 | if(indegree[neighbour] == 0) { 191 | bfs.add(neighbour); 192 | } 193 | } 194 | } 195 | 196 | //System.out.println(bfs); 197 | } 198 | public static void main(String[] args) { 199 | // TODO Auto-generated method stub 200 | 201 | Graph g = new Graph(4); 202 | 203 | // g.addEdge(1, 2, true); 204 | // g.addEdge(1, 4, true); 205 | // g.addEdge(2, 3, true); 206 | // g.addEdge(3, 4, true); 207 | // g.addEdge(3, 5, true); 208 | // g.addEdge(5, 6, true); 209 | // g.addEdge(7, 8, true); 210 | // g.addEdge(9, 9, false); 211 | 212 | //g.dfs(1); 213 | //g.connectedComponents(); 214 | // g.addEdge(0, 1, false); 215 | // g.addEdge(0, 2, false); 216 | // g.addEdge(2, 3, false); 217 | // g.addEdge(2, 4, false); 218 | // g.addEdge(3, 1, false); 219 | // g.addEdge(4, 6, false); 220 | // g.addEdge(5, 3, false); 221 | // g.addEdge(5, 6, false); 222 | // g.display(); 223 | // g.indegree(); 224 | // g.topologicalSorting(); 225 | 226 | } 227 | 228 | } 229 | -------------------------------------------------------------------------------- /class28/CycleInDirectedGraph.java: -------------------------------------------------------------------------------- 1 | package class28; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | public class CycleInDirectedGraph { 11 | 12 | static class Graph { 13 | 14 | // vertex - list of neighbours to that vertex 15 | Map> adjList; 16 | 17 | int numV; 18 | 19 | public Graph(int numV) { 20 | adjList = new HashMap<>(); 21 | this.numV = numV; 22 | } 23 | 24 | // u and v mein add edge 25 | // isBidir = true -> undirected edge, false -> directed edge 26 | private void addEdge(int u, int v, boolean isBidir) { 27 | // TODO Auto-generated method stub 28 | 29 | // u -> v edge 1 -> 2 30 | 31 | // 1 ki neighbour list 32 | List uNeighbour = this.adjList.getOrDefault(u, new ArrayList<>()); 33 | uNeighbour.add(v); 34 | this.adjList.put(u, uNeighbour); 35 | 36 | if (isBidir) { 37 | // v -> u edge 2 -> 1 38 | 39 | // 2 ki neighbour list 40 | List vNeighbour = this.adjList.getOrDefault(v, new ArrayList<>()); 41 | 42 | // 2 ka neighbour 1 43 | vNeighbour.add(u); 44 | 45 | this.adjList.put(v, vNeighbour); 46 | } 47 | 48 | } 49 | 50 | private void display() { 51 | // TODO Auto-generated method stub 52 | 53 | for (Map.Entry> entry : this.adjList.entrySet()) { 54 | int vertex = entry.getKey(); 55 | List neighbourList = entry.getValue(); 56 | System.out.println(vertex + " -> " + neighbourList); 57 | } 58 | } 59 | 60 | //Do not set for backtracking, as set do not preserve order so last element removal is not feasible. 61 | private boolean dFS(int src, Set vis, List path) { 62 | // TODO Auto-generated method stub 63 | 64 | vis.add(src); 65 | path.add(src); 66 | //recursion 67 | boolean hasCycle = false; 68 | for(int neighbour : this.adjList.getOrDefault(src, new ArrayList<>())) { 69 | if(!vis.contains(neighbour)) { 70 | 71 | hasCycle = dFS(neighbour, vis, path); 72 | 73 | } else if(path.contains(neighbour)) { 74 | return true; 75 | } 76 | } 77 | 78 | //System.out.println(path); 79 | path.remove(path.size() - 1); 80 | //System.out.println(":" + path); 81 | return hasCycle; 82 | } 83 | private void detectCycle() { 84 | // TODO Auto-generated method stub 85 | 86 | Set vis = new HashSet<>(); 87 | List path = new ArrayList<>(); 88 | 89 | System.out.println(dFS(0, vis, path)); 90 | } 91 | 92 | } 93 | 94 | public static void main(String[] args) { 95 | 96 | Graph g = new Graph(7); 97 | 98 | g.addEdge(0, 1, false); 99 | g.addEdge(1, 5, false); 100 | g.addEdge(1, 2, false); 101 | g.addEdge(5, 6, false); 102 | g.addEdge(2, 3, false); 103 | g.addEdge(3, 4, false); 104 | g.addEdge(4, 5, false); 105 | g.addEdge(4, 2, false); 106 | 107 | g.display(); 108 | 109 | g.detectCycle(); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /class28/Main.java: -------------------------------------------------------------------------------- 1 | package class28; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | Set s = new HashSet<>(); 12 | s.add(1); 13 | s.add(2); 14 | System.out.println(s); 15 | s.remove(s.size() - 1); 16 | System.out.println(s); 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /class28/ValidTree.java: -------------------------------------------------------------------------------- 1 | package class28; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Queue; 10 | import java.util.Set; 11 | 12 | public class ValidTree { 13 | 14 | static class Graph { 15 | 16 | // vertex - list of neighbours to that vertex 17 | Map> adjList; 18 | 19 | int numV; 20 | public Graph(int numV) { 21 | adjList = new HashMap<>(); 22 | this.numV = numV; 23 | } 24 | 25 | // u and v mein add edge 26 | // isBidir = true -> undirected edge, false -> directed edge 27 | private void addEdge(int u, int v, boolean isBidir) { 28 | // TODO Auto-generated method stub 29 | 30 | // u -> v edge 1 -> 2 31 | 32 | // 1 ki neighbour list 33 | List uNeighbour = this.adjList.getOrDefault(u, new ArrayList<>()); 34 | uNeighbour.add(v); 35 | this.adjList.put(u, uNeighbour); 36 | 37 | if (isBidir) { 38 | // v -> u edge 2 -> 1 39 | 40 | // 2 ki neighbour list 41 | List vNeighbour = this.adjList.getOrDefault(v, new ArrayList<>()); 42 | 43 | // 2 ka neighbour 1 44 | vNeighbour.add(u); 45 | 46 | this.adjList.put(v, vNeighbour); 47 | } 48 | 49 | } 50 | 51 | private void display() { 52 | // TODO Auto-generated method stub 53 | 54 | for (Map.Entry> entry : this.adjList.entrySet()) { 55 | int vertex = entry.getKey(); 56 | List neighbourList = entry.getValue(); 57 | System.out.println(vertex + " -> " + neighbourList); 58 | } 59 | } 60 | 61 | private boolean isValidTree(int n) { 62 | // TODO Auto-generated method stub 63 | 64 | Set vis = new HashSet<>(); 65 | int[] parent = new int[n]; 66 | Queue bfs = new LinkedList<>(); 67 | for(int i = 0; i < n; i++) { 68 | parent[i] = i; 69 | } 70 | 71 | bfs.add(0); 72 | vis.add(0); 73 | 74 | while(!bfs.isEmpty()) { 75 | int frontV = bfs.poll(); 76 | 77 | for(int neighbour : this.adjList.getOrDefault(frontV, new ArrayList<>())) { 78 | if(!vis.contains(neighbour)) { 79 | bfs.add(neighbour); 80 | vis.add(neighbour); 81 | parent[neighbour] = frontV; 82 | } else if(parent[frontV] != neighbour) { 83 | return false; // not tree 84 | } 85 | } 86 | } 87 | 88 | //no cycle 89 | System.out.println(vis); 90 | return vis.size() == n; //false -> graph that is not connected, tree should be connected. 91 | } 92 | 93 | private boolean dFS(int src, Set vis, int parent) { 94 | // TODO Auto-generated method stub 95 | 96 | //System.out.print(src); 97 | vis.add(src); 98 | 99 | boolean hasCycle = false; 100 | for(int neighbour : this.adjList.getOrDefault(src, new ArrayList<>())) { 101 | if(!vis.contains(neighbour)) { 102 | hasCycle = dFS(neighbour, vis, src); 103 | return hasCycle; 104 | } else if(parent != neighbour) { 105 | return true; 106 | } 107 | } 108 | 109 | return hasCycle; 110 | } 111 | 112 | private void hasCycle() { 113 | // TODO Auto-generated method stub 114 | 115 | Set vis = new HashSet<>(); 116 | 117 | for(int v = 0; v < this.numV; v++) { 118 | if(!vis.contains(v)) { 119 | System.out.println(dFS(v, vis, v)); 120 | } 121 | } 122 | 123 | } 124 | } 125 | 126 | 127 | 128 | 129 | public static void main(String[] args) { 130 | int[][] edges = {{1, 2}, {2, 3}, {1, 3}}; 131 | int n = 4; 132 | 133 | // //1 condn 134 | // if(edges.length < n - 1) { 135 | // System.out.println("false"); 136 | // return; 137 | // } 138 | 139 | Graph g = new Graph(n); 140 | for(int i = 0; i < edges.length; i++) { 141 | int u = edges[i][0], v = edges[i][1]; 142 | 143 | //u -> v, v -> u 144 | 145 | g.addEdge(u, v, true); 146 | } 147 | 148 | g.display(); 149 | g.hasCycle(); 150 | System.out.println(g.isValidTree(n)); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /class29/DisjointSetUnionUnoptimised.java: -------------------------------------------------------------------------------- 1 | package class29; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class DisjointSetUnionUnoptimised { 8 | 9 | static class EdgeList { 10 | 11 | class Edge { 12 | int u; 13 | int v; 14 | 15 | public Edge(int u, int v) { 16 | this.u = u; 17 | this.v = v; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | // TODO Auto-generated method stub 23 | return "{" + this.u + ", " + this.v + "}"; 24 | } 25 | } 26 | 27 | int numV; 28 | List edgeList; 29 | 30 | public EdgeList(int numV) { 31 | // TODO Auto-generated constructor stub 32 | this.numV = numV; 33 | this.edgeList = new ArrayList<>(); 34 | } 35 | 36 | private void addEdge(int u, int v) { 37 | // TODO Auto-generated method stub 38 | 39 | Edge edge = new Edge(u, v); 40 | this.edgeList.add(edge); 41 | } 42 | 43 | private void display() { 44 | // TODO Auto-generated method stub 45 | System.out.println(this.edgeList); 46 | } 47 | 48 | private int find(int[] parent, int u) { // find u ka godfather i.e vertex with no parent = -1 49 | // TODO Auto-generated method stub 50 | 51 | if(parent[u] == -1) { //mil gaya godfather 52 | return u; 53 | } 54 | 55 | return find(parent, parent[u]); 56 | } 57 | 58 | private void union(int u, int v, int[] parent) { 59 | // TODO Auto-generated method stub 60 | int godFatherU = this.find(parent, u); 61 | int godFatherV = this.find(parent, v); 62 | 63 | //godFatherU ko godFatherV ka child 64 | 65 | if(godFatherU != godFatherV) { 66 | parent[godFatherU] = godFatherV; 67 | } 68 | } 69 | 70 | private boolean detectCycle(int[] parent) { 71 | // TODO Auto-generated method stub 72 | 73 | for(Edge edge : this.edgeList) { 74 | int u = edge.u; 75 | int v = edge.v; 76 | 77 | int godFatherU = this.find(parent, u); 78 | int godFatherV = this.find(parent, v); 79 | 80 | //agar equal ni hai 81 | 82 | if(godFatherU != godFatherV) { 83 | this.union(godFatherU, godFatherV, parent); 84 | } else { //equal bole to cycle 85 | return true; 86 | } 87 | } 88 | 89 | return false; 90 | } 91 | } 92 | 93 | public static void main(String[] args) { 94 | EdgeList g = new EdgeList(5); 95 | 96 | g.addEdge(0, 1); 97 | g.addEdge(0, 2); 98 | g.addEdge(0, 3); 99 | 100 | g.addEdge(1, 4); 101 | g.addEdge(4, 2); 102 | g.display(); 103 | int[] parent = new int[5]; 104 | Arrays.fill(parent, -1); 105 | 106 | System.out.println(g.detectCycle(parent)); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /class29/KruskalAlgorithm.java: -------------------------------------------------------------------------------- 1 | package class29; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.Comparator; 7 | import java.util.List; 8 | 9 | public class KruskalAlgorithm { 10 | 11 | static class EdgeList { 12 | 13 | class Edge { 14 | int u; 15 | int v; 16 | int wt; 17 | public Edge(int u, int v, int wt) { 18 | this.u = u; 19 | this.v = v; 20 | this.wt = wt; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | // TODO Auto-generated method stub 26 | return "{" + this.u + ", " + this.v + ", " + this.wt + "}"; 27 | } 28 | } 29 | 30 | int numV; 31 | List edgeList; 32 | 33 | public EdgeList(int numV) { 34 | // TODO Auto-generated constructor stub 35 | this.numV = numV; 36 | this.edgeList = new ArrayList<>(); 37 | } 38 | 39 | private void addEdge(int u, int v, int wt) { 40 | // TODO Auto-generated method stub 41 | 42 | Edge edge = new Edge(u, v, wt); 43 | this.edgeList.add(edge); 44 | } 45 | 46 | private void display() { 47 | // TODO Auto-generated method stub 48 | System.out.println(this.edgeList); 49 | } 50 | 51 | private int find(int[] parent, int u) { // find u ka godfather i.e vertex with no parent = -1 52 | // TODO Auto-generated method stub 53 | 54 | if (parent[u] == -1) { // mil gaya godfather 55 | return u; 56 | } 57 | 58 | return find(parent, parent[u]); 59 | } 60 | 61 | private void union(int u, int v, int[] parent) { 62 | // TODO Auto-generated method stub 63 | int godFatherU = this.find(parent, u); 64 | int godFatherV = this.find(parent, v); 65 | 66 | // godFatherU ko godFatherV ka child 67 | 68 | if (godFatherU != godFatherV) { 69 | parent[godFatherU] = godFatherV; 70 | } 71 | } 72 | 73 | private boolean detectCycle(int[] parent) { 74 | // TODO Auto-generated method stub 75 | 76 | for (Edge edge : this.edgeList) { 77 | int u = edge.u; 78 | int v = edge.v; 79 | 80 | int godFatherU = this.find(parent, u); 81 | int godFatherV = this.find(parent, v); 82 | 83 | // agar equal ni hai 84 | 85 | if (godFatherU != godFatherV) { 86 | this.union(godFatherU, godFatherV, parent); 87 | } else { // equal bole to cycle 88 | return true; 89 | } 90 | } 91 | 92 | return false; 93 | } 94 | 95 | private int kruskalAlgorithm(int[] parent) { 96 | // TODO Auto-generated method stub 97 | //step 1 -> sort edge in inc order of wt 98 | 99 | Collections.sort(this.edgeList, new Comparator() { 100 | 101 | @Override 102 | public int compare(Edge o1, Edge o2) { //o1 -> curr, o2 -> curr + 1 103 | // TODO Auto-generated method stub 104 | return o1.wt - o2.wt; 105 | } 106 | }); 107 | 108 | System.out.println(this.edgeList); 109 | 110 | int minCost = 0; 111 | 112 | for(Edge edge : this.edgeList) { 113 | int u = edge.u; 114 | int v = edge.v; 115 | int wt = edge.wt; 116 | //step 2 - find godfather 117 | int godFatherU = this.find(parent, u); 118 | int godFatherV = this.find(parent, v); 119 | 120 | //step3 - can we do a union without forming cycle 121 | 122 | if (godFatherU != godFatherV) { 123 | this.union(godFatherU, godFatherV, parent); 124 | minCost += wt; 125 | } 126 | } 127 | 128 | return minCost; 129 | } 130 | } 131 | 132 | public static void main(String[] args) { 133 | EdgeList g = new EdgeList(4); 134 | g.addEdge(1, 2, 1); 135 | g.addEdge(1, 3, 2); 136 | g.addEdge(1, 4, 2); 137 | g.addEdge(2, 4, 3); 138 | g.addEdge(2, 3, 2); 139 | g.addEdge(3, 4, 3); 140 | 141 | g.display(); 142 | int[] parent = new int[5]; 143 | Arrays.fill(parent, -1); 144 | System.out.println(g.kruskalAlgorithm(parent)); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /class3/Permutations.java: -------------------------------------------------------------------------------- 1 | package class3; 2 | 3 | public class Permutations { 4 | 5 | private static void sol(String inp, String ans) { 6 | // TODO Auto-generated method stub 7 | 8 | if(inp.length() == 0) { 9 | System.out.println(ans); 10 | return; 11 | } 12 | for(int i = 0; i < inp.length(); i++) { 13 | String bachiHuiString = inp.substring(0, i) + inp.substring(i + 1); 14 | char nikalaFixed = inp.charAt(i); 15 | 16 | sol(bachiHuiString, ans + nikalaFixed); 17 | } 18 | } 19 | public static void main(String[] args) { 20 | // TODO Auto-generated method stub 21 | sol("abc", ""); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /class3/SubsequenceGenerate.java: -------------------------------------------------------------------------------- 1 | package class3; 2 | 3 | public class SubsequenceGenerate { 4 | 5 | static int count; 6 | 7 | public static int genSubs2(String input, String ans) { 8 | 9 | if (input.length() == 0) { 10 | 11 | System.out.println(ans); 12 | return 1; 13 | } 14 | 15 | int count = 0; 16 | char cc = input.charAt(0); // a 17 | 18 | count = count + genSubs2(input.substring(1), ans); 19 | 20 | count = count + genSubs2(input.substring(1), ans + cc); 21 | 22 | return count; 23 | } 24 | public static void genSubs(String input, String ans) { 25 | 26 | if (input.length() == 0) { 27 | count++; 28 | System.out.println(ans); 29 | return; 30 | } 31 | char cc = input.charAt(0); // a 32 | 33 | genSubs(input.substring(1), ans); 34 | genSubs(input.substring(1), ans + cc); 35 | 36 | } 37 | 38 | public static void main(String[] args) { 39 | // TODO Auto-generated method stub 40 | 41 | count = 0; 42 | int ct = genSubs2("abc", ""); 43 | System.out.println(ct); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /class3/SubstringDemo.java: -------------------------------------------------------------------------------- 1 | package class3; 2 | 3 | public class SubstringDemo { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | /* 8 | String str = "kartik"; 9 | 10 | //artik 11 | System.out.println(str.substring(1)); //1 -> end 12 | 13 | //rtik 14 | System.out.println(str.substring(2)); //2 -> end 15 | 16 | System.out.println(str.substring(0, 3)); //3 exc 17 | System.out.println(str.substring(1, 4)); //4 exc 18 | */ 19 | String n = "coding"; 20 | int ci = 3; 21 | String s = n.substring(0, ci) + n.substring(ci + 1); 22 | System.out.println(s); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /class30/DisjointSetOptimised.java: -------------------------------------------------------------------------------- 1 | package class30; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | public class DisjointSetOptimised { 8 | 9 | static class EdgeList { 10 | 11 | class Edge { 12 | int u; 13 | int v; 14 | 15 | public Edge(int u, int v) { 16 | this.u = u; 17 | this.v = v; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | // TODO Auto-generated method stub 23 | return "{" + this.u + ", " + this.v + "}"; 24 | } 25 | } 26 | 27 | int numV; 28 | List edgeList; 29 | 30 | public EdgeList(int numV) { 31 | // TODO Auto-generated constructor stub 32 | this.numV = numV; 33 | this.edgeList = new ArrayList<>(); 34 | } 35 | 36 | private void addEdge(int u, int v) { 37 | // TODO Auto-generated method stub 38 | 39 | Edge edge = new Edge(u, v); 40 | this.edgeList.add(edge); 41 | } 42 | 43 | //u ka godfather dhundo, aisa vertex jiks parent -1 44 | private int find(int[]parent, int u) { 45 | // TODO Auto-generated method stub 46 | 47 | if(parent[u] == -1) {//godfather, leader, parent of itself 48 | return u; 49 | } 50 | 51 | return parent[u] = find(parent, parent[u]); 52 | } 53 | 54 | private void union(int[] parent, int[] rank, int u, int v) { 55 | // TODO Auto-generated method stub 56 | 57 | //find godfather of u and v both 58 | 59 | int godFatherU = this.find(parent, u); 60 | int godFatherV = this.find(parent, v); 61 | 62 | if(godFatherU != godFatherV) { 63 | int godFatherURank = rank[godFatherU]; 64 | int godFatherVRank = rank[godFatherV]; 65 | 66 | if(godFatherURank < godFatherVRank) { 67 | // u banega v ka bacha 68 | parent[godFatherU] = godFatherV; 69 | rank[godFatherV] += rank[godFatherU]; 70 | } else { 71 | //v banega u ka bacha 72 | parent[godFatherV] = godFatherU; 73 | rank[godFatherU] += rank[godFatherV]; 74 | } 75 | } 76 | } 77 | 78 | private boolean detectCycle(int[] parent, int[] rank) { 79 | // TODO Auto-generated method stub 80 | 81 | for(Edge edge : this.edgeList) { 82 | int u = edge.u; 83 | int v = edge.v; 84 | 85 | int godFatherU = this.find(parent, u); 86 | int godFatherV = this.find(parent, v); 87 | 88 | //agar equal ni hai 89 | 90 | if(godFatherU != godFatherV) { 91 | this.union(parent,rank, godFatherU, godFatherV); 92 | } else { //equal bole to cycle 93 | return true; 94 | } 95 | } 96 | 97 | return false; 98 | } 99 | } 100 | 101 | public static void main(String[] args) { 102 | int n = 5; 103 | 104 | int[] rank = new int[n]; 105 | Arrays.fill(rank, 1); 106 | 107 | int[] parent = new int[n]; 108 | Arrays.fill(parent, -1); 109 | 110 | EdgeList g = new EdgeList(n); 111 | g.addEdge(0, 1); 112 | g.addEdge(1, 2); 113 | //g.addEdge(0, 2); 114 | //g.union(parent, rank, n, n); 115 | System.out.println(g.detectCycle(parent, rank)); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /class30/PrimsAlgorithm.java: -------------------------------------------------------------------------------- 1 | package class30; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class PrimsAlgorithm { 7 | 8 | static class Graph { 9 | 10 | int numV; 11 | int[][] costMatrix; 12 | 13 | class Edge { 14 | int u, v; 15 | public Edge(int u, int v) { 16 | this.u = u; 17 | this.v = v; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | // TODO Auto-generated method stub 23 | return "{" + u + ", " + v + "}"; 24 | } 25 | } 26 | public Graph(int[][] conn) { 27 | // TODO Auto-generated constructor stub 28 | this.numV = conn.length; 29 | 30 | this.costMatrix = new int[numV][numV]; 31 | 32 | for (int i = 0; i < this.numV; i++) { 33 | for (int j = 0; j < this.numV; j++) { 34 | if (conn[i][j] == 0) { 35 | costMatrix[i][j] = Integer.MAX_VALUE; 36 | } else { 37 | costMatrix[i][j] = conn[i][j]; 38 | } 39 | } 40 | } 41 | 42 | for (int i = 0; i < this.numV; i++) { 43 | for (int j = 0; j < this.numV; j++) { 44 | if (costMatrix[i][j] == Integer.MAX_VALUE) 45 | System.out.print("X "); 46 | else 47 | System.out.print(costMatrix[i][j] + " "); 48 | } 49 | 50 | System.out.println(); 51 | } 52 | } 53 | 54 | private List primsAlgorithm() { 55 | // TODO Auto-generated method stub 56 | 57 | //unvisited = {1, 2, 3, 4, 5, 6, 7, 8} 58 | //Mst = {0} 59 | boolean[] vis = new boolean[this.numV]; 60 | 61 | vis[0] = true; 62 | 63 | List mstEdge = new ArrayList<>(); 64 | int cost = 0; 65 | for(int ct = 1; ct < this.numV; ct++) { 66 | int u = 0, v = 0;//chosen edge 67 | 68 | for(int i = 0; i < this.numV; i++) { 69 | for(int j = 0; j < this.numV; j++) { 70 | if(vis[i] && !vis[j] && costMatrix[i][j] < costMatrix[u][v]) { 71 | u = i; 72 | v = j; 73 | } 74 | } 75 | } 76 | 77 | //(u, v) -> where u is in mst/vis and v is not visited, cost minimum 78 | System.out.println("Chosen edge is " + u + "->" + v + " with weight " + costMatrix[u][v]); 79 | cost += costMatrix[u][v]; 80 | mstEdge.add(new Edge(u, v)); 81 | //v ko mst mein include 82 | vis[v] = true; 83 | } 84 | 85 | System.out.println(cost); 86 | return mstEdge; 87 | } 88 | } 89 | 90 | public static void main(String[] args) { 91 | int[][] conn = { { 0, 3, 0, 2, 0, 0, 0, 0, 4 }, // 0 //9*9 92 | { 3, 0, 0, 0, 0, 0, 0, 4, 0 }, // 1 93 | { 0, 0, 0, 6, 0, 1, 0, 2, 0 }, // 2 94 | { 2, 0, 6, 0, 1, 0, 0, 0, 0 }, // 3 95 | { 0, 0, 0, 1, 0, 0, 0, 0, 8 }, // 4 96 | { 0, 0, 1, 0, 0, 0, 8, 0, 0 }, // 5 97 | { 0, 0, 0, 0, 0, 8, 0, 0, 0 }, // 6 98 | { 0, 4, 2, 0, 0, 0, 0, 0, 0 }, // 7 99 | { 4, 0, 0, 0, 8, 0, 0, 0, 0 } // 8 100 | }; 101 | 102 | Graph g = new Graph(conn); 103 | System.out.println(g.primsAlgorithm()); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /class31/DjikstraAlgorithm.java: -------------------------------------------------------------------------------- 1 | package class31; 2 | 3 | import java.util.Arrays; 4 | 5 | public class DjikstraAlgorithm { 6 | 7 | static class Graph { 8 | 9 | int numV; 10 | int[][] costMatrix; 11 | 12 | class Edge { 13 | int u, v; 14 | public Edge(int u, int v) { 15 | this.u = u; 16 | this.v = v; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | // TODO Auto-generated method stub 22 | return "{" + u + ", " + v + "}"; 23 | } 24 | } 25 | public Graph(int[][] conn) { 26 | // TODO Auto-generated constructor stub 27 | this.numV = conn.length; 28 | 29 | this.costMatrix = new int[numV][numV]; 30 | 31 | for (int i = 0; i < this.numV; i++) { 32 | for (int j = 0; j < this.numV; j++) { 33 | if (conn[i][j] == 0) { 34 | costMatrix[i][j] = 999999; 35 | } else { 36 | costMatrix[i][j] = conn[i][j]; 37 | } 38 | } 39 | } 40 | 41 | for (int i = 0; i < this.numV; i++) { 42 | for (int j = 0; j < this.numV; j++) { 43 | if (costMatrix[i][j] == 999999) 44 | System.out.print("X "); 45 | else 46 | System.out.print(costMatrix[i][j] + " "); 47 | } 48 | 49 | System.out.println(); 50 | } 51 | } 52 | 53 | private void djikstr(int src) { 54 | // TODO Auto-generated method stub 55 | 56 | boolean[] vis = new boolean[this.numV]; 57 | vis[src] = true; 58 | System.out.println("Node chosen is : " + src); 59 | 60 | int[] dis = new int[this.numV]; 61 | 62 | for(int i = 0; i < this.numV; i++) { 63 | dis[i] = this.costMatrix[src][i]; 64 | } 65 | 66 | System.out.println(Arrays.toString(dis)); 67 | 68 | int m;//unvisited shortest distance node 69 | for(int count = 1; count < this.numV; count++) { 70 | 71 | for(m = 0; m < this.numV; m++) { 72 | if(!vis[m]) { 73 | break; 74 | } 75 | } 76 | 77 | 78 | 79 | //compare m with other nodes to fetch the shortest distance unvis node 80 | 81 | for(int k = m + 1; k < this.numV; k++) { 82 | if(!vis[k] && dis[k] < dis[m]) { 83 | m = k; 84 | } 85 | } 86 | //System.out.println(m); 87 | vis[m] = true; 88 | 89 | System.out.println("Node chosen is : " + m); 90 | for(int n = 0; n < this.numV; n++) {//n = neighbour 91 | 92 | if(!vis[n] && dis[m] + this.costMatrix[m][n] < dis[n]) { 93 | dis[n] = dis[m] + this.costMatrix[m][n]; 94 | } 95 | } 96 | } 97 | } 98 | } 99 | public static void main(String[] args) { 100 | // TODO Auto-generated method stub 101 | 102 | int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, 103 | { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, 104 | { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, 105 | { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; 106 | 107 | Graph g = new Graph(graph); 108 | g.djikstr(0); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /class31/MergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | package class31; 2 | 3 | import class31.MiddleOfLinkedList.ListNode; 4 | 5 | public class MergeTwoSortedLists { 6 | 7 | public class ListNode { 8 | int val; 9 | ListNode next; 10 | 11 | ListNode() { 12 | } 13 | 14 | ListNode(int val) { 15 | this.val = val; 16 | } 17 | 18 | ListNode(int val, ListNode next) { 19 | this.val = val; 20 | this.next = next; 21 | } 22 | } 23 | 24 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 25 | 26 | if (l1 == null && l2 == null) { 27 | return null; 28 | } 29 | 30 | if (l1 == null) { 31 | return l2; 32 | } 33 | 34 | if (l2 == null) { 35 | return l1; 36 | } 37 | ListNode head = null; 38 | 39 | if (l1.val < l2.val) { 40 | head = l1; 41 | l1 = l1.next; 42 | } else { 43 | head = l2; 44 | l2 = l2.next; 45 | } 46 | 47 | ListNode temp = head; 48 | 49 | while (l1 != null && l2 != null) { 50 | if (l1.val < l2.val) { 51 | temp.next = l1; 52 | l1 = l1.next; 53 | } else { 54 | temp.next = l2; 55 | l2 = l2.next; 56 | } 57 | 58 | temp = temp.next; 59 | } 60 | 61 | if (l1 == null) { 62 | temp.next = l2; 63 | } 64 | 65 | if (l2 == null) { 66 | temp.next = l1; 67 | } 68 | 69 | return head; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /class31/MiddleOfLinkedList.java: -------------------------------------------------------------------------------- 1 | package class31; 2 | 3 | public class MiddleOfLinkedList { 4 | 5 | public class ListNode { 6 | int val; 7 | ListNode next; 8 | 9 | ListNode() { 10 | } 11 | 12 | ListNode(int val) { 13 | this.val = val; 14 | } 15 | 16 | ListNode(int val, ListNode next) { 17 | this.val = val; 18 | this.next = next; 19 | } 20 | } 21 | 22 | public ListNode middleNode(ListNode head) { 23 | 24 | ListNode tortoise = head; 25 | ListNode rabbit = head; 26 | 27 | while (rabbit != null && rabbit.next != null) { 28 | tortoise = tortoise.next; 29 | rabbit = rabbit.next.next; 30 | } 31 | 32 | return tortoise; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /class32/IntersectionOfTwoLinkedList.java: -------------------------------------------------------------------------------- 1 | package class32; 2 | 3 | public class IntersectionOfTwoLinkedList { 4 | 5 | public class ListNode { 6 | int val; 7 | ListNode next; 8 | 9 | ListNode() { 10 | } 11 | 12 | ListNode(int val) { 13 | this.val = val; 14 | } 15 | 16 | ListNode(int val, ListNode next) { 17 | this.val = val; 18 | this.next = next; 19 | } 20 | } 21 | public int length(ListNode head) { 22 | int count = 0; 23 | 24 | while(head != null) { 25 | head = head.next; 26 | count++; 27 | } 28 | 29 | return count; 30 | } 31 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 32 | int l1 = length(headA); 33 | int l2 = length(headB); 34 | 35 | int diff = 0; 36 | 37 | ListNode lN1 = null; 38 | ListNode lN2 = null; 39 | 40 | if(l1 >= l2) { 41 | diff = l1 - l2; 42 | lN1 = headA; 43 | lN2 = headB; 44 | } else { 45 | diff = l2 - l1; 46 | 47 | lN1 = headB; 48 | lN2 = headA; 49 | } 50 | 51 | while(diff > 0) { 52 | lN1 = lN1.next; 53 | diff--; 54 | } 55 | while(lN1 != null && lN2 != null) { 56 | if(lN1 == lN2) { 57 | return lN1; 58 | } 59 | 60 | lN1 = lN1.next; 61 | lN2 = lN2.next; 62 | } 63 | 64 | return null; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /class32/OddEvenLinkedList.java: -------------------------------------------------------------------------------- 1 | package class32; 2 | 3 | public class OddEvenLinkedList { 4 | 5 | public class ListNode { 6 | int val; 7 | ListNode next; 8 | 9 | ListNode() { 10 | } 11 | 12 | ListNode(int val) { 13 | this.val = val; 14 | } 15 | 16 | ListNode(int val, ListNode next) { 17 | this.val = val; 18 | this.next = next; 19 | } 20 | } 21 | public ListNode oddEvenList(ListNode head) { 22 | if (head == null) { 23 | return null; 24 | } 25 | ListNode evenHead = head.next; 26 | ListNode oddTemp = head; 27 | ListNode evenTemp = head.next; 28 | 29 | while (oddTemp != null && oddTemp.next != null && evenTemp != null && evenTemp.next != null) { 30 | oddTemp.next = oddTemp.next.next; 31 | oddTemp = oddTemp.next; 32 | 33 | evenTemp.next = evenTemp.next.next; 34 | evenTemp = evenTemp.next; 35 | } 36 | oddTemp.next = evenHead; 37 | return head; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /class32/ReverseInKPairs.java: -------------------------------------------------------------------------------- 1 | package class32; 2 | 3 | public class ReverseInKPairs { 4 | 5 | public class ListNode { 6 | int val; 7 | ListNode next; 8 | 9 | ListNode() { 10 | } 11 | 12 | ListNode(int val) { 13 | this.val = val; 14 | } 15 | 16 | ListNode(int val, ListNode next) { 17 | this.val = val; 18 | this.next = next; 19 | } 20 | } 21 | public ListNode reverse(ListNode head, ListNode end) { 22 | 23 | ListNode revList = head; 24 | ListNode toDo = head.next; 25 | revList.next = null; 26 | 27 | while (toDo != end) { 28 | ListNode temp = toDo; 29 | toDo = toDo.next; 30 | temp.next = revList; 31 | revList = temp; 32 | } 33 | 34 | return revList; 35 | } 36 | 37 | public ListNode reverseKGroup(ListNode head, int k) { 38 | if (head == null) { 39 | return null; 40 | } 41 | ListNode start = head, end = head; 42 | for (int i = 0; i < k; i++) { 43 | if (end == null) { 44 | return head; 45 | } 46 | end = end.next; 47 | } 48 | ListNode newHead = reverse(start, end); 49 | 50 | start.next = reverseKGroup(end, k); 51 | return newHead; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /class32/ReverseLLBetween.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode reverseList(ListNode head, ListNode tail, ListNode a, ListNode b, ListNode mai) { 13 | 14 | ListNode revList = head; 15 | ListNode toDo = head.next; 16 | 17 | revList.next = b; 18 | ListNode nextN = b; 19 | ListNode temp = null; 20 | while (toDo != nextN) { 21 | 22 | temp = toDo; 23 | toDo = toDo.next; 24 | 25 | temp.next = revList; 26 | revList = temp; 27 | } 28 | 29 | if(a != null) { 30 | a.next = revList; 31 | return mai; 32 | } else { 33 | return revList; 34 | } 35 | 36 | 37 | //return mai; 38 | } 39 | 40 | public ListNode getAtNode(int nodeNumber, ListNode head) { 41 | // TODO Auto-generated method stub 42 | 43 | if (head == null) { 44 | return null; 45 | } 46 | 47 | if(nodeNumber < 1) { 48 | return null; 49 | } 50 | 51 | ListNode i = head; 52 | for (int j = 1; j < nodeNumber; j++) { 53 | i = i.next; 54 | } 55 | 56 | return i; 57 | } 58 | public ListNode reverseBetween(ListNode head, int left, int right) { 59 | 60 | if(left == right) { 61 | return head; 62 | } 63 | ListNode nLeft = getAtNode(left, head); 64 | ListNode nRight = getAtNode(right, head); 65 | ListNode nLeftm1 = getAtNode(left - 1, head); 66 | ListNode nRightm1 = getAtNode(right + 1, head); 67 | //System.out.println(nLeftm1.val); 68 | // System.out.println(nRightm1.val); 69 | return reverseList(nLeft, nRight, nLeftm1, nRightm1, head); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /class32/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package class32; 2 | 3 | public class ReverseLinkedList { 4 | 5 | public class ListNode { 6 | int val; 7 | ListNode next; 8 | 9 | ListNode() { 10 | } 11 | 12 | ListNode(int val) { 13 | this.val = val; 14 | } 15 | 16 | ListNode(int val, ListNode next) { 17 | this.val = val; 18 | this.next = next; 19 | } 20 | } 21 | public ListNode reverse(ListNode head) { 22 | 23 | ListNode revList = head; 24 | ListNode toDo = head.next; 25 | revList.next = null; 26 | 27 | while (toDo != null) { 28 | ListNode temp = toDo; 29 | toDo = toDo.next; 30 | temp.next = revList; 31 | revList = temp; 32 | } 33 | 34 | return revList; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /class32/SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | package class32; 2 | 3 | public class SwapNodesInPairs { 4 | 5 | public class ListNode { 6 | int val; 7 | ListNode next; 8 | 9 | ListNode() { 10 | } 11 | 12 | ListNode(int val) { 13 | this.val = val; 14 | } 15 | 16 | ListNode(int val, ListNode next) { 17 | this.val = val; 18 | this.next = next; 19 | } 20 | } 21 | 22 | public ListNode reverse(ListNode head, ListNode end) { 23 | 24 | ListNode revList = head; 25 | ListNode toDo = head.next; 26 | revList.next = null; 27 | 28 | while (toDo != end) { 29 | ListNode temp = toDo; 30 | toDo = toDo.next; 31 | temp.next = revList; 32 | revList = temp; 33 | } 34 | 35 | return revList; 36 | } 37 | 38 | public ListNode reverseKGroup(ListNode head, int k) { 39 | if (head == null) { 40 | return null; 41 | } 42 | ListNode start = head, end = head; 43 | for (int i = 0; i < k; i++) { 44 | if (end == null) { 45 | return head; 46 | } 47 | end = end.next; 48 | } 49 | ListNode newHead = reverse(start, end); 50 | 51 | start.next = reverseKGroup(end, k); 52 | return newHead; 53 | } 54 | 55 | public ListNode swapPairs(ListNode head) { 56 | return reverseKGroup(head, 2); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /class33/SegmentTree.java: -------------------------------------------------------------------------------- 1 | package class33; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SegmentTree { 6 | 7 | private static void build(int[] arr ,int l, int r, int[] segTree, int ci) { 8 | // TODO Auto-generated method stub 9 | 10 | if(l == r) { 11 | segTree[ci] = arr[l]; 12 | return; 13 | } 14 | int mid = (l + r) / 2; 15 | build(arr, l, mid, segTree, 2 * ci); 16 | build(arr, mid + 1, r, segTree, 2 * ci + 1); 17 | segTree[ci] = Math.min(segTree[2 * ci], segTree[2 * ci + 1]); 18 | } 19 | 20 | private static int minQuery(int[] segTree, int cl, int cr, int ql, int qr, int ci) { 21 | // TODO Auto-generated method stub 22 | 23 | //No overlap 24 | if(cr < ql || cl > qr) { 25 | return Integer.MAX_VALUE; 26 | } 27 | 28 | if(cl >= ql && cr <= qr) { 29 | return segTree[ci]; 30 | } 31 | 32 | //Partial Overlap 33 | int mid = (cl + cr) / 2; 34 | int leftMin = minQuery(segTree, cl, mid, ql, qr, 2 * ci); 35 | int rightMin = minQuery(segTree, mid + 1, cr, ql, qr, 2 * ci + 1); 36 | 37 | return Math.min(leftMin, rightMin); 38 | } 39 | 40 | private static void updatePoint(int[] arr ,int l, int r, int[] segTree, int ci, int updInd) { 41 | // TODO Auto-generated method stub 42 | 43 | if(l == r) { 44 | segTree[ci] = arr[l]; 45 | return; 46 | } 47 | int mid = (l + r) / 2; 48 | 49 | //updInd <= mid -> left search, updInd > mid -> right search 50 | if(updInd <= mid) { 51 | updatePoint(arr, l, mid, segTree, 2*ci, updInd); 52 | } else { 53 | updatePoint(arr, mid + 1, r, segTree, 2*ci + 1, updInd); 54 | } 55 | 56 | segTree[ci] = Math.min(segTree[2 * ci], segTree[2 * ci + 1]); 57 | } 58 | public static void main(String[] args) { 59 | // TODO Auto-generated method stub 60 | 61 | int[] arr = {1, 5, 2, -3, 4, -1}; 62 | int n = arr.length; 63 | 64 | int[] segTree = new int[4 * n]; //inp size cannnot be repr in power of 2 65 | 66 | build(arr, 0, n - 1, segTree, 1); 67 | System.out.println(Arrays.toString(segTree)); 68 | 69 | System.out.println(minQuery(segTree, 0, n - 1, 0, 2, 1)); 70 | 71 | arr[3] = 5; 72 | updatePoint(arr, 0, n - 1, segTree, 1, 3); 73 | System.out.println(Arrays.toString(segTree)); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /class34/SegmentTree.java: -------------------------------------------------------------------------------- 1 | package class34; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SegmentTree { 6 | 7 | private static void build(int[] arr, int l, int r, int[] segTree, int ci) { 8 | // TODO Auto-generated method stub 9 | 10 | if (l == r) { 11 | segTree[ci] = arr[l]; 12 | return; 13 | } 14 | int mid = (l + r) / 2; 15 | build(arr, l, mid, segTree, 2 * ci); 16 | build(arr, mid + 1, r, segTree, 2 * ci + 1); 17 | segTree[ci] = Math.min(segTree[2 * ci], segTree[2 * ci + 1]); 18 | } 19 | 20 | private static int minQuery(int[] segTree, int cl, int cr, int ql, int qr, int ci, int[] lazy) { 21 | // TODO Auto-generated method stub 22 | 23 | // lazyness hatao 24 | if (lazy[ci] != 0) { 25 | 26 | segTree[ci] += lazy[ci]; 27 | // lazyness propogate karni hai childs 28 | if (cl != cr) { // childs lazy bana diya 29 | lazy[2 * ci] += lazy[ci]; 30 | lazy[2 * ci + 1] += lazy[ci]; 31 | } 32 | 33 | lazy[ci] = 0; 34 | } 35 | 36 | // No overlap 37 | if (cr < ql || cl > qr) { 38 | return Integer.MAX_VALUE; 39 | } 40 | 41 | if (cl >= ql && cr <= qr) { 42 | return segTree[ci]; 43 | } 44 | 45 | // Partial Overlap 46 | int mid = (cl + cr) / 2; 47 | int leftMin = minQuery(segTree, cl, mid, ql, qr, 2 * ci, lazy); 48 | int rightMin = minQuery(segTree, mid + 1, cr, ql, qr, 2 * ci + 1, lazy); 49 | 50 | return Math.min(leftMin, rightMin); 51 | } 52 | 53 | private static void updatePoint(int[] arr, int l, int r, int[] segTree, int ci, int updInd) { 54 | // TODO Auto-generated method stub 55 | 56 | if (l == r) { 57 | segTree[ci] = arr[l]; 58 | return; 59 | } 60 | int mid = (l + r) / 2; 61 | 62 | // updInd <= mid -> left search, updInd > mid -> right search 63 | if (updInd <= mid) { 64 | updatePoint(arr, l, mid, segTree, 2 * ci, updInd); 65 | } else { 66 | updatePoint(arr, mid + 1, r, segTree, 2 * ci + 1, updInd); 67 | } 68 | 69 | segTree[ci] = Math.min(segTree[2 * ci], segTree[2 * ci + 1]); 70 | } 71 | 72 | private static void rangeUpdate(int[] segTree, int[] lazy, int ul, int ur, int cl, int cr, int value, int ci) { 73 | // TODO Auto-generated method stub 74 | 75 | // lazyness hatao 76 | if (lazy[ci] != 0) { 77 | 78 | segTree[ci] += lazy[ci]; 79 | // lazyness propogate karni hai childs 80 | if (cl != cr) { // childs lazy bana diya 81 | lazy[2 * ci] += lazy[ci]; 82 | lazy[2 * ci + 1] += lazy[ci]; 83 | } 84 | 85 | lazy[ci] = 0; 86 | } 87 | 88 | // No overlap 89 | if (cr < ul || cl > ur) { 90 | return; 91 | } 92 | 93 | if (cl >= ul && cr <= ur) { 94 | segTree[ci] += value; // current range node update 95 | if (cl != cr) { // childs lazy bana diya 96 | lazy[2 * ci] += value; 97 | lazy[2 * ci + 1] += value; 98 | } 99 | 100 | return; 101 | } 102 | 103 | int mid = (cl + cr) / 2; 104 | rangeUpdate(segTree, lazy, ul, ur, cl, mid, value, 2 * ci); 105 | rangeUpdate(segTree, lazy, ul, ur, mid + 1, cr, value, 2 * ci + 1); 106 | 107 | segTree[ci] = Math.min(segTree[2 * ci], segTree[2 * ci + 1]); 108 | } 109 | 110 | public static void main(String[] args) { 111 | // TODO Auto-generated method stub 112 | 113 | int[] arr = { -1, 2, 4, 1, 7, 1, 3, 2 }; 114 | int n = arr.length; 115 | 116 | int[] segTree = new int[4 * n]; // inp size cannnot be repr in power of 2 117 | int[] lazyTree = new int[4 * n]; 118 | build(arr, 0, n - 1, segTree, 1); 119 | System.out.println(Arrays.toString(segTree)); 120 | 121 | System.out.println("****************************"); 122 | rangeUpdate(segTree, lazyTree, 0, 3, 0, n - 1, 3, 1); 123 | System.out.println(Arrays.toString(segTree)); 124 | System.out.println(Arrays.toString(lazyTree)); 125 | 126 | System.out.println("****************************"); 127 | rangeUpdate(segTree, lazyTree, 0, 3, 0, n - 1, 1, 1); 128 | System.out.println(Arrays.toString(segTree)); 129 | System.out.println(Arrays.toString(lazyTree)); 130 | 131 | System.out.println("****************************"); 132 | rangeUpdate(segTree, lazyTree, 0, 0, 0, n - 1, 2, 1); 133 | System.out.println(Arrays.toString(segTree)); 134 | System.out.println(Arrays.toString(lazyTree)); 135 | 136 | System.out.println("****************************"); 137 | System.out.println(minQuery(segTree, 0, n - 1, 3, 5, 1, lazyTree)); 138 | System.out.println(Arrays.toString(segTree)); 139 | System.out.println(Arrays.toString(lazyTree)); 140 | // System.out.println(minQuery(segTree, 0, n - 1, 0, 2, 1)); 141 | // 142 | // arr[3] = 5; 143 | // updatePoint(arr, 0, n - 1, segTree, 1, 3); 144 | // System.out.println(Arrays.toString(segTree)); 145 | } 146 | 147 | } 148 | -------------------------------------------------------------------------------- /class34/SegmentTreeRangeSum.java: -------------------------------------------------------------------------------- 1 | package class34; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SegmentTreeRangeSum { 6 | 7 | private static void build(int[] arr, int l, int r, int[] segTree, int ci) { 8 | // TODO Auto-generated method stub 9 | 10 | if (l == r) { 11 | segTree[ci] = arr[l]; 12 | return; 13 | } 14 | int mid = (l + r) / 2; 15 | build(arr, l, mid, segTree, 2 * ci); 16 | build(arr, mid + 1, r, segTree, 2 * ci + 1); 17 | segTree[ci] = segTree[2 * ci] + segTree[2 * ci + 1]; 18 | } 19 | 20 | private static int sumQuery(int[] segTree, int cl, int cr, int ql, int qr, int ci, int[] lazy) { 21 | // TODO Auto-generated method stub 22 | 23 | // lazyness hatao 24 | if (lazy[ci] != 0) { 25 | 26 | segTree[ci] += lazy[ci]; 27 | // lazyness propogate karni hai childs 28 | if (cl != cr) { // childs lazy bana diya 29 | lazy[2 * ci] += lazy[ci]; 30 | lazy[2 * ci + 1] += lazy[ci]; 31 | } 32 | 33 | lazy[ci] = 0; 34 | } 35 | 36 | // No overlap 37 | if (cr < ql || cl > qr) { 38 | return 0; 39 | } 40 | 41 | if (cl >= ql && cr <= qr) { 42 | return segTree[ci]; 43 | } 44 | 45 | // Partial Overlap 46 | int mid = (cl + cr) / 2; 47 | int leftMin = sumQuery(segTree, cl, mid, ql, qr, 2 * ci, lazy); 48 | int rightMin = sumQuery(segTree, mid + 1, cr, ql, qr, 2 * ci + 1, lazy); 49 | 50 | return leftMin + rightMin; 51 | } 52 | 53 | private static void updatePoint(int[] arr, int l, int r, int[] segTree, int ci, int updInd) { 54 | // TODO Auto-generated method stub 55 | 56 | if (l == r) { 57 | segTree[ci] = arr[l]; 58 | return; 59 | } 60 | int mid = (l + r) / 2; 61 | 62 | // updInd <= mid -> left search, updInd > mid -> right search 63 | if (updInd <= mid) { 64 | updatePoint(arr, l, mid, segTree, 2 * ci, updInd); 65 | } else { 66 | updatePoint(arr, mid + 1, r, segTree, 2 * ci + 1, updInd); 67 | } 68 | 69 | segTree[ci] = segTree[2 * ci] + segTree[2 * ci + 1]; 70 | } 71 | 72 | private static void rangeUpdate(int[] segTree, int[] lazy, int ul, int ur, int cl, int cr, int value, int ci) { 73 | // TODO Auto-generated method stub 74 | 75 | // lazyness hatao 76 | if (lazy[ci] != 0) { 77 | 78 | segTree[ci] += lazy[ci] ; 79 | // lazyness propogate karni hai childs 80 | if (cl != cr) { // childs lazy bana diya 81 | lazy[2 * ci] += lazy[ci]; 82 | lazy[2 * ci + 1] += lazy[ci]; 83 | } 84 | 85 | lazy[ci] = 0; 86 | } 87 | 88 | // No overlap 89 | if (cr < ul || cl > ur) { 90 | return; 91 | } 92 | 93 | if (cl >= ul && cr <= ur) { 94 | segTree[ci] += value * (ur - ul + 1); // current range node update 95 | if (cl != cr) { // childs lazy bana diya 96 | lazy[2 * ci] += value; 97 | lazy[2 * ci + 1] += value; 98 | } 99 | 100 | return; 101 | } 102 | 103 | int mid = (cl + cr) / 2; 104 | rangeUpdate(segTree, lazy, ul, ur, cl, mid, value, 2 * ci); 105 | rangeUpdate(segTree, lazy, ul, ur, mid + 1, cr, value, 2 * ci + 1); 106 | 107 | segTree[ci] = segTree[2 * ci] + segTree[2 * ci + 1]; 108 | } 109 | 110 | public static void main(String[] args) { 111 | // TODO Auto-generated method stub 112 | 113 | int[] arr = { -1, 2, 4, 1, 7, 1, 3, 2 }; 114 | int n = arr.length; 115 | 116 | int[] segTree = new int[4 * n]; // inp size cannnot be repr in power of 2 117 | int[] lazyTree = new int[4 * n]; 118 | build(arr, 0, n - 1, segTree, 1); 119 | System.out.println(Arrays.toString(segTree)); 120 | System.out.println(sumQuery(segTree, 0, n - 1, 2, 4, 1, lazyTree)); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /class35/FenwickTree.java: -------------------------------------------------------------------------------- 1 | package class35; 2 | 3 | public class FenwickTree { 4 | 5 | private static void update(int index, int val, int[] fenw) { 6 | // TODO Auto-generated method stub 7 | 8 | while(index < fenw.length) { 9 | fenw[index] += val; 10 | int l = intervalLength(index); 11 | index = index + l; 12 | } 13 | } 14 | //sum from index 1 to i 15 | private static int querySum(int[] fenw, int index) {//index - 1 to 7 16 | // TODO Auto-generated method stub 17 | 18 | int sum = 0; 19 | 20 | while(index > 0) { 21 | 22 | sum += fenw[index]; 23 | int l = index & -index; 24 | 25 | index = index - l; 26 | } 27 | 28 | return sum; 29 | } 30 | 31 | private static int intervalLength(int index) { 32 | // TODO Auto-generated method stub 33 | 34 | return index & -index; 35 | } 36 | public static void main(String[] args) { 37 | // TODO Auto-generated method stub 38 | 39 | int[] arr = {0, 3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3}; 40 | 41 | int[] fenw = new int[12]; 42 | 43 | for(int i = 1; i < arr.length; i++) { 44 | update(i, arr[i], fenw); 45 | } 46 | //System.out.println(intervalLength(10)); 47 | 48 | System.out.println(querySum(fenw, 7)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /class36/FenwickTree.java: -------------------------------------------------------------------------------- 1 | package class36; 2 | 3 | import java.util.Arrays; 4 | 5 | public class FenwickTree { 6 | 7 | private static void update(int index, int val, int[] fenw) { 8 | // TODO Auto-generated method stub 9 | 10 | while (index < fenw.length) {// 8 < 12 11 | fenw[index] += val; 12 | int l = intervalLength(index); 13 | index = index + l; 14 | } 15 | } 16 | 17 | // sum from index 1 to i 18 | private static int querySum(int[] fenw, int index) {// index - 1 to 7 19 | // TODO Auto-generated method stub 20 | 21 | int sum = 0; 22 | 23 | while (index > 0) { 24 | 25 | sum += fenw[index]; 26 | int l = index & -index; 27 | 28 | index = index - l; 29 | } 30 | 31 | return sum; 32 | } 33 | 34 | private static int intervalLength(int index) { 35 | // TODO Auto-generated method stub 36 | 37 | return index & -index; 38 | } 39 | 40 | public static void main(String[] args) { 41 | // TODO Auto-generated method stub 42 | 43 | // int[] arr = { 0, 3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3 }; 44 | // 45 | // int[] fenw = new int[12];// all 0 46 | // 47 | // for (int i = 1; i < arr.length; i++) { 48 | // update(i, arr[i], fenw);// i = 1, val = 3 49 | // } 50 | // 51 | // System.out.println(Arrays.toString(fenw)); 52 | // System.out.println(querySum(fenw, 7)); 53 | 54 | int[] arr = {2, 3, 8, 6, 1000000}; 55 | int maxV = Integer.MIN_VALUE; 56 | for(int e : arr) { 57 | maxV = Math.max(maxV, e); 58 | } 59 | 60 | int[] fen = new int[maxV + 1]; 61 | int ct = 0; 62 | for(int i = 0; i < arr.length; i++) { 63 | int ce = arr[i]; 64 | int s1 = querySum(fen, maxV); 65 | int s2 = querySum(fen, ce); 66 | 67 | ct = ct + (s1 - s2); 68 | update(ce, 1, fen); 69 | } 70 | System.out.println(Arrays.toString(fen)); 71 | System.out.println(ct); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /class37/FormBiggestNumber.java: -------------------------------------------------------------------------------- 1 | package class37; 2 | 3 | public class FormBiggestNumber { 4 | 5 | private static int compare(int x, int y) { //x -> curr, y = curr + 1 6 | // TODO Auto-generated method stub 7 | 8 | String xy = x + "" + y; 9 | String yx = y + "" + x; 10 | 11 | int valxy = Integer.valueOf(xy); 12 | int valyx = Integer.valueOf(yx); 13 | 14 | if(valxy > valyx) { 15 | return -1; //no swapping requireed 16 | } else { 17 | return 1; //swapping required 18 | } 19 | } 20 | public static void main(String[] args) { 21 | // TODO Auto-generated method stub 22 | int[] arr = {54, 546, 548, 60}; 23 | int n = arr.length; 24 | 25 | for(int cp = 1; cp <= n - 1; cp++) { //1, 2, 3 26 | 27 | for(int curr = 0; curr <= n - cp - 1; curr++) { 28 | if(compare(arr[curr], arr[curr + 1]) > 0) { 29 | int temp = arr[curr]; 30 | arr[curr] = arr[curr + 1]; 31 | arr[curr + 1] = temp; 32 | } 33 | } 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /class37/Trie.java: -------------------------------------------------------------------------------- 1 | package class37; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class Trie { 7 | 8 | class Node { 9 | char data; 10 | Map children; 11 | boolean isMarked; 12 | int freq; 13 | 14 | public Node(char data) { 15 | // TODO Auto-generated constructor stub 16 | this.data = data; 17 | this.children = new HashMap<>(); 18 | this.isMarked = false; 19 | this.freq = 0; 20 | } 21 | } 22 | 23 | Node root; 24 | 25 | public Trie() { 26 | this.root = new Node('*'); 27 | } 28 | 29 | private void insert(String word) { 30 | // TODO Auto-generated method stub 31 | 32 | Node curr = root; 33 | for (char c : word.toCharArray()) { //'h', 'a', 'c','k', h a c k e r r a n k 34 | if (curr.children.containsKey(c)) { 35 | curr = curr.children.get(c); 36 | } else { 37 | Node n = new Node(c); 38 | curr.children.put(c, n); 39 | curr = n; 40 | } 41 | curr.freq++; 42 | } 43 | 44 | curr.isMarked = true; 45 | } 46 | 47 | private boolean search(String word) { 48 | // TODO Auto-generated method stub 49 | 50 | Node curr = root; 51 | for (char c : word.toCharArray()) { 52 | if (curr.children.containsKey(c)) { 53 | curr = curr.children.get(c); 54 | } else { 55 | return false; 56 | } 57 | } 58 | 59 | return curr.isMarked; 60 | } 61 | 62 | public boolean startsWith(String prefix) { 63 | Node curr = root; 64 | 65 | for(char c : prefix.toCharArray()) { 66 | if(curr.children.containsKey(c)) { 67 | curr = curr.children.get(c); 68 | } else { 69 | return false; 70 | } 71 | } 72 | 73 | return true; 74 | } 75 | 76 | private int countPrefix(String prefix) { 77 | // TODO Auto-generated method stub 78 | Node curr = root; 79 | for(char c : prefix.toCharArray()) { 80 | if(curr.children.containsKey(c)) { 81 | curr = curr.children.get(c); 82 | } else { 83 | return 0; 84 | } 85 | } 86 | 87 | return curr.freq; 88 | } 89 | 90 | public static void main(String[] args) { 91 | // TODO Auto-generated method stub 92 | 93 | Trie trie = new Trie(); 94 | // trie.insert("RAJ"); 95 | // trie.insert("RAM"); 96 | // 97 | // System.out.println(trie.search("Fa")); 98 | // trie.insert("apple"); 99 | // System.out.println(trie.search("apple")); 100 | // System.out.println(trie.search("app")); 101 | // System.out.println(trie.startsWith("ape")); 102 | trie.insert("hack"); 103 | trie.insert("hackerrank"); 104 | trie.insert("hackerearth"); 105 | System.out.println(trie.countPrefix("hacker")); 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /class38/CbNumber.java: -------------------------------------------------------------------------------- 1 | package class38; 2 | 3 | public class CbNumber { 4 | 5 | private static boolean isVis(boolean[] vis, int si, int ei) { //si -> inc, ei -> exc 6 | // TODO Auto-generated method stub 7 | 8 | for(int i = si; i < ei; i++) { 9 | if(vis[i] == true) { 10 | return true; 11 | } 12 | } 13 | 14 | return false; 15 | } 16 | private static boolean isCbNum(String subStr) { 17 | // TODO Auto-generated method stub 18 | 19 | long subStrVal = Long.valueOf(subStr); 20 | if(subStrVal == 0 || subStrVal == 1) { 21 | return false; 22 | } 23 | 24 | long[] l = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; 25 | 26 | for(long e : l) { 27 | if(e == subStrVal) { 28 | return true; 29 | } 30 | } 31 | 32 | for(long e : l) { 33 | if(subStrVal % e== 0) { 34 | return false; 35 | } 36 | } 37 | 38 | return true; 39 | } 40 | public static void main(String[] args) { 41 | // TODO Auto-generated method stub 42 | 43 | String str = "4992"; 44 | int ct = 0; 45 | boolean[] vis = new boolean[str.length()]; 46 | for(int l = 1; l <= str.length(); l++) { 47 | for(int si = 0; si <= str.length() - l; si++) { 48 | int ei = si + l; 49 | 50 | String subStr = str.substring(si,ei); 51 | 52 | if(isCbNum(subStr) == true && isVis(vis, si, ei) == false) { 53 | ct++; 54 | for(int i = si; i < ei; i++) { 55 | vis[i] = true; 56 | } 57 | } 58 | } 59 | } 60 | 61 | System.out.println(ct); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /class38/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | package class38; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SieveOfEratosthenes { 6 | 7 | 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | int n = 25; 12 | boolean[] primes = new boolean[n + 1]; 13 | 14 | Arrays.fill(primes, true); 15 | 16 | primes[0] = primes[1] = false; 17 | for(int curr = 2; curr * curr <= n; curr++) { 18 | if(primes[curr] == true) {//curr = 5 19 | //curr ke saare multiples ko cancel krdo, yaani false krdo, yaani not prime 20 | for(int i = curr * 2; i <= n; i = i + curr) { 21 | primes[i] = false; 22 | } 23 | } 24 | } 25 | 26 | for(int i = 2; i <= n; i++) { 27 | if(primes[i]) { 28 | System.out.println(i); 29 | } 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /class4/GenerateBrackets.java: -------------------------------------------------------------------------------- 1 | package class4; 2 | 3 | public class GenerateBrackets { 4 | 5 | static int count = 0; 6 | private static void genB(String ans, int n, int oc, int cc) { 7 | // TODO Auto-generated method stub 8 | 9 | if(oc == n && cc == n) { 10 | count++; 11 | System.out.println(ans); 12 | return; 13 | } 14 | 15 | if(oc > cc) { 16 | genB(ans + ')', n, oc, cc + 1); 17 | } 18 | 19 | if(oc < n) { 20 | genB(ans + '(', n, oc + 1, cc); 21 | } 22 | 23 | 24 | } 25 | public static void main(String[] args) { 26 | // TODO Auto-generated method stub 27 | int t = 2; 28 | 29 | while(t-- != 0) { 30 | count = 0; 31 | genB("", 3, 0, 0); 32 | System.out.println(count); 33 | } 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /class4/LexicoCounting.java: -------------------------------------------------------------------------------- 1 | package class4; 2 | 3 | public class LexicoCounting { 4 | 5 | 6 | public static void lexico(int initial, int end) { 7 | if(initial > end) { 8 | return; 9 | } 10 | 11 | System.out.println(initial); 12 | 13 | int callNumber = 0; 14 | 15 | if(initial == 0) { 16 | callNumber = 1; 17 | } 18 | 19 | while(callNumber <= 9) { 20 | lexico(initial * 10 + callNumber, end); 21 | callNumber++; 22 | } 23 | } 24 | public static void main(String[] args) { 25 | // TODO Auto-generated method stub 26 | 27 | lexico(0, 1000); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /class5/BlockedMaze.java: -------------------------------------------------------------------------------- 1 | package class5; 2 | 3 | public class BlockedMaze { 4 | 5 | 6 | static boolean hasPath; 7 | public static void printPath(int[][] maze, int cr, int cc, int er, int ec, String path, boolean[][] vis) { 8 | if (cr > er || cc > ec || cr < 0 || cc < 0 || vis[cr][cc] == true || maze[cr][cc] == 1) { 9 | return; 10 | } 11 | 12 | if (cr == er && cc == ec) { 13 | hasPath = true; 14 | System.out.println(path); 15 | return; 16 | } 17 | 18 | vis[cr][cc] = true; // topi pehnai 19 | printPath(maze, cr - 1, cc, er, ec, path + 'U', vis); 20 | printPath(maze, cr + 1, cc, er, ec, path + 'D', vis); 21 | printPath(maze, cr, cc - 1, er, ec, path + 'L', vis); 22 | printPath(maze, cr, cc + 1, er, ec, path + 'R', vis); 23 | vis[cr][cc] = false; // topi utarna //backtracking 24 | } 25 | 26 | public static void main(String[] args) { 27 | 28 | int[][] maze = { {0, 1, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 } }; 29 | 30 | hasPath = false; 31 | printPath(maze, 0, 0, 3, 3, "", new boolean[4][4]); 32 | System.out.println(hasPath); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /class5/MazePathFour.java: -------------------------------------------------------------------------------- 1 | package class5; 2 | 3 | public class MazePathFour { 4 | 5 | public static void printPath(int cr, int cc, int er, int ec, String path, boolean[][] vis) { 6 | if(cr > er || cc > ec || cr < 0 || cc < 0 || vis[cr][cc] == true) { 7 | return; 8 | } 9 | 10 | if(cr == er && cc == ec) { 11 | System.out.println(path); 12 | return; 13 | } 14 | 15 | vis[cr][cc] = true; //topi pehnai 16 | printPath(cr - 1, cc, er, ec, path + 'U', vis); 17 | printPath(cr + 1, cc, er, ec, path + 'D', vis); 18 | printPath(cr, cc - 1, er, ec, path + 'L', vis); 19 | printPath(cr, cc + 1, er, ec, path + 'R', vis); 20 | vis[cr][cc] = false; //topi utarna //backtracking 21 | } 22 | public static void main(String[] args) { 23 | // TODO Auto-generated method stub 24 | int n = 3; 25 | int m = 3; 26 | printPath(0, 0, n - 1, m - 1, "", new boolean[n][m]); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /class5/MazePathTwoDir.java: -------------------------------------------------------------------------------- 1 | package class5; 2 | 3 | public class MazePathTwoDir { 4 | 5 | static int count; 6 | public static void printPath(int cr, int cc, int er, int ec, String path) { 7 | if(cr > er || cc > ec) { 8 | 9 | return; 10 | } 11 | 12 | if(cr == er && cc == ec) { 13 | count++; 14 | System.out.println(path); 15 | return; 16 | } 17 | 18 | printPath(cr, cc + 1, er, ec, path + 'H'); 19 | printPath(cr + 1, cc, er, ec, path + 'V'); 20 | } 21 | public static void main(String[] args) { 22 | // TODO Auto-generated method stub 23 | 24 | int n = 3; 25 | int m = 3; 26 | count = 0; 27 | printPath(0, 0, n - 1, m - 1, ""); 28 | System.out.println(count); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /class6/LetterCombinations.java: -------------------------------------------------------------------------------- 1 | package class6; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class LetterCombinations { 7 | 8 | static String[] mapping = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; 9 | 10 | public List letterCombinations(String digits) { 11 | 12 | if (digits.length() == 0) { 13 | return new ArrayList<>(); 14 | } 15 | 16 | List res = new ArrayList<>(); 17 | helper(digits, "", res); 18 | return res; 19 | } 20 | 21 | public static void helper(String digits, String comb, List res) { 22 | 23 | if (digits.length() == 0) { 24 | res.add(comb); 25 | System.out.println(comb); 26 | return; 27 | } 28 | char digitPressed = digits.charAt(0); // '2' char 29 | int index = digitPressed - '0'; // int 2 30 | 31 | String mappedString = mapping[index]; 32 | // System.out.println(mappedString); 33 | 34 | for (int i = 0; i < mappedString.length(); i++) { 35 | 36 | String bachiKuchiString = digits.substring(1); 37 | char choice = mappedString.charAt(i); 38 | helper(bachiKuchiString, comb + choice, res); 39 | } 40 | 41 | } 42 | 43 | public static void main(String[] args) { 44 | // TODO Auto-generated method stub 45 | 46 | //helper("27", ""); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /class6/NQueen2.java: -------------------------------------------------------------------------------- 1 | package class6; 2 | 3 | public class NQueen2 { 4 | 5 | static int count; 6 | 7 | private static boolean kyaMainQueenRakhSaktaHun(int[][] board, int cr, int cc, int n) { 8 | // TODO Auto-generated method stub 9 | 10 | for (int row = 0; row <= cr - 1; row++) { 11 | if (board[row][cc] == 1) { 12 | return false; 13 | } 14 | } 15 | 16 | int row = cr; 17 | int col = cc; 18 | 19 | while (row >= 0 && col >= 0) { 20 | if (board[row][col] == 1) { 21 | return false; 22 | } 23 | row--; 24 | col--; 25 | } 26 | 27 | row = cr; 28 | col = cc; 29 | 30 | while (row >= 0 && col < n) { 31 | if (board[row][col] == 1) { 32 | return false; 33 | } 34 | row--; 35 | col++; 36 | } 37 | 38 | return true; 39 | } 40 | 41 | private static void queenConf(int[][] board, int cr, int n) { 42 | // TODO Auto-generated method stub 43 | 44 | if (cr == n) { 45 | 46 | for (int i = 0; i < n; i++) { 47 | for (int j = 0; j < n; j++) { 48 | if (board[i][j] == 1) 49 | System.out.print("Q "); 50 | else 51 | System.out.print("- "); 52 | 53 | } 54 | System.out.println(); 55 | } 56 | System.out.println("----------------"); 57 | count++; 58 | return; 59 | } 60 | 61 | for (int cc = 0; cc < n; cc++) { 62 | if (kyaMainQueenRakhSaktaHun(board, cr, cc, n) == true) { 63 | board[cr][cc] = 1; 64 | queenConf(board, cr + 1, n); 65 | board[cr][cc] = 0; 66 | } 67 | } 68 | } 69 | 70 | public static void main(String[] args) { 71 | // TODO Auto-generated method stub 72 | int n = 4; 73 | int[][] board = new int[n][n]; // All 0, no queen is placed iniitally 74 | 75 | count = 0; 76 | queenConf(board, 0, n); 77 | System.out.println(count); 78 | 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /class7/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package class7; 2 | 3 | import java.util.Arrays; 4 | 5 | public class FibonacciNumber { 6 | 7 | private static int sol(int n, int[] cache) { 8 | // TODO Auto-generated method stub 9 | 10 | if(n == 0 || n == 1) { 11 | return n; 12 | } 13 | 14 | 15 | if(cache[n] != -1) { // -1 -> pehlie baar 16 | return cache[n]; 17 | } 18 | 19 | //pehli baar musibat ka saamna 20 | int c1 = sol(n - 1, cache); 21 | int c2 = sol(n - 2, cache); 22 | 23 | int meraAnswer = c1 + c2; 24 | cache[n] = meraAnswer; 25 | return meraAnswer; //experience store for future 26 | } 27 | public static void main(String[] args) { 28 | // TODO Auto-generated method stub 29 | int n = 40; 30 | int[] cache = new int[n + 1]; 31 | Arrays.fill(cache, -1); 32 | System.out.println(sol(n, cache)); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /class7/MinCostClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package class7; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MinCostClimbingStairs { 6 | 7 | public static int minCostClimbingStairs(int[] cost) { 8 | int n = cost.length; 9 | int[] dp = new int[n + 1]; 10 | Arrays.fill(dp, -1); 11 | int s1 = helper(cost, 0, n, dp); 12 | int s2 = helper(cost, 1, n, dp); 13 | return Math.min(s1, s2); 14 | } 15 | 16 | public static int helper(int[] cost, int curr, int n, int[] dp) { 17 | 18 | if (curr >= n) { 19 | return 0; 20 | } 21 | 22 | if (curr == n - 1) { 23 | return cost[n - 1]; 24 | } 25 | 26 | if (dp[curr] != -1) { 27 | return dp[curr]; 28 | } 29 | 30 | int c1 = helper(cost, curr + 1, n, dp); 31 | int c2 = helper(cost, curr + 2, n, dp); 32 | 33 | int futureMin = Math.min(c1, c2); 34 | int mera = cost[curr] + futureMin; 35 | return dp[curr] = mera; 36 | } 37 | 38 | public static void main(String[] args) { 39 | // TODO Auto-generated method stub 40 | 41 | int[] cost = {10,15,20}; 42 | System.out.println(minCostClimbingStairs(cost)); 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /class8/DeleteAndEarn.java: -------------------------------------------------------------------------------- 1 | package class8; 2 | 3 | import java.util.Arrays; 4 | 5 | public class DeleteAndEarn { 6 | 7 | public int deleteAndEarn(int[] nums) { 8 | int maxNum = Integer.MIN_VALUE; 9 | 10 | for (int el : nums) { 11 | maxNum = Math.max(maxNum, el); 12 | } 13 | 14 | int[] ha = new int[maxNum + 1]; 15 | for (int el : nums) { 16 | ha[el] += el; 17 | } 18 | 19 | int[] dp = new int[ha.length + 1]; 20 | Arrays.fill(dp, -1); 21 | return rob(ha, 0, ha.length, dp); 22 | } 23 | 24 | public int rob(int[] nums, int curr, int n, int[] dp) { 25 | 26 | if (curr >= n) { 27 | return 0; 28 | } 29 | 30 | if (dp[curr] != -1) { 31 | return dp[curr]; 32 | } 33 | 34 | int c1 = rob(nums, curr + 1, n, dp); 35 | int c2 = nums[curr] + rob(nums, curr + 2, n, dp); 36 | 37 | return dp[curr] = Math.max(c1, c2); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /class8/HouseRobber.java: -------------------------------------------------------------------------------- 1 | package class8; 2 | 3 | import java.util.Arrays; 4 | 5 | public class HouseRobber { 6 | 7 | public int rob(int[] nums) { 8 | int[] dp = new int[nums.length + 1]; 9 | Arrays.fill(dp, -1); 10 | return maxMoney(nums, 0, nums.length, dp); 11 | } 12 | 13 | public static int maxMoney(int[] house, int curr, int n, int[] dp) { 14 | 15 | if (curr >= n) { 16 | return 0; 17 | } 18 | 19 | if (dp[curr] != -1) { 20 | return dp[curr]; 21 | } 22 | int c1 = house[curr] + maxMoney(house, curr + 2, n, dp); 23 | int c2 = maxMoney(house, curr + 1, n, dp); 24 | 25 | return dp[curr] = Math.max(c1, c2); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /class8/LIS.java: -------------------------------------------------------------------------------- 1 | package class8; 2 | 3 | import java.util.Arrays; 4 | 5 | public class LIS { 6 | 7 | public int lengthOfLIS(int[] nums) { 8 | 9 | int[][] dp = new int[nums.length + 1][nums.length + 1]; 10 | 11 | for (int[] row : dp) { 12 | Arrays.fill(row, -1); 13 | } 14 | return recursive(nums, 0, -1, nums.length, dp); 15 | } 16 | 17 | private static int recursive(int[] nums, int curr, int prev, int n, int[][] dp) { 18 | // TODO Auto-generated method stub 19 | 20 | if (curr == n) { 21 | return 0; 22 | } 23 | 24 | if (dp[curr][prev + 1] != -1) { 25 | return dp[curr][prev + 1]; 26 | } 27 | int inc = 0, exc = 0; 28 | if (prev == -1 || nums[curr] > nums[prev]) { 29 | inc = 1 + recursive(nums, curr + 1, curr, n, dp); 30 | } 31 | 32 | exc = recursive(nums, curr + 1, prev, n, dp); 33 | 34 | return dp[curr][prev + 1] = Math.max(inc, exc); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /class9/CoinChange2.java: -------------------------------------------------------------------------------- 1 | package class9; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class CoinChange2 { 7 | 8 | private static int sol(int[] coins, int n, int amount, int[][] dp) { 9 | // TODO Auto-generated method stub 10 | 11 | if(amount == 0) { 12 | return 1; //1 tareeka 13 | } 14 | 15 | if(n == 0) { 16 | return 0; 17 | } 18 | 19 | if(dp[n][amount] != -1) { 20 | return dp[n][amount]; 21 | } 22 | int inc = 0, exc = 0; 23 | 24 | if(coins[n - 1] <= amount) { 25 | inc = sol(coins, n, amount - coins[n - 1], dp); 26 | } 27 | 28 | exc = sol(coins, n - 1, amount, dp); 29 | 30 | return dp[n][amount] = inc + exc; 31 | } 32 | public static void main(String[] args) { 33 | // TODO Auto-generated method stub 34 | Scanner s = new Scanner(System.in); 35 | int n = s.nextInt(); 36 | int a = s.nextInt(); 37 | 38 | int[] arr = new int[n]; 39 | 40 | for(int i = 0; i < n; i++) { 41 | arr[i] = s.nextInt(); 42 | } 43 | 44 | int[][] dp = new int[n + 1][a + 1]; 45 | for(int[] row : dp) { 46 | Arrays.fill(row, -1); 47 | } 48 | 49 | System.out.println(sol(arr, n, a, dp)); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /class9/DistinctSubsequences.java: -------------------------------------------------------------------------------- 1 | package class9; 2 | 3 | import java.util.Arrays; 4 | 5 | public class DistinctSubsequences { 6 | 7 | private static int sol(String source, String target, int n, int m, int[][] dp) { 8 | // TODO Auto-generated method stub 9 | //target string ban gyi 10 | if(m == 0) { 11 | return 1; //1 tareeka 12 | } 13 | 14 | //target ni bani/ source khatam yaani aisi country jisme currency hi ni hai 15 | if(n == 0) { 16 | return 0; 17 | } 18 | 19 | if(dp[n][m] != -1) { 20 | return dp[n][m]; 21 | } 22 | int inc = 0, exc = 0; 23 | 24 | if(source.charAt(n - 1) == target.charAt(m - 1)) { 25 | inc = sol(source, target, n - 1, m - 1, dp); 26 | } 27 | 28 | exc = sol(source, target, n - 1, m, dp); 29 | 30 | return dp[n][m] = inc + exc; 31 | } 32 | public static void main(String[] args) { 33 | // TODO Auto-generated method stub 34 | 35 | String source = "babgbag"; 36 | String target = "bag"; 37 | 38 | int n = source.length(); 39 | int m = target.length(); 40 | 41 | int[][] dp = new int[n + 1][m + 1]; 42 | 43 | for(int[] row : dp) { 44 | Arrays.fill(row, -1); 45 | } 46 | 47 | 48 | System.out.println(sol(source, target, n, m, dp)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /class9/KnapsackZeroOne.java: -------------------------------------------------------------------------------- 1 | package class9; 2 | 3 | import java.util.Arrays; 4 | 5 | public class KnapsackZeroOne { 6 | 7 | private static int sol(int[] weight, int[] cost, int n, int bagC, int[][] dp) { 8 | // TODO Auto-generated method stub 9 | if(bagC == 0 || n == 0) { 10 | return 0; 11 | } 12 | 13 | if(dp[n][bagC] != -1) { 14 | return dp[n][bagC]; 15 | } 16 | int inc = 0, exc = 0; 17 | 18 | if(weight[n - 1] <= bagC) { 19 | inc = cost[n - 1] + sol(weight, cost, n - 1, bagC - weight[n - 1], dp); 20 | } 21 | 22 | exc = sol(weight, cost, n - 1, bagC, dp); 23 | 24 | return dp[n][bagC] = Math.max(inc, exc); 25 | } 26 | public static void main(String[] args) { 27 | // TODO Auto-generated method stub 28 | 29 | int[] weight = {1, 2, 3, 2, 2}; 30 | int[] cost = {8, 4, 0, 5, 3}; 31 | 32 | int n = 5; 33 | int bagC = 4; 34 | int[][] dp = new int[n + 1][bagC + 1]; 35 | for(int[] row : dp) { 36 | Arrays.fill(row, -1); 37 | } 38 | 39 | System.out.println(sol(weight, cost, n, bagC, dp)); 40 | } 41 | 42 | } 43 | --------------------------------------------------------------------------------