diff --git a/src/HelloWorld.java b/src/day1/HelloWorld.java similarity index 91% rename from src/HelloWorld.java rename to src/day1/HelloWorld.java index f716995..9aab7d7 100644 --- a/src/HelloWorld.java +++ b/src/day1/HelloWorld.java @@ -1,8 +1,8 @@ -public class HelloWorld { +package day1; +public class HelloWorld { public static void main(String[] args) { - System.out.println("Hello Competitive Programming"); } } diff --git a/src/day1/MergeTwoSortedArrays.java b/src/day1/MergeTwoSortedArrays.java new file mode 100644 index 0000000..812871d --- /dev/null +++ b/src/day1/MergeTwoSortedArrays.java @@ -0,0 +1,33 @@ +package day1; + + +/* + + In m size of array add n more slots with number zero + + + m_arr = m - 1; + n_arr = n - 1; + last = m + n - 1; + + compare m[m_arr] with n[n_arr] + if m[m_arr] > n[n_arr] + m[last] = m[m_arr] + m_arr--; + last--; + else + m[last] = n[n_arr] + n_arr--; + last + + put all the elements of n size array in m and decrement last; + + + */ +public class MergeTwoSortedArrays { + + + public static void main(String[] args) { + + } +} diff --git a/src/day1/MinimumPlatforms.java b/src/day1/MinimumPlatforms.java new file mode 100644 index 0000000..80f67cb --- /dev/null +++ b/src/day1/MinimumPlatforms.java @@ -0,0 +1,40 @@ +package day1; + +import java.util.Arrays; + +/** + * Sort the arrival time in ascending order + * Sort the departure time in ascending order + * n is size of array + * + * platform = 1 + * total platform; + * + * start with index 1 of arrival array with pointer name i + * j = index 0 of departure array + * + * run a loop i < n && j < n { + * if(arr[i] <= dep[j]) { + * platform++; + * i++; + * } else if(arr[i] > dep[j] { + * platform--; + * j++; + * } + * + * if(platform > total platform) { + * total platform = platform; + * } + * + * return total_platform; + * } + */ +public class MinimumPlatforms { + + + + + public static void main(String[] args) { + + } +} diff --git a/src/day1/SearchInSortedMatrix.java b/src/day1/SearchInSortedMatrix.java new file mode 100644 index 0000000..4922994 --- /dev/null +++ b/src/day1/SearchInSortedMatrix.java @@ -0,0 +1,55 @@ +package day1; + +import java.util.Scanner; + +public class SearchInSortedMatrix { + + public static boolean isExist(int [][] matrix, int targetValue) { + + //Start from top right + //if greater than target go to left + //if smaller then go to down + + int i = 0; + int j = matrix[0].length - 1; + + while (i < matrix.length && j >= 0) { + if(matrix[i][j] == targetValue) { + return true; + } + + if(matrix[i][j] > targetValue) { + j--; //left column + } else { + i++; // next row + } + } + + return false; + } + + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + System.out.println("Enter number of rows"); + int r = sc.nextInt(); + System.out.println("Enter number of cols"); + int c = sc.nextInt(); + int [][] matrix = new int[r][c]; + + for(int i = 0; i < r; i++) { + System.out.println("Enter elements for row" + i); + for(int j = 0; j < c; j++) { + int element = sc.nextInt(); + matrix[i][j] = element; + } + } + + System.out.println("Enter the value to be searched"); + + int target = sc.nextInt(); + + System.out.println(isExist(matrix, target)); + } +} diff --git a/src/day1/Sort012.java b/src/day1/Sort012.java new file mode 100644 index 0000000..0348040 --- /dev/null +++ b/src/day1/Sort012.java @@ -0,0 +1,67 @@ +package day1; + +/** + * Use three pointers + * + * left = 0 + * right = length - 1; + * mid = 0; + * + * + * run a loop from mid to high + * + * if(a[mid] == 0) { + * swap with left + * left++; + * mid++; + * } else id( a[mid] == 1) { + * mid++; + * } else { + * swap with right + * right--; + * } + */ +public class Sort012 { + + + public static void sorting(int [] arr) { + int left = 0; + int right = arr.length - 1; + int mid = 0; + while(mid <= right) { + if(arr[mid] == 0) { + int temp = arr[left]; + arr[left] = arr[mid]; + arr[mid] = temp; + left++; + mid++; + } else if(arr[mid] == 1) { + mid++; + } else { + int temp = arr[mid]; + arr[mid] = arr[right]; + arr[right] = temp; + right--; + } + } + } + + + private static void printArray(int [] arr) { + for(int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } + + public static void main(String[] args) { + + + int [] arr = {0, 2, 1, 1, 2, 1, 0, 0, 2, 1, 0, 1, 2, 0, 0, 1, 2}; + + sorting(arr); + + printArray(arr); + + + } +} diff --git a/src/day1/TrappingRainWater.java b/src/day1/TrappingRainWater.java new file mode 100644 index 0000000..42b658e --- /dev/null +++ b/src/day1/TrappingRainWater.java @@ -0,0 +1,65 @@ +package day1; + +/** + * + * T.C = O(n) + * S.C = O(n) + * create left and right side array with size n + * + * fill the left the array from 1 to n - 1 (Inclusive) + * if(input[i] > left [i - 1]) { + * left[i] = input[i]; + * } else { + * left[i] = left[i - 1]; + * } + * + * fill the right the array from n - 1 to 0 (Inclusive) + * if(input[i] > right[i + 1]) { + * right[i] = input[i]; + * } else { + * right[i] = right[i + 1]; + * } + * + * int totalWater = 0; + * + * Traverse the main array and for every element + * totalWater = totalWater + (min(left[i], right[i]) - current element); + * + * + */ +public class TrappingRainWater { + + public static int totalWater(int [] arr) { + + int [] left = new int[arr.length]; + int [] right = new int [arr.length]; + + //fill left array + + left[0] = arr[0]; + for(int i = 1; i < arr.length; i++) { + left[i] = Math.max(left[i - 1], arr[i]); + } + + right[arr.length - 1] = arr[arr.length - 1]; + for(int i = arr.length - 2; i >= 0; i--) { + right[i] = Math.max(right[i + 1], arr[i]); + } + + int totalWater = 0; + + for(int i = 0; i < arr.length; i++) { + totalWater += Math.min(left[i], right[i]) - arr[i]; + } + + return totalWater; + } + + + public static void main(String[] args) { + + int [] arr = {3, 1, 0, 5, 2, 2}; + + System.out.println(totalWater(arr)); + } +} diff --git a/src/day1/TwoPeopleMeetEachOther.java b/src/day1/TwoPeopleMeetEachOther.java new file mode 100644 index 0000000..a2c1aa4 --- /dev/null +++ b/src/day1/TwoPeopleMeetEachOther.java @@ -0,0 +1,74 @@ +package day1; + +public class TwoPeopleMeetEachOther { + + + public static boolean isMeet(int d1, int d2, int v1, int v2) { + if(d1 > d2 && v1 > v2) { + System.out.println("They will never meet"); + return false; + } + + if (d2 > d1 && v2 > v1) { + System.out.println("They will never meet"); + return false; + } + + + //Assuming d1 will always be ahead in starting + + while(d1 >= d2) { //d2 > d1 + + if(d1 == d2) { + + System.out.println(d1); + return true; + } + d1 = d1 + v1; + + d2 = d2 + v2; + } + + return false; + + } + + + public static boolean isMeetUsingRelativeSpeed(int d1, int d2, int v1, int v2) { + + if(d1 > d2 && v1 > v2) { + System.out.println("They will never meet"); + return false; + } + + if (d2 > d1 && v2 > v1) { + System.out.println("They will never meet"); + return false; + } + + int D = d1 - d2; + int V = v1 - v2; + + if(D % V == 0) { + return true; + } + + return false; + } + + public static void main(String[] args) { + + int d1 = 6; + int d2 = 4; + + int v1 = 6; + int v2 = 8; + + + + System.out.println(isMeetUsingRelativeSpeed(d1, d2, v1, v2)); + + + + } +} diff --git a/src/day1/kSmallestElements.java b/src/day1/kSmallestElements.java new file mode 100644 index 0000000..697e965 --- /dev/null +++ b/src/day1/kSmallestElements.java @@ -0,0 +1,75 @@ +package day1; + + +/* + Assume for first K elements are minimum elements + + + + Start from k to n { + + Try to find the maximum element of this window and store at max + + element = take the current element in this window + if (max > element) { + + +// Some computation + + Perform shifting of elements by one to left side in 0 to k -1 (Exclusive) + + +//Putting the element at hole + arr[k - 1] = element + } + + } + */ +public class kSmallestElements { + +/* + T.C = O(nk) + S.C = O(1) + */ + public static void printKSmallestElements(int [] arr, int k) { + + for(int i = k; i < arr.length; i++) { + + int max = arr[k -1]; + int max_position = k - 1; + + for(int j = k - 2; j >= 0 ; j--) { + if(arr[j] > max) { + max = arr[j]; + max_position = j; + } + } + + int currentElement = arr[i]; + + if(max > currentElement) { + + int m = max_position; + while(m < k - 1) { + arr[m] = arr[m + 1]; + m++; + } + arr[k - 1] = currentElement; + } + } + + for(int i = 0; i < k; i++) { + System.out.print(arr[i] + " "); + } + + } + + public static void main(String[] args) { + + + int [] arr = {300, 400, 250, 100, 800}; + + printKSmallestElements(arr, 3); + + } +} diff --git a/src/day2/GenerateParenthesis.java b/src/day2/GenerateParenthesis.java new file mode 100644 index 0000000..ddcb8e8 --- /dev/null +++ b/src/day2/GenerateParenthesis.java @@ -0,0 +1,38 @@ +package day2; + + +public class GenerateParenthesis { + + + //T.C = O(2^n) + public static void generate(int left, int right, String s) { + + + if(left > right) { + return; + } + + if (left == 0 && right == 0) { + //print the string + System.out.println(s); + return; + } + + if (left > 0) { + //do recursive call + generate(left - 1, right, s + "("); + } + + if (right > 0) { + //do recursive + generate(left, right - 1, s + ")"); + + } + } + + public static void main(String[] args) { + + generate(2,2, ""); + + } +} diff --git a/src/day2/GeneratePaths.java b/src/day2/GeneratePaths.java new file mode 100644 index 0000000..3721cb2 --- /dev/null +++ b/src/day2/GeneratePaths.java @@ -0,0 +1,51 @@ +package day2; + + +import java.util.Stack; + +public class GeneratePaths { + + + public static void generatePaths(int[][] matrix, int i, int j, Stack path) { + + + int m = matrix.length; + int n = matrix[0].length; + if ((i == m - 1) && (j == n - 1)) { + //print the path + path.add(matrix[i][j]); + System.out.println(path); + path.pop(); + } + + + path.add(matrix[i][j]); + + + + + //attempt to reach to solution + //move to right + if (j + 1 >= 0 && j + 1 < n) { + generatePaths(matrix, i, j + 1, path); + } + + + //move to down + if (i + 1 >= 0 && i + 1 < m) { + generatePaths(matrix, i + 1, j, path); + } + + path.pop(); + } + + + public static void main(String[] args) { + + + int[][] matrix = {{1, 2, 3}, {4, 5, 6,}, {7, 8, 9}}; + Stack s = new Stack<>(); + + generatePaths(matrix, 0, 0, s); + } +} diff --git a/src/day2/GenerateSubsets.java b/src/day2/GenerateSubsets.java new file mode 100644 index 0000000..f935cc7 --- /dev/null +++ b/src/day2/GenerateSubsets.java @@ -0,0 +1,31 @@ +package day2; + + +import java.util.ArrayList; + +public class GenerateSubsets { + + + public static void generateAllSubsets(int [] arr, int begining, ArrayList ans) { + + + for(int i = 0; i < ans.size(); i++) { + System.out.print(ans.get(i)); + } + System.out.println(); + + + for(int i = begining; i < arr.length; i++) { + ans.add(arr[i]); + generateAllSubsets(arr, i + 1, ans); + ans.remove(ans.size() - 1); + } + } + + + public static void main(String[] args) { + + int arr[] = {4,5,6}; + generateAllSubsets(arr, 0, new ArrayList<>()); + } +} diff --git a/src/day2/MaxElement.java b/src/day2/MaxElement.java new file mode 100644 index 0000000..cf0bdbb --- /dev/null +++ b/src/day2/MaxElement.java @@ -0,0 +1,29 @@ +package day2; + + +public class MaxElement { + + public static int findMaximum(int [] arr, int index ) { //0 + + + if(index == arr.length - 1) { + return arr[index]; + } + + int smallerProblemMax = findMaximum(arr, index + 1); + + int max = Math.max(arr[index], smallerProblemMax); + + return max; + + + + } + + public static void main(String[] args) { + + int [] arr = {5, 7, 1, 4, 3}; + + System.out.println(findMaximum(arr, 0)); + } +} diff --git a/src/day2/Nqueen.java b/src/day2/Nqueen.java new file mode 100644 index 0000000..73a50b0 --- /dev/null +++ b/src/day2/Nqueen.java @@ -0,0 +1,80 @@ +package day2; + + +public class Nqueen { + + + public static boolean placeQueens(int[][] grid, int i) { // i = 1, grid.length = 4 + + if (i == grid.length) { + //Print the grid + for (int row = 0; row < grid.length; row++) { + for (int col = 0; col < grid[0].length; col++) { + System.out.print(grid[row][col] + " "); + } + System.out.println(); + } + return true; + } + + for (int k = 0; k < grid[0].length; k++) { + if (isSafeToPlace(grid, i, k)) { + grid[i][k] = 1; + boolean isPlaced = placeQueens(grid, i + 1); + if (isPlaced) { + return true; + } + //backtrack step + grid[i][k] = 0; + } + } + return false; + + + } + + private static boolean isSafeToPlace(int[][] grid, int i, int k) { // i = 1, k = 0 + + for (int row = 0; row < i; row++) { + if (grid[row][k] == 1) { + return false; + } + } + + int x = i; + int y = k; + + //Check for left diagonal + while (x >= 0 && y >= 0) { + if (grid[x][y] == 1) { + return false; + } + x--; + y--; + } + + x = i; + y = k; + while (x >= 0 && y < grid.length) { + if (grid[x][y] == 1) { + return false; + } + x--; + y++; + } + + return true; + } + + + public static void main(String[] args) { + + + int n = 1; + int [][] grid = new int[1][1]; + + placeQueens(grid, 0); + + + } +} diff --git a/src/day2/Permutation.java b/src/day2/Permutation.java new file mode 100644 index 0000000..f113f30 --- /dev/null +++ b/src/day2/Permutation.java @@ -0,0 +1,40 @@ +package day2; + + +import java.util.ArrayList; +import java.util.List; + +public class Permutation { + + + //T.C = O(2^n) + public static void generatePermutation(int[] arr, ArrayList ans) { //123 + + if (ans.size() == arr.length) { + //print the ans + System.out.println(); + for (int i = 0; i < ans.size(); i++) { + int element = ans.get(i); + System.out.print(element + " "); + } + + return; + } + + for (int i = 0; i < arr.length; i++) { + + if (ans.contains(arr[i])) { + continue; + } + ans.add(arr[i]); + generatePermutation(arr, ans); + ans.remove(ans.size() - 1); + } + } + + public static void main(String[] args) { + + int arr[] = {4,5,6}; + generatePermutation(arr, new ArrayList<>()); + } +} diff --git a/src/day2/PrintDecodings.java b/src/day2/PrintDecodings.java new file mode 100644 index 0000000..12d21fb --- /dev/null +++ b/src/day2/PrintDecodings.java @@ -0,0 +1,46 @@ +package day2; + + +public class PrintDecodings { + + public static void printAlllDecoing(String number, String output) { + + if(number.length() == 0) { + System.out.println(output); + return; + } + + String firstCharacter = number.substring(0,1); + + + int firstNumber = Integer.parseInt(firstCharacter); + + if(firstNumber != 0) { + char character = (char)('a' + firstNumber - 1); + printAlllDecoing(number.substring(1), output + character); + } + + if(number.length() <= 1) { + return; + } + + String firstTwoCharacters = number.substring(0,2); + + + int firstTwoNumber = Integer.parseInt(firstTwoCharacters); + + + if(firstTwoNumber <= 26) { + char character = (char)('a' + firstTwoNumber - 1); + printAlllDecoing(number.substring(2), output + character); + } + + + } + + public static void main(String[] args) { + + printAlllDecoing("20", ""); + } + +} diff --git a/src/day2/Printkeypad.java b/src/day2/Printkeypad.java new file mode 100644 index 0000000..df5b35d --- /dev/null +++ b/src/day2/Printkeypad.java @@ -0,0 +1,60 @@ +package day2; + + +import java.util.ArrayList; + +public class Printkeypad { + + + public static String getValue(char c) { + + if (c == '1') { + return "abc"; + } + if (c == '2') { + return "def"; + } + if(c == '3') { + return "ghi"; + } + + return ""; + } + + + public static ArrayList getAllCombinations(String input) { //2 + + if(input.length() == 0) { + + ArrayList emptyList = new ArrayList<>(); + emptyList.add(""); + return emptyList; + } + + String firstCharacterValue = getValue(input.charAt(0)); //def + + ArrayList smallerproblemCombinations = getAllCombinations(input.substring(1)); // empty + + ArrayList ans = new ArrayList<>(); + + //n + for(int i = 0; i < firstCharacterValue.length(); i++) { + for(int j = 0; j < smallerproblemCombinations.size(); j++) { + String output = firstCharacterValue.charAt(i) + smallerproblemCombinations.get(j); + ans.add(output); + } + } + return ans; + } + + + public static void main(String[] args) { + + ArrayList ans = getAllCombinations("123"); + + + for(String s : ans) { + System.out.println(s); + } + } +} diff --git a/src/day3/CloneLinkedList.java b/src/day3/CloneLinkedList.java new file mode 100644 index 0000000..35b2768 --- /dev/null +++ b/src/day3/CloneLinkedList.java @@ -0,0 +1,83 @@ +package day3; + + + +public class CloneLinkedList { + + /** + * T.C = O(Length of linked list) + * S.C = O(1) + * @param head + * @return + */ + public static Node createClone(Node head) { + + Node original = head; + + while(original != null && original.next != null) { + Node copy = new Node(original.data); + Node next = original.next; + original.next = copy; + copy.next = next; + original = original.next.next; + } + original.next = new Node(original.data); + + original = head; + + while(original != null && original.next != null) { + + if(original.random != null) { + original.next.random = original.random.next; + } + original = original.next.next; + } + + original = head; + Node copy = head.next; + Node copyHead = head.next; + + + while(original.next != null && copy.next != null) { + original.next = original.next.next; + copy.next = copy.next.next; + original = original.next; + copy = copy.next; + } + + original.next = null; + + return copyHead; + + } + + public static void printList(Node head) { + Node current = head; + + while(current != null) { + System.out.println(current.data + " Random pointer of this node is " + current.random.data); + current = current.next; + } + } + + public static void main(String[] args) { + + + Node head = new Node(1); + Node node2 = new Node(2); + Node node3 = new Node(3); + + head.next = node2; + head.random = node3; + + node2.next = node3; + node2.random = node3; + + node3.random = head; + + Node newClonedHead = createClone(head); + + printList(newClonedHead); + + } +} diff --git a/src/day3/DesignLinkedList.java b/src/day3/DesignLinkedList.java new file mode 100644 index 0000000..e1a857c --- /dev/null +++ b/src/day3/DesignLinkedList.java @@ -0,0 +1,53 @@ +package day3; + + +public class DesignLinkedList { + + + public static Node reverseLinkedList(Node head) { + + if(head == null || head.next == null) { + return head; + } + + + Node rest = reverseLinkedList(head.next); + + head.next.next = head; + + head.next = null; + + return rest; + } + + + public static void printList(Node head) { + Node current = head; + + while(current != null) { + System.out.print(current.data + " -> "); + current = current.next; + } + } + + + public static void main(String[] args) { + + Node head = new Node(4); + + Node node1 = new Node(5); + + head.next = node1; + + head.next.next = new Node(6); + + head.next.next.next = new Node(7); + + printList(head); + Node newHead = reverseLinkedList(head); + + System.out.println(); + printList(newHead); + + } +} diff --git a/src/day3/DetectAndRemoveLoop.java b/src/day3/DetectAndRemoveLoop.java new file mode 100644 index 0000000..177b54e --- /dev/null +++ b/src/day3/DetectAndRemoveLoop.java @@ -0,0 +1,58 @@ +package day3; + + +public class DetectAndRemoveLoop { + + + public static void detectAndRemove(Node head) { + + Node fast = head; + Node slow = head; + boolean isLoopAvailable = false; + while (slow != null && fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (slow == fast) { + System.out.print("Loop Exists"); + isLoopAvailable = true; + break; + } + } + + if (isLoopAvailable) { + slow = head; + Node prevNode = null; + while (slow != fast) { + prevNode = fast; + fast = fast.next; + slow = slow.next; + } + System.out.print("Loop Found Node : " + slow.data); + prevNode.next = null; //Remove the Loop + } + + } + + + public static void main(String[] args) { + + + Node head = new Node(1); + + Node node1 = new Node(2); + + Node node2 = new Node(3); + + Node node3 = new Node(4); + + Node node4 = new Node(5); + + head.next = node1; + node1.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node2; + + detectAndRemove(head); + } +} diff --git a/src/day3/Node.java b/src/day3/Node.java new file mode 100644 index 0000000..526fa3f --- /dev/null +++ b/src/day3/Node.java @@ -0,0 +1,21 @@ +package day3; + + +public class Node { + + + public int data; + + public Node next; + + + public int min; + + public Node(int data) { + this.data = data; + } + + + Node random; + +} diff --git a/src/day3/RearrangeLinkedList.java b/src/day3/RearrangeLinkedList.java new file mode 100644 index 0000000..a8af23d --- /dev/null +++ b/src/day3/RearrangeLinkedList.java @@ -0,0 +1,15 @@ +package day3; + + +/** + * Rearrange the linked list L in below fashion + * + * l0 > ln > l1 > ln -1 > l2 > ln -2 + * + * //Step 1 Find the mid of the linked list + * //Step 2 Make two seperate linked lists with l1 and l2 + * //step 2.1 reverse the l2 + * // Step 3 merge l1 and l2 + */ +public class RearrangeLinkedList { +} diff --git a/src/day3/ReorderOddEven.java b/src/day3/ReorderOddEven.java new file mode 100644 index 0000000..04e8107 --- /dev/null +++ b/src/day3/ReorderOddEven.java @@ -0,0 +1,63 @@ +package day3; + + +public class ReorderOddEven { + + + /** + * T.C = O(n) + * S.C = O(1) + * @param head + * @return + */ + public static Node rearrange(Node head) { + + if (head == null || head.next == null) { + return head; + } + Node odd = head; + Node even = head.next; + Node evenHead = even; + + //Performing of rearrangement of links + + while (even != null && even.next != null) { + odd.next = even.next; + odd = odd.next; + even.next = odd.next; + even = even.next; + } + + odd.next = evenHead; + return head; + + } + + public static void printList(Node head) { + Node current = head; + + while(current != null) { + System.out.print(current.data + " -> "); + current = current.next; + } + } + + + public static void main(String[] args) { + + + Node root = new Node(1); + root.next = new Node(2); + root.next.next = new Node(3); + root.next.next.next = new Node(4); + root.next.next.next.next = new Node(5); + + printList(root); + + Node result = rearrange(root); + + System.out.println(); + printList(result); + + } +} diff --git a/src/day3/SumOfLinkedList.java b/src/day3/SumOfLinkedList.java new file mode 100644 index 0000000..b2b1cf1 --- /dev/null +++ b/src/day3/SumOfLinkedList.java @@ -0,0 +1,117 @@ +package day3; + + +public class SumOfLinkedList { + + + /* + T.C = O(max(l1, l2)) + */ + public static Node sum(Node head1, Node head2) { + + + //get the length of both the linked list + + Node sum_result = null; + if (length(head1) > length(head2)) { + + int diff = length(head1) - length(head2); + sum_result = sumHelper(head1, head2, diff); + } else { + int diff = length(head2) - length(head1); + sum_result = sumHelper(head2, head1, diff); + } + + + Node temp = new Node(1); // 1 > null + + if(sum_result.data > 9) { + sum_result.data = sum_result.data % 10; + temp.next = sum_result; //1 > 9 > 8 + sum_result = temp; + } + return sum_result; + } + + private static int length(Node head1) { + + int length = 0; + Node current = head1; + + while(current != null) { + length++; + current = current.next; + } + return length; + } + + + /** + * This function is assuming that size of l1 and l2 are equal + * @param head1 + * @param head2 + * @param diff + * @return + */ + public static Node sumHelper(Node head1, Node head2, int diff) { + + if(head1 == null) { + return null; + } + + Node my_result = null; + if(diff == 0) { + my_result = new Node(head1.data + head2.data); + } else { + my_result = new Node(head1.data); + } + + + Node recursiveResult = null; + if(diff == 0) { + recursiveResult = sumHelper(head1.next, head2.next, diff); + } else { + recursiveResult = sumHelper(head1.next, head2,diff - 1); + } + + + if(recursiveResult != null && recursiveResult.data > 9) { + recursiveResult.data = recursiveResult.data % 10; + my_result.data = my_result.data + 1; + } + + my_result.next = recursiveResult; + return my_result; + } + + public static void printList(Node head) { + Node current = head; + + while(current != null) { + System.out.print(current.data + " -> "); + current = current.next; + } + } + + public static void main(String[] args) { + + Node head1 = new Node(9); + head1.next = new Node(9); + + printList(head1); + + System.out.println(); + Node head2 = new Node(9); + head2.next = new Node(9); + head2.next.next = new Node(9); + + printList(head2); + System.out.println(); + Node result = sum(head1, head2); + + printList(result); + + + } + +} diff --git a/src/day4/LargestHistogram.java b/src/day4/LargestHistogram.java new file mode 100644 index 0000000..e154185 --- /dev/null +++ b/src/day4/LargestHistogram.java @@ -0,0 +1,79 @@ +package day4; + + +/** + * 1. Create a stack + * + * 2. Iterate over the array { + Take the current index + + int max area = 0; + * + * If stack is empty -> push the current index in stack + * else if stack is not empty + * a. If building is greater than building which is at top of stack -> push it in stack + * b.If building is smaller or no building -> + * b.1 take the top of the stack and pop it + * height = from get height of building + * if stack is empty, width = currentIndex + * else, width = currentIndex - s.top() - 1; + * area = height * width + * + * if(area > maxarea) { + * area = maxarea; + * } + * } + * + * + */ +public class LargestHistogram { + + public static int maxAreaInHistogram(int [] arr) { + StackUsingLinkedList s = new StackUsingLinkedList(); + + int max_area = 0; + + int i = 0; + while(i < arr.length) { + int currentBuilding = arr[i]; + if(s.isEmpty() || currentBuilding >= arr[s.top()]) { + s.push(i); + i++; + } else { + int previousBar = s.pop(); + int height = arr[previousBar]; + int width; + if(s.isEmpty()) { + width = i; + } else { + width = i - s.top() - 1; + } + int area = height * width; + max_area = Math.max(area, max_area); + } + } + + while(!s.isEmpty()) { + int previousBar = s.pop(); + int height = arr[previousBar]; + int width; + if(s.isEmpty()) { + width = i; + } else { + width = i - s.top() - 1; + } + int area = height * width; + max_area = Math.max(area, max_area); + } + + return max_area; + } + + + public static void main(String[] args) { + + int [] arr = {6, 0, 5, 4, 5, 1, 6}; + + System.out.println(maxAreaInHistogram(arr)); + } +} diff --git a/src/day4/MaximumInEachKWindow.java b/src/day4/MaximumInEachKWindow.java new file mode 100644 index 0000000..877ffb4 --- /dev/null +++ b/src/day4/MaximumInEachKWindow.java @@ -0,0 +1,58 @@ +package day4; + + +import java.util.Deque; +import java.util.LinkedList; + +public class MaximumInEachKWindow { + + + //T.C - O(n) + public static void printMaximum(int [] arr, int k) { + + Deque deque = new LinkedList<>(); + + int i; + for(i = 0; i < k; i++) { + + while(!deque.isEmpty() && arr[i] >= arr[deque.peekLast()]) { + deque.removeLast(); + } + + deque.addLast(i); + } + + + for(; i < arr.length; i++) { + + + System.out.println(arr[deque.peek()]); + + + //remove the elements from start which are outside of window + + if(!deque.isEmpty() && deque.peek() <= i - k) { + deque.removeFirst(); + } + + + while(!deque.isEmpty() && arr[i] >= arr[deque.peekLast()]) { + deque.removeLast(); + } + + deque.addLast(i); + } + + System.out.println(arr[deque.peek()]); + + + } + + public static void main(String[] args) { + + int [] arr = {7, 6, 5, 4, 3, 2, 1}; + + printMaximum(arr, 3); + + } +} diff --git a/src/day4/NextGreaterElement.java b/src/day4/NextGreaterElement.java new file mode 100644 index 0000000..0201614 --- /dev/null +++ b/src/day4/NextGreaterElement.java @@ -0,0 +1,20 @@ +package day4; + + +/** + * + * 1. Create a stack + * 2. Start traversing from end in the array + * if s is empty { + * for current element print -1 and push this current element in stack + * } else { + * if current element is greater than top of the stack { + * keep removing the elements from stack till it will become empty and stack is top is greater than current + * } + * print the top for this current element + * push the current element in stack + * } + * + */ +public class NextGreaterElement { +} diff --git a/src/day4/SortTheStack.java b/src/day4/SortTheStack.java new file mode 100644 index 0000000..c4e2ae0 --- /dev/null +++ b/src/day4/SortTheStack.java @@ -0,0 +1,50 @@ +package day4; + + +public class SortTheStack { + + + public static void addInStack(StackUsingLinkedList s, int element) { + + if (s.isEmpty() || element > s.top()) { + s.push(element); + return; + } + int temp = s.pop(); + addInStack(s, element); + s.push(temp); + + } + + public static void sort(StackUsingLinkedList s) { + + if (s.isEmpty()) { + return; + } + + int element = s.pop(); + sort(s); + addInStack(s, element); + } + + private static void printStack(StackUsingLinkedList s) { + while (!s.isEmpty()) { + System.out.println(s.pop()); + } + } + + public static void main(String[] args) { + + StackUsingLinkedList s = new StackUsingLinkedList(); + s.push(40); + s.push(10); + s.push(-5); + s.push(30); + + sort(s); + + printStack(s); + + + } +} diff --git a/src/day4/StackUse.java b/src/day4/StackUse.java new file mode 100644 index 0000000..967d477 --- /dev/null +++ b/src/day4/StackUse.java @@ -0,0 +1,35 @@ +package day4; + + +import java.util.Stack; + +public class StackUse { + + + public static void main(String[] args) { + + StackUsingLinkedList s = new StackUsingLinkedList(); + + s.push(4); + s.push(5); + s.push(3); + + System.out.println(s.size()); + + + + System.out.println(s.size()); + + + System.out.println(s.getMin()); + + s.pop(); + + System.out.println(s.getMin()); + + + + + } + +} diff --git a/src/day4/StackUsingLinkedList.java b/src/day4/StackUsingLinkedList.java new file mode 100644 index 0000000..3b199d4 --- /dev/null +++ b/src/day4/StackUsingLinkedList.java @@ -0,0 +1,70 @@ +package day4; + + +import day3.Node; + +public class StackUsingLinkedList { + + private Node head = null; + + public void push(int element) { + if(head == null) { + Node stackElement = new Node(element); + stackElement.min = element; + head = stackElement; + } else { + Node stackElement = new Node(element); + int min = head.min; + stackElement.min = Math.min(min, element); + stackElement.next = head; + head = stackElement; + } + } + + public int size() { + + int length = 0; + Node temp = head; + + while(temp != null) { + length++; + temp = temp.next; + } + return length; + } + + + public boolean isEmpty() { + + if(this.size() == 0) { + return true; + } + return false; + } + + public int top() { + if(isEmpty()) { + System.out.println("Some offensive message"); + return Integer.MAX_VALUE; + } + return head.data; + } + + public int pop() { + if(isEmpty()) { + System.out.println("Some offensive message"); + return Integer.MAX_VALUE; + } + int poppedElement = head.data; + head = head.next; + return poppedElement; + } + + + public int getMin() { + return head.min; + } + + + +} diff --git a/src/day5/ConnectNodes.java b/src/day5/ConnectNodes.java new file mode 100644 index 0000000..31431d2 --- /dev/null +++ b/src/day5/ConnectNodes.java @@ -0,0 +1,68 @@ +package day5; + + +public class ConnectNodes { + + + //T.C - O(n) + //SC - Constant + public static void connectLevel(TreeNode root) { + + + while(root != null) { + TreeNode dummyTreeNode = new TreeNode(Integer.MIN_VALUE); + TreeNode childNode = dummyTreeNode; + + while (root != null) { + if (root.left != null) { + childNode.next = root.left; + childNode = childNode.next; + } + + if (root.right != null) { + childNode.next = root.right; + childNode = childNode.next; + } + root = root.next; + } + root = dummyTreeNode.next; + } + } + + + public static void printTree(TreeNode root) { + if(root == null) { + return; + } + + TreeNode temp = root; + while(temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } + System.out.println(); + if(root.left != null) { + printTree(root.left); + } else { + printTree(root.right); + } + + } + + + + + public static void main(String[] args) { + + + TreeNode root = new TreeNode(1); + + TreeNode.takeInput(root); + + connectLevel(root); + + printTree(root); + + + } +} diff --git a/src/day5/ConstructBinaryTree.java b/src/day5/ConstructBinaryTree.java new file mode 100644 index 0000000..7196ff3 --- /dev/null +++ b/src/day5/ConstructBinaryTree.java @@ -0,0 +1,50 @@ +package day5; + + +public class ConstructBinaryTree { + + + public static TreeNode constructTree(int [] inorder, int [] preorder, int preorderIndex, int inStart, int inEnd) { + + + if(inStart > inEnd) { + return null; + } + + TreeNode root = new TreeNode(preorder[preorderIndex]); + + int inorderIndex = -1; + for(int i = inStart; i <= inEnd; i++) { + if(inorder[i] == preorder[preorderIndex]) { + inorderIndex = i; + break; + } + } + + int leftSubTreeSize = inorderIndex - inStart; + + root.left = constructTree(inorder, preorder, preorderIndex + 1, inStart, inorderIndex - 1); + root.right = constructTree(inorder, preorder, preorderIndex + leftSubTreeSize + 1, + inorderIndex + 1, inEnd); + + return root; + } + + + + + public static void main(String[] args) { + + + + int [] inorder = {4,2, 5, 1,3}; + int preOrder[] = {1,2,4,5,3}; + + TreeNode root = constructTree(inorder, preOrder, 0, 0, inorder.length - 1); + + TreeUse.levelOrderTraversalUsingQueue(root); + + + + } +} diff --git a/src/day5/LargestSum.java b/src/day5/LargestSum.java new file mode 100644 index 0000000..5c7544e --- /dev/null +++ b/src/day5/LargestSum.java @@ -0,0 +1,32 @@ +package day5; + + +public class LargestSum { + + + //T.C - O(N) + public static int max = 0; + public static int maximumSum(TreeNode root) { + + if(root == null) { + return 0; + } + int leftSum = maximumSum(root.left); + int rightSum = maximumSum(root.right); + + max = Math.max(max, leftSum + rightSum + root.data); + + return leftSum + rightSum + root.data; + } + + public static void main(String[] args) { + + TreeNode root = new TreeNode(-10); + + TreeNode.takeInput(root); + + int max_sum = maximumSum(root); + + System.out.println(max); + } +} diff --git a/src/day5/NodesAtKDistance.java b/src/day5/NodesAtKDistance.java new file mode 100644 index 0000000..3505c6f --- /dev/null +++ b/src/day5/NodesAtKDistance.java @@ -0,0 +1,88 @@ +package day5; + + +import java.util.ArrayList; + +public class NodesAtKDistance { + + static ArrayList path = new ArrayList<>(); + + //T.C - O(n) + //S.C - node to root path + public static void printNodesAtKLevel(TreeNode root, int targetNode, int k) { + + findPath(root, targetNode); + + for(TreeNode treeNode : path) { + System.out.print(treeNode.data +" "); + } + System.out.println(); + + for(int i = 0; i < path.size(); i++) { + printNodesDownAtKLevel(path.get(i), + k - i, i == 0 ? null : path.get(i - 1)); + } + } + + + private static boolean findPath(TreeNode root, int targetNode) { + + if(root == null) { + return false; + } + + if(root.data == targetNode) { + path.add(root); + return true; + } + + + boolean isFindLeft = findPath(root.left, targetNode); + if(isFindLeft) { + path.add(root); + return true; + } + + boolean isFindRight = findPath(root.right, targetNode); + if(isFindRight) { + path.add(root); + return true; + } + + return false; + } + + private static void printNodesDownAtKLevel(TreeNode node, int currentLevel, TreeNode obstacle) { + + if(node == null || currentLevel < 0 || node == obstacle) { + return; + } + + if(currentLevel == 0) { + System.out.println(node.data); + return; + } + + printNodesDownAtKLevel(node.left, currentLevel - 1, obstacle); + printNodesDownAtKLevel(node.right, currentLevel - 1, obstacle); + + } + + + public static void main(String[] args) { + + + TreeNode root = new TreeNode(1); + + root.left = new TreeNode(2); + root.right = new TreeNode(3); + + root.left.left = new TreeNode(6); + root.left.left.left = new TreeNode(5); + root.left.left.right = new TreeNode(4); + + root.right.right = new TreeNode(10); + + printNodesAtKLevel(root, 2, 2); + } +} diff --git a/src/day5/RightViewBinaryTree.java b/src/day5/RightViewBinaryTree.java new file mode 100644 index 0000000..d5658fe --- /dev/null +++ b/src/day5/RightViewBinaryTree.java @@ -0,0 +1,36 @@ +package day5; + + +public class RightViewBinaryTree { + + + static int alreadyTraversedLevel = 0; + + public static void printRightView(TreeNode root, int currentLevel) { + + if(root == null) { + return; + } + + if(currentLevel > alreadyTraversedLevel) { + System.out.println(root.data); + alreadyTraversedLevel = currentLevel; + } + + printRightView(root.right, currentLevel + 1); + printRightView(root.left, currentLevel + 1); + } + + public static void main(String[] args) { + + TreeNode root = new TreeNode(1); + + root.left = new TreeNode(2); + + root.right = new TreeNode(3); + + root.left.left = new TreeNode(4); + + printRightView(root, 1); + } +} diff --git a/src/day5/TreeNode.java b/src/day5/TreeNode.java new file mode 100644 index 0000000..71a890d --- /dev/null +++ b/src/day5/TreeNode.java @@ -0,0 +1,45 @@ +package day5; + + +import java.util.Scanner; + +public class TreeNode { + + public int data; + + public TreeNode left; + + public TreeNode right; + + TreeNode next; + + public TreeNode(int data) { + this.data = data; + } + + + public static void takeInput(TreeNode root) { + Scanner sc = new Scanner(System.in); + System.out.println("Is left child of node available " + root.data); + boolean isLeft = sc.nextBoolean(); + + if(isLeft) { + System.out.println("Enter the left child for " + root.data); + int data = sc.nextInt(); + TreeNode node = new TreeNode(data); + root.left = node; + takeInput(root.left); + } + + System.out.println("Is Right child of node available " + root.data); + boolean isRight = sc.nextBoolean(); + + if(isRight) { + System.out.println("Enter the Right child for " + root.data); + int data = sc.nextInt(); + TreeNode node = new TreeNode(data); + root.right = node; + takeInput(root.right); + } + } +} diff --git a/src/day5/TreeUse.java b/src/day5/TreeUse.java new file mode 100644 index 0000000..9c28fc3 --- /dev/null +++ b/src/day5/TreeUse.java @@ -0,0 +1,136 @@ +package day5; + + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Stack; + +public class TreeUse { + + + public static void inorderIterative(TreeNode root) { + Stack stack = new Stack<>(); + + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + TreeNode node = stack.pop(); + System.out.println(node.data); + root = node.right; + } + } + + public static void levelOrderTraversal(TreeNode root) { + int height = getHeight(root); + + + for (int i = 1; i <= height; i++) { + printlevel(root, 1, i); + } + } + + private static void printlevel(TreeNode root, int currentLevel, int targetLevel) { + + if(root == null) { + return; + } + if(currentLevel == targetLevel) { + System.out.println(root.data); + return; + } + + printlevel(root.left, currentLevel + 1, targetLevel); + printlevel(root.right, currentLevel + 1, targetLevel); + + } + + + public static void levelOrderTraversalUsingQueue(TreeNode root) { + + Queue queue = new LinkedList<>(); + + queue.add(root); + + helper(queue); + } + + private static void helper(Queue currentQueue) { + + + if(currentQueue.isEmpty()) { + return; + } + + Queue queueForNextLevel = new LinkedList<>(); + + while(!currentQueue.isEmpty()) { + + TreeNode node = currentQueue.poll(); //deque + + System.out.print(node.data +" "); + + if(node.left != null) { + queueForNextLevel.add(node.left); + } + + if(node.right != null) { + queueForNextLevel.add(node.right); + } + } + + System.out.println(); + + helper(queueForNextLevel); + } + + private static int getHeight(TreeNode root) { + + if (root == null) { + return 0; + } + + int leftHeight = getHeight(root.left); + int rightHeight = getHeight(root.right); + + return Math.max(leftHeight, rightHeight) + 1; + } + + + public static void inorderTraversal(TreeNode root) { + + if (root == null) { + return; + } + inorderTraversal(root.left); + System.out.println(root.data); + inorderTraversal(root.right); + } + + public static void main(String[] args) { + + TreeNode root = new TreeNode(1); + + root.left = new TreeNode(2); + + root.right = new TreeNode(3); + + root.left.left = new TreeNode(4); + + inorderTraversal(root); + + System.out.println(); + + inorderIterative(root); + + System.out.println(); + + levelOrderTraversal(root); + + System.out.println(); + + + levelOrderTraversalUsingQueue(root); + } +} diff --git a/src/day6/BSTOperations.java b/src/day6/BSTOperations.java new file mode 100644 index 0000000..368cea4 --- /dev/null +++ b/src/day6/BSTOperations.java @@ -0,0 +1,126 @@ +package day6; + + +import day5.TreeNode; +import day5.TreeUse; + +public class BSTOperations { + + //Average T.C - O(log n) + public static TreeNode deleteNode(TreeNode root, int deleteKey) { //21, 23 + + if(root == null) { + return null; + } + if(deleteKey < root.data) { + root.left = deleteNode(root.left, deleteKey); + } else if (deleteKey > root.data) { + root.right = deleteNode(root.right, deleteKey); + } else { + if (root.left != null && root.right != null) { // 2 Children + int leftMax = max(root.left); //11 + root.data = leftMax; + root.left = deleteNode(root.left, leftMax); + return root; + } else if(root.left != null) { + return root.left; + } else if(root.right != null) { + return root.right; + } + return null; + } + return root; + } + + private static int max(TreeNode root) { + while(root.right != null) { + root = root.right; + } + return root.data; + } + + + public static TreeNode insertNode(TreeNode root, int value) { + + if(root == null) { + TreeNode node = new TreeNode(value); + return node; + } + if(value <= root.data) { + root.left = insertNode(root.left, value); + } else { + root.right = insertNode(root.right, value); + } + return root; + } + + public static boolean searchNode(TreeNode root, int target) { + + if(root == null) { + return false; + } + + if(root.data == target) { + return true; + } + + if(target <= root.data) { + boolean isAvailableInLeft = searchNode(root.left, target); + + if(isAvailableInLeft) { + return true; + } + } else { + boolean isAvailableInRight = searchNode(root.right, target); + + if(isAvailableInRight) { + return true; + } + } + return false; + } + + + + + public static void main(String[] args) { + + TreeNode root = new TreeNode(15); + + insertNode(root, 10); + insertNode(root, 20); + insertNode(root, 6); + insertNode(root, 11); + insertNode(root, 16); + insertNode(root, 23); + + TreeUse.levelOrderTraversalUsingQueue(root); + + System.out.println(); + + System.out.println(searchNode(root, 23)); + + deleteNode(root, 20); + + + TreeUse.levelOrderTraversalUsingQueue(root); + + System.out.println(); + + + deleteNode(root, 10); + + + TreeUse.levelOrderTraversalUsingQueue(root); + + System.out.println(); + + + + + + + + } + +} diff --git a/src/day6/LargestBst.java b/src/day6/LargestBst.java new file mode 100644 index 0000000..1d4a315 --- /dev/null +++ b/src/day6/LargestBst.java @@ -0,0 +1,102 @@ +package day6; + + +import day5.TreeNode; +import day5.TreeUse; + +class TreeNodeInfo { + boolean isBst; + + int size; + + int min; + + int max; + + TreeNodeInfo() { + min = Integer.MAX_VALUE; + max = Integer.MIN_VALUE; + isBst = true; + size = 0; + } + } + +public class LargestBst { + + + public static int largestBstSize(TreeNode root) { + TreeNodeInfo treeNodeInfo = helper(root); + return treeNodeInfo.size; + } + + private static TreeNodeInfo helper(TreeNode root) { + + if(root == null) { + return new TreeNodeInfo(); + } + + TreeNodeInfo leftTreeNodeInfo = helper(root.left); + + TreeNodeInfo rightTreeNodeInfo = helper(root.right); + + TreeNodeInfo result = new TreeNodeInfo(); + + if(leftTreeNodeInfo.isBst == false || rightTreeNodeInfo.isBst == false || + (leftTreeNodeInfo.max > root.data || rightTreeNodeInfo.min <= root.data)) { + result.isBst = false; + result.size = Math.max(leftTreeNodeInfo.size, rightTreeNodeInfo.size); + return result; + } + + result.isBst = true; + result.size = leftTreeNodeInfo.size + rightTreeNodeInfo.size + 1; + if(root.left != null) { + result.min = leftTreeNodeInfo.min; + } else { + result.min = root.data; + } + + if(root.right != null) { + result.max = rightTreeNodeInfo.max; + } else { + result.max = root.data; + } + + return result; + } + + + public static void main(String[] args) { + + TreeNode root = new TreeNode(15); + + root.left = new TreeNode(7); + + root.right = new TreeNode(8); + + root.left.left = new TreeNode(6); + + root.left.right = new TreeNode(9); + + root.right.right = new TreeNode(5); + + root.right.left = new TreeNode(11); + + root.right.left.left = new TreeNode(9); + + root.right.left.right = new TreeNode(13); + + root.right.left.left.left = new TreeNode(7); + root.right.left.left.right = new TreeNode(10); + + + TreeUse.levelOrderTraversalUsingQueue(root); + + System.out.println(); + + + System.out.println(largestBstSize(root)); + + } + +} diff --git a/src/day7/Map.java b/src/day7/Map.java new file mode 100644 index 0000000..e168366 --- /dev/null +++ b/src/day7/Map.java @@ -0,0 +1,107 @@ +package day7; + + +import java.util.ArrayList; + +class MapNode { + int key; + int value; + MapNode next; + + public MapNode(int key, int value) { + this.key = key; + this.value = value; + } +} + +public class Map { + + private ArrayList bucketList; + private int size; + private int bucketlistSize; + + public Map() { + + bucketList = new ArrayList<>(); + bucketlistSize = 11; + + for(int i = 0; i < bucketlistSize; i++) { + bucketList.add(null); + } + } + + + public int size() { + return size; + } + + public boolean isEmpty() { + return size == 0; + } + + + public void put(int key, int value) { + int bucketIndex = getBucketIndex(key); + MapNode head = bucketList.get(bucketIndex); + MapNode temp = head; + + while(temp != null) { + if(temp.key == key) { + temp.value = value; + return; + } + temp = temp.next; + } + MapNode newNode = new MapNode(key, value); + newNode.next = head; + bucketList.set(bucketIndex, newNode); + size++; + + //load factor + if((1.0) * size / bucketlistSize > 0.7) { + rehash(); + } + } + + private void rehash() { + ArrayList temp = bucketList; + bucketList = new ArrayList<>(); + + for(int i = 0; i < bucketlistSize * 2; i++) { + bucketList.add(null); + } + + bucketlistSize = bucketlistSize * 2; + size = 0; + + for(MapNode head : temp) { + while(head != null) { + put(head.key, head.value); + head = head.next; + } + } + } + + + public int get(int key) { + int bucketIndex = getBucketIndex(key); + MapNode head = bucketList.get(bucketIndex); + MapNode temp = head; + while(temp != null) { + if(temp.key == key) { + return temp.value; + } + temp = temp.next; + } + return Integer.MIN_VALUE; + } + + + + private int getBucketIndex(Integer key) { + + int hashCode = Math.abs(key.hashCode()); + int compressed = hashCode % bucketlistSize; + return compressed; + } +} diff --git a/src/day7/MapUse.java b/src/day7/MapUse.java new file mode 100644 index 0000000..7c18283 --- /dev/null +++ b/src/day7/MapUse.java @@ -0,0 +1,14 @@ +package day7; + + +public class MapUse { + + + public static void main(String[] args) { + Map map = new Map(); + map.put(1, 5); + map.put(2, 6); + + System.out.print(map.size()); + } +} diff --git a/src/day7/MergeKSortedArrays.java b/src/day7/MergeKSortedArrays.java new file mode 100644 index 0000000..ae7a641 --- /dev/null +++ b/src/day7/MergeKSortedArrays.java @@ -0,0 +1,72 @@ +package day7; + + +import java.util.PriorityQueue; +import java.util.Scanner; + +class ArrayContainer implements Comparable { + + int arr[]; + int index; + + public ArrayContainer(int[] arr, int index) { + this.arr = arr; + this.index = index; + } + + @Override + public int compareTo(ArrayContainer o) { + return this.arr[this.index] - o.arr[o.index]; + } +} + +public class MergeKSortedArrays { + + + //O(nlogn) + public static int[] mergeArrays(int [][] matrix) { + + int total = 0; + PriorityQueue pq = new PriorityQueue<>(); + + for(int i = 0; i < matrix.length; i++) { + ArrayContainer arrayContainer = new ArrayContainer(matrix[i], 0); + pq.add(arrayContainer); + total = total + matrix[i].length; + } + + int resultant[] = new int[total]; + int resultIndex = 0; + + while(!pq.isEmpty()) { + ArrayContainer arrayContainer = pq.poll(); //log n + + resultant[resultIndex] = arrayContainer.arr[arrayContainer.index]; + resultIndex++; + + if (arrayContainer.index < arrayContainer.arr.length - 1) { + ArrayContainer nextArrayContainer = + new ArrayContainer(arrayContainer.arr, arrayContainer.index + 1); + pq.add(nextArrayContainer); // log n + } + } + + return resultant; + } + + + public static void main(String[] args) { + + + int [] arr1 = {1, 3, 5}; + int [] arr2 = {2,4,6,8}; + int [] arr3 = {9,15, 18, 20}; + + int [] result = mergeArrays(new int[][] {arr1, arr2, arr3}); + + for(int i = 0; i < result.length; i++) { + System.out.print(result[i] + " "); + } + } + +} diff --git a/src/day7/MinHeap.java b/src/day7/MinHeap.java new file mode 100644 index 0000000..a4c805e --- /dev/null +++ b/src/day7/MinHeap.java @@ -0,0 +1,102 @@ +package day7; + + +import java.util.ArrayList; + +public class MinHeap { + + + private ArrayList data; + + public MinHeap() { + data = new ArrayList<>(); + data.add(null); + } + + + public boolean isEmpty() { + if(data.size() == 1) { + return true; + } + return false; + } + + public int size () { + return data.size() - 1; + } + + + public void insert(int element) { + data.add(element); + int currentIndex = data.size() - 1; + int parentIndex = currentIndex / 2; + + while(currentIndex != 1) { + if (data.get(currentIndex) >= data.get(parentIndex)) { + //Everything fine + break; + } else { + int currentData = data.get(currentIndex); + int parentData = data.get(parentIndex); + data.set(currentIndex, parentData); + data.set(parentIndex, currentData); + currentIndex = parentIndex; + parentIndex = currentIndex / 2; + } + } + } + + public int getMin() { + return data.get(1); + } + + + //Heapify Operation -> O(log n) + public int removeMin() { + int min = data.get(1); + + int last = data.get(data.size() - 1); + + data.set(1, last); + data.remove(data.size() - 1); + + + int currentIndex = 1; + int leftChildIndex = 2 * currentIndex; + int rightChildIndex = leftChildIndex + 1; + + while(leftChildIndex < data.size() - 1) { + int minIndex = currentIndex; + int currentData = data.get(currentIndex); + int leftData = data.get(leftChildIndex); + int rightData = data.get(rightChildIndex); + + if (leftData < currentData) { + minIndex = leftChildIndex; + min = data.get(leftChildIndex); + } + + if (rightChildIndex < data.size()) { + if (rightData < data.get(minIndex)) { + minIndex = rightChildIndex; + min = data.get(minIndex); + } + } + + if (minIndex == currentIndex) { + // no need to perform anything + break; + } + + data.set(currentIndex, data.get(minIndex)); + data.set(minIndex, currentData); + currentIndex = minIndex; + leftChildIndex = 2 * currentIndex; + rightChildIndex = leftChildIndex + 1; + } + return min; + } + + + +} diff --git a/src/day7/MinHeapUse.java b/src/day7/MinHeapUse.java new file mode 100644 index 0000000..36356c4 --- /dev/null +++ b/src/day7/MinHeapUse.java @@ -0,0 +1,26 @@ +package day7; + + +public class MinHeapUse { + + + public static void main(String[] args) { + + MinHeap heap = new MinHeap(); + + heap.insert(15); + heap.insert(19); + heap.insert(11); + heap.insert(20); + + System.out.println(heap.getMin()); + + + heap.removeMin(); + + System.out.println(heap.getMin()); + + + + } +} diff --git a/src/day7/MinimumWindow.java b/src/day7/MinimumWindow.java new file mode 100644 index 0000000..83cf04f --- /dev/null +++ b/src/day7/MinimumWindow.java @@ -0,0 +1,72 @@ +package day7; + + +import java.util.HashMap; + +public class MinimumWindow { + + + //O(n) + public static int findMinimumWindow(String s, String p) { + + + HashMap pMap = new HashMap<>(); + + for (int i = 0; i < p.length(); i++) { + if (pMap.containsKey(p.charAt(i))) { + int count = pMap.get(p.charAt(i)); + count++; + pMap.put(p.charAt(i), count); + } else { + pMap.put(p.charAt(i), 1); + } + } + + int start = 0; + int index = 0; + int targetCount = p.length(); + int matchingCount = 0; + HashMap sMap = new HashMap<>(); + int ansSize = 0; + + while (index < s.length()) { + + char ch = s.charAt(index); + sMap.put(ch, sMap.getOrDefault(ch, 0) + 1); + + if (sMap.getOrDefault(ch, 0) <= pMap.getOrDefault(ch, 0)) { + matchingCount++; + } + + while (start < index && matchingCount == targetCount) { + + int tempAns = s.substring(start, index + 1).length(); + if (ansSize == 0 || tempAns < ansSize) + ansSize = tempAns; + + char beginCharacter = s.charAt(start); + + if(sMap.getOrDefault(beginCharacter, 0) == 1) { + sMap.remove(beginCharacter); + } else { + sMap.put(beginCharacter, sMap.get(beginCharacter) - 1); + } + if(sMap.getOrDefault(beginCharacter, 0) < pMap.getOrDefault(beginCharacter, 0)) { + matchingCount--; + } + start++; + } + index++; + } + return ansSize; + } + + + public static void main(String[] args) { + + String s = "avcgdjrtbacb"; + String p = "ab"; + + System.out.print(findMinimumWindow(s, p)); + } +} diff --git a/src/day8/KnapsackProblem.java b/src/day8/KnapsackProblem.java new file mode 100644 index 0000000..c0bacbe --- /dev/null +++ b/src/day8/KnapsackProblem.java @@ -0,0 +1,114 @@ +package day8; + + +public class KnapsackProblem { + + + + + //2^n + public static int knapsackMemoziation(int [] wts, int [] vals, int N, int W, int [][] dp) { + + if (N == 0 || W == 0) { + return 0; + } + + if(dp[N][W] != -1) { + return dp[N][W]; + } + + + if (wts[N - 1] <= W) { + int remainingCapacity = W - wts[N - 1]; + int considerItem = vals[N - 1] + knapsackMemoziation(wts, vals, N - 1, remainingCapacity, dp); + int notConsiderItem = knapsackMemoziation(wts, vals, N - 1, W, dp); + dp[N][W] = Math.max(considerItem, notConsiderItem); + } else { + int notConsiderItem = knapsackMemoziation(wts, vals, N - 1, W, dp); + dp[N][W] = notConsiderItem; + } + return dp[N][W]; + } + + + + //N^2 + public static int maxProfitUsingDynamicApproach(int[] wts, int[] values, int N, int W) { + + int [][] dpMemory = new int[N + 1][W + 1]; + + + for(int i = 1; i < dpMemory.length; i++) { + for(int j = 1; j < dpMemory[0].length; j++) { + if(j >= wts[i -1]) { + + int pickItemProfit = 0; + int non_pickItemProfit = 0; + + int remainingCapacity = j - wts[i - 1]; + pickItemProfit = values [i - 1] + dpMemory[i - 1][remainingCapacity]; + non_pickItemProfit = dpMemory[i - 1][j]; + dpMemory[i][j] = Math.max(pickItemProfit, non_pickItemProfit); + } else { + //don't pick + dpMemory[i][j] = dpMemory[i - 1][j]; + } + } + } + + /* for(int i = 0; i < dpMemory.length; i++) { + for(int j = 0; j < dpMemory[0].length; j++) { + System.out.print(dpMemory[i][j] + " "); + } + System.out.println(); + }*/ + return dpMemory[N][W]; + } + + + public static int maxTarget(int[] wts, int[] values, int N, int W) { + + if (N == 0 || W == 0) { + return 0; + } + + int pick = 0; + int dont_pick = 0; + + if (wts[N - 1] <= W) { + int remainingCapacity = W - wts[N - 1]; + pick = values[N - 1] + maxTarget(wts, values, N - 1, remainingCapacity); + } else { + dont_pick = 0 + maxTarget(wts, values, N - 1, W); + } + + int maxTarget = Math.max(pick, dont_pick); + return maxTarget; + } + + + public static void main(String[] args) { + + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; + int W = 50; + + int [][] dp = new int[val.length + 1] [W + 1]; + + for(int i = 0; i < dp.length; i++) { + for(int j = 0; j < dp[i].length; j++) { + dp[i][j] = -1; + } + } + + System.out.println(maxTarget(wt, val, val.length, W)); + + + System.out.println(knapsackMemoziation(wt, val, val.length, W, dp)); + + System.out.println(maxProfitUsingDynamicApproach(wt, val, val.length, W)); + + + } + +} diff --git a/src/day8/NthFibonacciNumber.java b/src/day8/NthFibonacciNumber.java new file mode 100644 index 0000000..4163b5c --- /dev/null +++ b/src/day8/NthFibonacciNumber.java @@ -0,0 +1,77 @@ +package day8; + + +public class NthFibonacciNumber { + + + // 2^n + public static int fibUsingRecursion(int n) { + if(n < 2) { + return n; + } + + int smallOutput1 = fibUsingRecursion(n- 1); + int smallOutput2 = fibUsingRecursion(n- 2); + + return smallOutput1 + smallOutput2; + } + + + //Recursion + Memoziation + //O(n) + public static int topDownFib(int n, int dpMemory[]) { + + + if(n == 0 || n == 1) { + dpMemory[n] = n; + return n; + } + + //Asking the past + if(dpMemory[n] != - 1) { + return dpMemory[n]; + } + + int smallOutput1 = topDownFib(n- 1, dpMemory); + int smallOutput2 = topDownFib(n- 2, dpMemory); + + dpMemory[n] = smallOutput1 + smallOutput2; + + return dpMemory[n]; + + } + + + + //Tabulation + public static int bottomUp(int n) { + + int[] dp = new int[n + 1]; + + dp[0] = 0; + dp[1] = 1; + + for(int i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; + } + + + public static void main(String[] args) { + + int dp[] = new int[101]; + for(int i = 0; i < dp.length; i++) { + dp[i] = -1; + } + + + System.out.println(bottomUp(1)); + + + System.out.println(fibUsingRecursion(1)); + } + + + +} diff --git a/src/day8/minDenominations.java b/src/day8/minDenominations.java new file mode 100644 index 0000000..ee98e80 --- /dev/null +++ b/src/day8/minDenominations.java @@ -0,0 +1,87 @@ +package day8; + + +public class minDenominations { + + + + //2^n + public static int minCoinsUsingRecursion(int [] denominations, int amount) { + + + if(amount == 0) { + return 0; + } + + int finalAns = Integer.MAX_VALUE; + + for(int i = 0; i < denominations.length; i++) { + + int currentDenomination = denominations[i]; + + int remainingAmount = amount - currentDenomination; + + if(remainingAmount >= 0) { + int smallAns = minCoinsUsingRecursion(denominations, remainingAmount); //0 + + finalAns = Math.min(finalAns, smallAns + 1); //2 + } + } + + return finalAns; + } + + + + //N^2 + public static int minDenominationsUsingDynamic(int [] denominations, int amount) { + + int dp[][] = new int[amount + 1][denominations.length + 1]; + + + for(int i = 0; i <= amount; i++) { + dp[i][0] = i; + } + + //Filling the table + for(int i = 1; i <= amount; i++) { + for(int j = 1; j <= denominations.length; j++) { + if(denominations[j - 1] <= i) { + int remainingAmount = i - denominations[j - 1]; + int pastCoins = dp[remainingAmount][j]; + + int considerCurrentCoin = 1 + pastCoins; //1 + int notConsideringCurrentCoin = dp[i][j - 1]; //0 + + int minCoins = Math.min(considerCurrentCoin, notConsideringCurrentCoin); + + //Save it memory + dp[i][j] = minCoins; + } else { + //Not Considering this coin + dp[i][j] = dp[i][j - 1]; + } + } + } + + for(int i = 0; i <= amount; i++) { + for(int j = 0; j <= denominations.length; j++) { + System.out.print(dp[i][j] + " "); + } + System.out.println(); + } + return dp[amount][denominations.length]; + } + + + public static void main(String[] args) { + + int [] deno = {10,3,5}; + + int amount = 10; + + System.out.println(minCoinsUsingRecursion(deno, amount)); + + System.out.println(minDenominationsUsingDynamic(deno, amount)); + } +} diff --git a/src/day9/CycleDetection.java b/src/day9/CycleDetection.java new file mode 100644 index 0000000..aeecc10 --- /dev/null +++ b/src/day9/CycleDetection.java @@ -0,0 +1,45 @@ +package day9; + + +import java.util.ArrayList; + +public class CycleDetection { + + + public static boolean isCycleAvailable(ArrayList adjancyList[], int V) { + + + boolean marked[] = new boolean[V]; + for (int i = 0; i < V; i++) { + if (!marked[i]) + if (helper(adjancyList, i, marked, -1)) { + return true; + } + } + return false; + } + + + private static boolean helper(ArrayList adjancyList[], int source, + boolean[] marked, int parent) { + + marked[source] = true; + // System.out.print(v + " "); + + ArrayList neighbours = adjancyList[source]; // 4, 3, 2 + for (Integer node : neighbours) { + if (!marked[node]) { + if (helper(adjancyList, node, marked, source)) { //2 //4 + return true; + } + } else if (node != parent) { //2 //4 + return true; + } + } + return false; + } + + public static void main(String[] args) { + + } +} diff --git a/src/day9/Graph.java b/src/day9/Graph.java new file mode 100644 index 0000000..9f6c048 --- /dev/null +++ b/src/day9/Graph.java @@ -0,0 +1,107 @@ +package day9; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class Graph { + + private int V; + + + private ArrayList adjancyList[]; + + + public int getV() { + return V; + } + + public ArrayList[] getAdjancyList() { + return adjancyList; + } + + Graph(int V) { + this.V = V; + + adjancyList = new ArrayList[V]; + for (int i = 0; i < V; i++) { + adjancyList[i] = new ArrayList<>(); + } + } + + public void addEgde(int source, int destination) { + adjancyList[source].add(destination); + adjancyList[destination].add(source); + } + + + public void dfs() { + + boolean marked[] = new boolean[this.V]; + for (int i = 0; i < V; i++) { + if (!marked[i]) + helper(i, marked); + System.out.println(); + } + } + + + public void bfs() { + + boolean marked[] = new boolean[this.V]; + for (int i = 0; i < V; i++) { + if (!marked[i]) + bfsHelper(i, marked); + } + + } + + private void bfsHelper(int v, boolean[] marked) { + Queue q = new LinkedList<>(); + + marked[v] = true; + + q.add(v); + + while(!q.isEmpty()) { + int vertex = q.poll(); + System.out.print(vertex + " "); + ArrayList neighbours = adjancyList[v]; + + for (Integer node : neighbours) { + if (!marked[node]) { + marked[node] = true; + q.add(node); + } + } + } + } + + private void helper(int v, boolean[] marked) { + + marked[v] = true; + System.out.print(v + " "); + + ArrayList neighbours = adjancyList[v]; + for (Integer node : neighbours) { + if (!marked[node]) { + helper(node, marked); + } + } + } + + + public static void main(String[] args) { + + Graph g = new Graph(3); + + g.addEgde(0, 2); + g.addEgde(1, 2); + + g.dfs(); + + g.bfs(); + } + + +} diff --git a/src/day9/MakeZombies.java b/src/day9/MakeZombies.java new file mode 100644 index 0000000..4a21500 --- /dev/null +++ b/src/day9/MakeZombies.java @@ -0,0 +1,113 @@ +package day9; + + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +class Position { + + int x; + int y; + + public Position(int x, int y) { + this.x = x; + this.y = y; + } +} + +public class MakeZombies { + + + //O(m *n) + public static int makingZombies(int[][] grid) { + + Queue q = new LinkedList<>(); + + int totalCreatures = 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[i].length; j++) { + if (grid[i][j] == 1 || grid[i][j] == 2) { + totalCreatures++; + } + if (grid[i][j] == 2) { + q.add(new Position(i, j)); + } + } + } + + int time = 0; + + int zombies = 0; + + + while (!q.isEmpty()) { + + int size = q.size(); + + zombies += size; + + if (zombies == totalCreatures) { + return time; + } + + time++; + + for (int i = 0; i < size; i++) { + + //Position of zombie + Position p = q.poll(); + + //Down + if (p.x + 1 < grid.length && grid[p.x + 1][p.y] == 1) { + grid[p.x + 1][p.y] = 2; + q.add(new Position(p.x + 1, p.y)); + } + + //Up + if(p.x - 1 >= 0 && grid[p.x -1][p.y] == 1) { + grid[p.x - 1][p.y] = 2; + q.add(new Position(p.x - 1, p.y)); + } + + + //Left + if(p.y - 1 >=0 && grid[p.x][p.y - 1] == 1) { + grid[p.x][p.y - 1] = 2; + q.add(new Position(p.x , p.y - 1)); + } + + //Right + if(p.y + 1 < grid[0].length && grid[p.x][p.y + 1] == 1) { + grid[p.x][p.y + 1] = 2; + q.add(new Position(p.x , p.y + 1)); + } + } + + } + + return -1; + } + + public static void main(String[] args) { + + + Scanner sc = new Scanner(System.in); + System.out.println("Enter number of rows"); + int r = sc.nextInt(); + System.out.println("Enter number of cols"); + int c = sc.nextInt(); + int [][] matrix = new int[r][c]; + + for(int i = 0; i < r; i++) { + System.out.println("Enter elements for row" + i); + for(int j = 0; j < c; j++) { + int element = sc.nextInt(); + matrix[i][j] = element; + } + } + + System.out.print(makingZombies(matrix)); + } +} diff --git a/src/day9/Trie.java b/src/day9/Trie.java new file mode 100644 index 0000000..ba8bdb6 --- /dev/null +++ b/src/day9/Trie.java @@ -0,0 +1,94 @@ +package day9; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Set; + +class TrieNode { + + boolean isEnd; + char data; + HashMap children; + + public TrieNode(char data) { + this.data = data; + isEnd = false; + children = new HashMap<>(); + } +} + +public class Trie { + + private TrieNode root; + private int totalWords; + + public Trie() { + root = new TrieNode((char) 48); + } + + public int getTotalWords() { + return totalWords; + } + + public void addWord(String word) { + if(addWordHelper(word, root)) { + totalWords++; + } + } + + private boolean addWordHelper(String word, TrieNode node) { + if(word.length() == 0) { + node.isEnd = true; + return true; + } + TrieNode child = node.children.get(word.charAt(0)); + if(child == null) { + child = new TrieNode(word.charAt(0)); + node.children.put(word.charAt(0), child); + } + boolean isAdded = addWordHelper(word.substring(1), child); + return true; + } + + private ArrayList allWords(TrieNode node) { + + ArrayList output = new ArrayList<>(); + + if(node == null) { + return output; + } + + if(node.isEnd) { + output.add(node.data + ""); + } + + Set children = node.children.keySet(); + for(Character c : children) { + ArrayList childOutput = allWords(node.children.get(c)); + for(String word : childOutput) { + output.add(node.data + word); + } + } + return output; + } + + public ArrayList allWords() { + + ArrayList output = new ArrayList<>(); + + Set children = root.children.keySet(); + + for(Character c : children) { + ArrayList childOutput = allWords(root.children.get(c)); + output.addAll(childOutput); + } + return output; + } + + + + + + +} diff --git a/src/day9/TrieUse.java b/src/day9/TrieUse.java new file mode 100644 index 0000000..cfd3a47 --- /dev/null +++ b/src/day9/TrieUse.java @@ -0,0 +1,25 @@ +package day9; + + +public class TrieUse { + + + public static void main(String[] args) { + + Trie trie = new Trie(); + + trie.addWord("tea"); + trie.addWord("trend"); + trie.addWord("truck"); + trie.addWord("trunck"); + + System.out.println(trie.getTotalWords()); + + for(String s : trie.allWords()) { + System.out.println(s); + } + + trie.remove("truck"); + + } +} diff --git a/src/day9/WordSearch.java b/src/day9/WordSearch.java new file mode 100644 index 0000000..3b45bde --- /dev/null +++ b/src/day9/WordSearch.java @@ -0,0 +1,63 @@ +package day9; + + +public class WordSearch { + + + // M^2 * N^2 + public static boolean isExist(char[][] grid, String word) { + + + boolean[][] visited = new boolean[grid.length][grid[0].length]; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (word.charAt(0) == grid[i][j] && search(grid, word, i, j, 0, visited)) { + return true; + } + } + } + return false; + } + + + private static boolean search(char[][] grid, String word, int i, int j, int index, boolean[][] visited) { + + if (index == word.length()) { + return true; + } + + if (i >= grid.length || i < 0 || j >= grid[i].length || j < 0 || grid[i][j] != word.charAt(index) || + visited[i][j]) { + return false; + } + + visited[i][j] = true; + + if (search(grid, word, i - 1, j, index + 1, visited) || + search(grid, word, i + 1, j, index + 1, visited) + || search(grid, word, i, j - 1, index + 1, visited) || + search(grid, word, i, j + 1, index + 1, visited)) { + return true; + } + + visited[i][j] = false; + + return false; + + } + + + public static void main(String[] args) { + + + char[][] grid = { { 'G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S' }, + { 'G', 'E', 'E', 'K', 'S', 'Q', 'U', 'I', 'Z', 'G', 'E', 'E', 'K' }, + { 'I', 'D', 'E', 'Q', 'A', 'P', 'R', 'A', 'C', 'T', 'I', 'C', 'E' } }; + + + + System.out.print(isExist(grid, "ANT")); + + } +} diff --git a/src/doubts/BottomView.java b/src/doubts/BottomView.java new file mode 100644 index 0000000..0470fb8 --- /dev/null +++ b/src/doubts/BottomView.java @@ -0,0 +1,83 @@ +package doubts; + + +import day5.TreeNode; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; +import java.util.TreeMap; + + +class Pair { + + TreeNode node; + int identifier; + + public Pair(TreeNode node, int identifier) { + this.node = node; + this.identifier = identifier; + } +} + +public class BottomView { + + + public static void bottomView(TreeNode root) { + + if (root == null) { + return; + } + + Queue queue = new LinkedList<>(); + + Pair p = new Pair(root, 0); + queue.add(p); + Map map = new TreeMap<>(); + + while (!queue.isEmpty()) { + + Pair pair = queue.poll(); + + TreeNode node = pair.node; + int value = pair.identifier; + + + map.put(value, node); + + if (node.left != null) { + Pair leftPair = new Pair(node.left, value - 1); + queue.add(leftPair); + } + + if (node.right != null) { + Pair rightPair = new Pair(node.right, value + 1); + queue.add(rightPair); + } + } + + + for (Map.Entry entry : map.entrySet()) { + System.out.print(entry.getValue().data + " "); + } + } + + public static void main (String[]args){ + + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + + root.left.left = new TreeNode(4); + root.left.right = new TreeNode(5); + + root.left.right.left = new TreeNode(8); + root.left.right.right = new TreeNode(9); + + root.right.left = new TreeNode(6); + root.right.right = new TreeNode(7); + + bottomView(root); + } + } diff --git a/src/doubts/KSmallestElementInMatrix.java b/src/doubts/KSmallestElementInMatrix.java new file mode 100644 index 0000000..675a008 --- /dev/null +++ b/src/doubts/KSmallestElementInMatrix.java @@ -0,0 +1,84 @@ +package doubts; + + +import java.util.Scanner; + +public class KSmallestElementInMatrix { + + + //Space - O(1) + public static int kSmallest(int [][] matrix, int k) { + + int cols = matrix[0].length; + int rows = matrix.length; + + int low = matrix[0][0]; + int high = matrix[rows - 1][cols - 1]; + + while(low < high) { + int mid = (low + high) / 2; + int count = getCountSmallerEquals(matrix, mid); + + if(count >= k) { + high = mid; + } else { + low = mid+1; + } + } + return low; + } + + /** + * This function will be giving us the count the number + * of element that are less than and equals to passed target + * @return + */ + private static int getCountSmallerEquals(int [][] matrix, int target) { + + int cols = matrix[0].length; + int rows = matrix.length; + int count = 0; + + int row = rows -1; + int col = 0; + + while(row >= 0 && col < cols) { + + if(matrix[row][col] <= target) { + col++; + count = count + (row + 1); + } else { + row--; + } + } + return count; + } + + public static void main(String[] args) { + + + Scanner sc = new Scanner(System.in); + System.out.println("Enter number of rows"); + int r = sc.nextInt(); + System.out.println("Enter number of cols"); + int c = sc.nextInt(); + int [][] matrix = new int[r][c]; + + for(int i = 0; i < r; i++) { + System.out.println("Enter elements for row" + i); + for(int j = 0; j < c; j++) { + int element = sc.nextInt(); + matrix[i][j] = element; + } + } + + + System.out.println("Enter the value to be searched"); + + int target = sc.nextInt(); + + System.out.println(kSmallest(matrix, target)); + + + } +} diff --git a/src/doubts/SortLinkedList.java b/src/doubts/SortLinkedList.java new file mode 100644 index 0000000..6f24439 --- /dev/null +++ b/src/doubts/SortLinkedList.java @@ -0,0 +1,96 @@ +package doubts; + + +import day3.Node; + +public class SortLinkedList { + + + public static Node mergeSort(Node head) { + + if(head == null || head.next == null) { + return head; + } + + Node mid = getMid(head); + + Node next = mid.next; + mid.next = null; + + + Node left = mergeSort(head); + Node right = mergeSort(next); + + Node mergedLinkedListHead = merge(left, right); + + return mergedLinkedListHead; + + + } + + private static Node merge(Node left, Node right) { + + if(left == null) { + return right; + } else if (right == null) { + return left; + } + + Node resultant = null; + + if(left.data <= right.data) { + resultant = left; + resultant.next = merge(left.next, right); + } else { + resultant = right; + resultant.next = merge(left, right.next); + } + + return resultant; + } + + private static Node getMid(Node head) { + + if(head == null) { + return head; + } + + Node slow = head; + Node fast = head; + + while(fast.next != null && fast.next.next != null) { + fast = fast.next.next; + slow = slow.next; + } + + return slow; + + } + + public static void printList(Node head) { + Node current = head; + + while(current != null) { + System.out.print(current.data + " -> "); + current = current.next; + } + } + + public static void main(String[] args) { + + + Node head = new Node(6); + head.next = new Node(3); + head.next.next = new Node(5); + head.next.next.next = new Node(1); + + + printList(head); + + System.out.println(); + Node result = mergeSort(head); + + printList(result); + + } +}