diff --git a/Filter.class b/Filter.class new file mode 100644 index 0000000..85c3be7 Binary files /dev/null and b/Filter.class differ diff --git a/Filter.java b/Filter.java new file mode 100644 index 0000000..40469aa --- /dev/null +++ b/Filter.java @@ -0,0 +1,17 @@ +public class Filter { + + public static void filterdArray(int[] arr) { + //! filtering process + for(int i = 0; i < arr.length - 1; i++) { + if(arr[i] % 2 != 0) + System.out.print(arr[i] + " "); + } + } + + + + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + filterdArray(arr); + } +} \ No newline at end of file diff --git a/Java DSA.iml b/Java DSA.iml new file mode 100644 index 0000000..cacc8df --- /dev/null +++ b/Java DSA.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Max.class b/Max.class new file mode 100644 index 0000000..5d5910c Binary files /dev/null and b/Max.class differ diff --git a/Max.java b/Max.java new file mode 100644 index 0000000..32f4157 --- /dev/null +++ b/Max.java @@ -0,0 +1,16 @@ +public class Max { + public static void max(int[] arr) { + int max = 0; + for(int i = 0; i < arr.length; i++) { + if(arr[i] > max) + max = arr[i]; + } + + System.out.println(max); + } + + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + max(arr); + } +} \ No newline at end of file diff --git a/Practice.class b/Practice.class new file mode 100644 index 0000000..8c8b96e Binary files /dev/null and b/Practice.class differ diff --git a/Practice.java b/Practice.java new file mode 100644 index 0000000..4374b3d --- /dev/null +++ b/Practice.java @@ -0,0 +1,55 @@ +import java.util.*; + +class Practice { + public static void main(String[] args) { + ArrayList arr = new ArrayList<>(); + + arr.add(4); + arr.add(5); + arr.add(8); + arr.add(9); + arr.add(3); + arr.add(7); + + int target = 4; + + for (int i = 0; i < arr.size(); i++) { + if (arr.get(i) == target) { + arr.remove(arr.get(i)); + } + } + + int first = 0; + int end = arr.size() - 1; + int mid = (first + end) / 2; + + while (mid < end) { + if (arr.get(first) < arr.get(mid)) { + first++; + } + + if (arr.get(first) > arr.get(mid)) { + int temp = arr.get(first); + arr.add(first, arr.get(mid)); + arr.add(mid, temp); + + first++; + } + + if (arr.get(mid) < arr.get(end)) { + end--; + } + + if (arr.get(mid) > arr.get(end)) { + int temp = arr.get(mid); + arr.add(mid, arr.get(end)); + arr.add(end, temp); + + end--; + } + } + + System.out.println("List" + arr); + System.out.println("Sorted List" + arr); + } +} \ No newline at end of file diff --git a/Sum_Array.class b/Sum_Array.class new file mode 100644 index 0000000..e6a0058 Binary files /dev/null and b/Sum_Array.class differ diff --git a/Sum_Array.java b/Sum_Array.java new file mode 100644 index 0000000..f9f5724 --- /dev/null +++ b/Sum_Array.java @@ -0,0 +1,14 @@ +public class Sum_Array { + public static void sum(int[] array) { + int sum = 0; + for(int i = 0; i < array.length - 1; i++) { + sum += array[i]; + } + System.out.println(sum); + } + + public static void main(String[] args) { + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + sum(array); + } +} \ No newline at end of file diff --git a/arrays/Array_Problem_10.java b/arrays/Array_Problem_10.java index 5c63b59..fdea1f9 100644 --- a/arrays/Array_Problem_10.java +++ b/arrays/Array_Problem_10.java @@ -3,49 +3,55 @@ import java.io.*; /* - * Problem :- + * Problem :- * Minimum no of jumps to reach end of an arrays.array */ -/* - * Understanding of The Problem: - - * +/* + * Understanding of The Problem: - + * * Given an arrays.array of integers where each element represents the max number of steps that can be made forward from the element * Write a function to return the minimum no of jumps to reach the end of the arrays.array(starting from the first element). * If an element is 0, they cannot move through that element. */ @SuppressWarnings("unused") public class Array_Problem_10 { - - static int minJumps(int arr[] , int l , int h) { - - //Base case: when source & destination are same - if(h == l) - return 0; - - //When nothing is reachable from the given source - if(arr[l] == 0) - return Integer.MAX_VALUE; - - /* + + // Function to find the minimum number of jumps required to reach the end of the array + public static int findMinimumJumps(int[] jumpDistances, int startingIndex, int endingIndex) { + // Base case: destination reached from the source itself + if (startingIndex == endingIndex) { + return 0; + } + + // Base case: no jump possible from the source + if (jumpDistances[startingIndex] == 0) { + return Integer.MAX_VALUE; + } + + /* * Traverse through all the points reachable from arrays.array[1]. * Recursively get the minimum number of jumps needed to reach arrays.array[h] from these reachable points. */ - - int min = Integer.MAX_VALUE; - for(int i = l + 1 ; i <= h - && i<= l + arr[l] ; i++) { - int jumps = minJumps(arr , i , h); - if(jumps != Integer.MAX_VALUE && jumps + 1 < min) - min = jumps + 1 ; - } - return min; - } - - public static void main(String[] args) { - int arr[] = { 1, 3, 6, 3, 2, 3, 6, 8, 9, 5 }; - int n = arr.length; - System.out.print("Minimum number of jumps to reach end is " + minJumps(arr , 0 , n -1 )); - } + // Explore all reachable destinations from the current position + int minJumps = Integer.MAX_VALUE; + for (int nextIndex = startingIndex + 1; nextIndex <= endingIndex && nextIndex <= startingIndex + jumpDistances[startingIndex]; nextIndex++) { + int jumpsFromNextIndex = findMinimumJumps(jumpDistances, nextIndex, endingIndex); + + // Update minimum jumps if a valid path is found + if (jumpsFromNextIndex != Integer.MAX_VALUE && jumpsFromNextIndex + 1 < minJumps) { + minJumps = jumpsFromNextIndex + 1; + } + } + + return minJumps; + } + + public static void main(String[] args) { + int[] jumpDistances = {1, 3, 6, 3, 2, 3, 6, 8, 9, 5}; + int numberOfElements = jumpDistances.length; + + System.out.println("Minimum number of jumps to reach the end: " + findMinimumJumps(jumpDistances, 0, numberOfElements - 1)); + } } diff --git a/arrays/Array_Problem_17.java b/arrays/Array_Problem_17.java index d3f49fb..e98c07a 100644 --- a/arrays/Array_Problem_17.java +++ b/arrays/Array_Problem_17.java @@ -1,25 +1,25 @@ package arrays; -//? Problem Title :-> Best Time to buy and sell stocks [1] +//? Problem Title :-> Best Time to buy and sell stocks [1] // * You are allowed to buy and sell only once -// ! You are not allowed to sell first and then buy, +// ! You are not allowed to sell first and then buy, // ! (you must buy first and then sell) public class Array_Problem_17 { - public int maxProfit(int[] prices) { + public static int maxProfit(int[] prices) { int mini = prices[0]; int maxProfit = 0; - - int n = prices.size(); + + int n = prices.length; for(int i = 0; i < n; i++) { int cost = prices[i] - mini; maxProfit = Math.max(maxProfit, cost); mini = Math.min(mini, prices[i]); } - + return maxProfit; } diff --git a/arrays/Array_Problem_19.java b/arrays/Array_Problem_19.java index 765b148..cbb8bab 100644 --- a/arrays/Array_Problem_19.java +++ b/arrays/Array_Problem_19.java @@ -1,41 +1,42 @@ package arrays; -/* Problem Title :-> find common elements in 3 sorted arrays */ +/* Problem Title: Find common elements in 3 sorted arrays */ public class Array_Problem_19 { - // This function prints common elements in a1 - void findCommon(int[] a1, int[] a2, int[] a3) { - // Initialize starting indexes for a1[], a2[] and a3[] - int i = 0, j = 0, k = 0; - // Iterate through three arrays while all arrays have elements - while (i < a1.length && j < a2.length && k < a3.length) { - // if x = y and y = z, print any of them and move ahead in all arrays - if (a1[i] >= a2[j] && a2[j] == a3[k]) { - System.out.print(a1[i] + " "); - i++; - k++; + + // This function prints common elements in firstArray + void findCommon(int[] firstArray, int[] secondArray, int[] thirdArray) { + // Initialize starting indices for arrays + int firstIndex = 0, secondIndex = 0, thirdIndex = 0; + + // Iterate through arrays while all have elements + while (firstIndex < firstArray.length && secondIndex < secondArray.length && thirdIndex < thirdArray.length) { + // If elements are equal, print any and move forward in all arrays + if (firstArray[firstIndex] == secondArray[secondIndex] && secondArray[secondIndex] == thirdArray[thirdIndex]) { + System.out.print(firstArray[firstIndex] + " "); + firstIndex++; + thirdIndex++; + } else if (firstArray[firstIndex] < secondArray[secondIndex]) { + // First element is smaller, so move its index + firstIndex++; + } else if (secondArray[secondIndex] < thirdArray[thirdIndex]) { + // Second element is smaller, so move its index + secondIndex++; + } else { + // Third element is smaller, so move its index + thirdIndex++; } - // x < y - else if (a1[j] < a2[j]) - i++; - // y < z - else if (a2[j] < a3[k]) - j++; - // we reach here whem x > y and z < y, i.e., z is smallest - else - k++; } } /* Driver Code */ public static void main(String[] args) { - Array_Problem_19 ob = new Array_Problem_19(); - int a1[] = { 1, 5, 10, 20, 40, 80 }; - int a2[] = { 6, 7, 20, 80, 100 }; - int a3[] = { 3, 4, 15, 20, 30, 70, 80, 120 }; - + Array_Problem_19 object = new Array_Problem_19(); + int[] firstArray = {1, 5, 10, 20, 40, 80}; + int[] secondArray = {6, 7, 20, 80, 100}; + int[] thirdArray = {3, 4, 15, 20, 30, 70, 80, 120}; System.out.print("Common elements are "); - ob.findCommon(a1, a2, a3); + object.findCommon(firstArray, secondArray, thirdArray); } } diff --git a/arrays/Array_Problem_20.java b/arrays/Array_Problem_20.java index e58b8cf..cb70b00 100644 --- a/arrays/Array_Problem_20.java +++ b/arrays/Array_Problem_20.java @@ -1,56 +1,70 @@ package arrays; -/* Problem Title :-> Rearrange the arrays.array in alternating positive and negative items with O(1) extra space - */ +/* Problem Title: Rearrange the array in alternating positive and negative items with O(1) extra space */ public class Array_Problem_20 { - void rightrotate(int[] a, int n, int outofplace, int cur) { - int temp = a[cur]; - for (int i = cur; i > outofplace; i--) { - a[i] = a[i - 1]; + // Rotates elements in the subarray starting from `from` to the right by `steps` positions + private void rightRotate(int[] array, int length, int from, int current) { + int temp = array[current]; + for (int i = current; i > from; i--) { + array[i] = array[i - 1]; } - a[outofplace] = temp; + array[from] = temp; } - void rearrange(int[] a, int n) { + // Rearranges the array in alternating positive and negative items + public void rearrange(int[] array, int length) { - int outofplace = -1; - for (int index = 0; index < n; index++) { - if (outofplace <= 0) { - if (((a[index] >= 0) && (a[outofplace] < 0) || (a[index] < 0) && (a[outofplace] >= 0))) { - if (index - outofplace >= 2) - outofplace = outofplace + 2; - else - outofplace = -1; + // Index of the first out-of-place element (needs to be swapped) + int outOfPlaceIndex = -1; + + for (int index = 0; index < length; index++) { + if (outOfPlaceIndex <= 0) { + // Check if the current element is opposite in sign to the first out-of-place element or if both are negative (need correction) + boolean needsCorrection = ((array[index] >= 0) && (array[outOfPlaceIndex] < 0) || (array[index] < 0) && (array[outOfPlaceIndex] >= 0)); + + if (needsCorrection) { + // If there are more than one element between the current and the out-of-place element, update the out-of-place index to skip those elements + if (index - outOfPlaceIndex >= 2) { + outOfPlaceIndex += 2; + } else { + outOfPlaceIndex = -1; // reset if no correction needed + } } } - if (outofplace == -1) { - if (((a[index] >= 0) && ((index * 0x01) == 0)) || ((a[index] < 0) && (index & 0x01) == 1)) - outofplace = index; + + // Check if the current element needs to be moved (positive at even index or negative at odd index) + if (outOfPlaceIndex == -1) { + boolean needsShift = ((array[index] >= 0) && ((index % 2) == 0)) || ((array[index] < 0) && (index % 2) == 1); + if (needsShift) { + outOfPlaceIndex = index; + } } } } - void printArray(int[] a, int n) { - for (int i = 0; i < n; i++) - System.out.print(a[i] + " "); - System.out.println(" "); + // Prints the array + private void printArray(int[] array, int length) { + for (int i = 0; i < length; i++) { + System.out.print(array[i] + " "); + } + System.out.println(); } public static void main(String[] args) { Array_Problem_20 rearrange = new Array_Problem_20(); - int[] a = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; - int n = a.length; + int[] array = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; + int n = array.length; - System.out.println("Given arrays.array is "); + System.out.println("Given array is "); - rearrange.printArray(a, n); - rearrange.rearrange(a, n); + rearrange.printArray(array, n); + rearrange.rearrange(array, n); - System.out.println("RearrangeD arrays.array is "); + System.out.println("Rearranged array is "); - rearrange.printArray(a, n); + rearrange.printArray(array, n); } } diff --git a/arrays/Array_Problem_21.java b/arrays/Array_Problem_21.java index 4f960f2..5a338cc 100644 --- a/arrays/Array_Problem_21.java +++ b/arrays/Array_Problem_21.java @@ -1,6 +1,6 @@ package arrays; -/* - * Problem Title :-> +/* + * Problem Title :-> * Find if there is any sub arrays.array with sum equal to 0 */ @@ -14,34 +14,43 @@ */ public class Array_Problem_21 { - static Boolean subArrayExists(int[] a) { - // Creates an empty hash set h_s - Set hs = new HashSet<>(); - // Initialise sum of elements - int sum = 0; - // Traverse through the given arrays.array - for(int i = 0; i < a.length; i++) { - // Add current element to sum - sum += a[i]; - /* - * Return true in following cases - * a). Current element is 0 - * b). sum of elements from 0 to i is 0 - * c). sum is already present in hash map - */ - if(a[i] == 0 || sum == 0 || hs.contains(sum)) return true; - // Add sum to hash set - hs.add(sum); - } - // We reach here only when there is no sub_array with 0 sum - return false; - } - // Driver Code - public static void main(String[] args) { - int[] a = {2, 3, -1, -2, 4, 5}; - if(subArrayExists(a)) - System.out.println("Found a subarray with 0 sum"); - else - System.out.println("No Such Sub Array Exists!"); - } + + static boolean subArrayExists(int[] array) { + // Create an empty HashSet to store seen sums + Set seenSums = new HashSet<>(); + // Initialize the sum of elements + int currentSum = 0; + + // Traverse through the array + for (int i = 0; i < array.length; i++) { + // Add current element to the sum + currentSum += array[i]; + + /* + * Return true in the following cases: + * a) Current element is 0. + * b) Sum of elements from 0 to i is 0. + * c) Current sum is already present in the hash set. + */ + if (array[i] == 0 || currentSum == 0 || seenSums.contains(currentSum)) { + return true; + } + + // Add the current sum to the set + seenSums.add(currentSum); + } + + // We reach here only when there is no subarray with 0 sum + return false; + } + + // Driver Code + public static void main(String[] args) { + int[] array = {2, 3, -1, -2, 4, 5}; + if (subArrayExists(array)) { + System.out.println("Found a subarray with 0 sum"); + } else { + System.out.println("No such subarray exists!"); + } + } } diff --git a/arrays/Array_Problem_25.java b/arrays/Array_Problem_25.java index d0e5b87..71f03cf 100644 --- a/arrays/Array_Problem_25.java +++ b/arrays/Array_Problem_25.java @@ -4,86 +4,86 @@ import java.util.*; class Array_Problem_25 { - + static class eleCount{ - int e, c; + int element, count; } - + static void moreThanNdk(int[] a, int n, int k) { - + if(k < 2) return; - + eleCount[] temp = new eleCount[k-1]; - + for(int i = 0; i < k-1; i++) { temp[i] = new eleCount(); } - + for(int i = 0; i < k-1; i++) { - temp[i].c = 0; + temp[i].count = 0; } - + for(int i = 0; i < n; i++) { - + int j; - + for(j = 0; j < k - 1; j++) { - if(temp[j].e == a[i]) { - temp[j].c += 1; + if(temp[j].element == a[i]) { + temp[j].count += 1; break; } } - + if(j == k - 1) { int l; for(l = 0; l < k - 1; l++) { - if(temp[1].c == 0) { - temp[l].e = a[i]; - temp[l].c = 1; + if(temp[1].count == 0) { + temp[l].element = a[i]; + temp[l].count = 1; break; } } - - if(l == k - 1) + + if(l == k - 1) for(l = 0; l < k-1; l++) - temp[l].c -= 1; + temp[l].count -= 1; } } for(int i = 0; i < k -1; i++) { - + int ac = 0; - + for(int j = 0; j < n; j++) { - if(a[j] == temp[i].e) + if(a[j] == temp[i].element) ac++; } - + if(ac > n/k) - System.out.println("Number:" + temp[i].e + " Count:" + ac + "\n"); + System.out.println("Number:" + temp[i].element + " Count:" + ac + "\n"); } } - + // Driver Code public static void main(String[] args) { - + System.out.println("First Test\n"); int[] a1 = {4,5,6,7,8,4,4}; int size = a1.length; int k = 3; moreThanNdk(a1, size, k); - + System.out.println("\nSecond Test\n"); int[] a2 = {4,5,6,7,8,4,4}; size = a2.length; k = 3; moreThanNdk(a2, size, k); - + System.out.println("\nThird Test\n"); int[] a3 = {4,5,6,7,8,4,4}; size = a3.length; k = 3; moreThanNdk(a3, size, k); - + System.out.println("\nFourth Test\n"); int[] a4 = {4,5,6,7,8,4,4}; size = a4.length; diff --git a/arrays/Array_Problem_27.java b/arrays/Array_Problem_27.java index 1e57a33..2e1e434 100644 --- a/arrays/Array_Problem_27.java +++ b/arrays/Array_Problem_27.java @@ -1,6 +1,6 @@ package arrays; -/* Problem Title :-> Find whether an arrays.array is a subset of another arrays.array +/* Problem Title :-> Find whether an array is a subset of another array */ public class Array_Problem_27 { @@ -14,13 +14,13 @@ static boolean isSubSet(int[] a1, int[] a2, int m, int n) { } return true; } - + public static void main(String args[]) { int[] a1 = {11, 1, 13, 21, 3, 7}; int[] a2 = {11, 3, 7, 1}; int m = a1.length; int n = a2.length; - + if(isSubSet(a1, a2, m, n)) System.out.println("a2[] is " + "subset of a1[] "); else diff --git a/arrays/Array_Problem_28.java b/arrays/Array_Problem_28.java index 6095f71..f679bd5 100644 --- a/arrays/Array_Problem_28.java +++ b/arrays/Array_Problem_28.java @@ -1,16 +1,19 @@ package arrays; // ? Problem Title :-> Find whether an array is a subset of another array +import java.util.HashSet; +import java.util.Set; + public class Array_Problem_28 { public static void main(String[] args) { - + int arr1[] = { 11, 1, 13, 21, 3, 7 }; int arr2[] = { 11, 3, 7, 1 }; - + int m = arr1.length; int n = arr2.length; - + Set s = new HashSet(); for (int i = 0; i < m; i++) { s.add(arr1[i]); @@ -20,7 +23,7 @@ public static void main(String[] args) { for (int i = 0; i < n; i++) { s.add(arr2[i]); } - + if (s.size() == p) { System.out.println("arr2[] is subset of arr1[] " + "\n"); } diff --git a/arrays/Array_Problem_30.java b/arrays/Array_Problem_30.java index d078261..23dda9d 100644 --- a/arrays/Array_Problem_30.java +++ b/arrays/Array_Problem_30.java @@ -6,16 +6,16 @@ public static int maxWater(int[] a, int n) { int res = 0; - //For every element of the arrays.array, except first and last element + // For every element of the array, except first and last element for(int i = 1; i < n - 1; i++) { - //Find max element on its left + // Find max element on its left int left = a[i]; for(int j = 0; j < i; j++) { left = Math.max(left, a[j]); } - //Find max element on its left + // Find max element on its right int right = a[i]; for(int j = i + 1; j < n; j++) { right = Math.max(right, a[j]); @@ -27,6 +27,7 @@ public static int maxWater(int[] a, int n) { return res; } + //Driver Code public static void main(String[] args) { int[] a = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; diff --git a/arrays/Array_Problem_32.java b/arrays/Array_Problem_32.java index 57097e1..5bc1db4 100644 --- a/arrays/Array_Problem_32.java +++ b/arrays/Array_Problem_32.java @@ -1,31 +1,46 @@ package arrays; -/* Problem Title :-> find minimum number of operations to make an arrays.array palindrome */ +/** + * This class finds the minimum number of operations required to make an array palindromic. + */ public class Array_Problem_32 { - static int findMinOps(int[] a, int n){ - int ans = 0; - for(int i = 0, j = n-1; i <= j;){ - if(a[i] == a[j]){ - i++; - j--; - } - else if(a[i] > a[j]){ - j--; - a[j] += a[j+1]; - ans++; + /** + * Calculates the minimum operations needed to make the given array a palindrome. + * + * @param arr The input array. + * @param n The length of the array. + * @return The minimum number of operations required. + */ + public static int findMinOps(int[] arr, int n) { + int minOperations = 0; + + // Iterate through the array from both ends, comparing elements. + for (int i = 0, j = n - 1; i <= j; i++, j--) { + if (arr[i] == arr[j]) { + // Elements are already equal, no operation needed. + continue; } - else{ - i++; - a[i] += a[i - 1]; - ans++; + + // Decide which element needs to be incremented based on cost optimization: + if (arr[i] < arr[j]) { + // Add the difference to the smaller element (potentially cheaper). + arr[i] += arr[j] - arr[i]; + } else { + // Add the difference to the larger element. + arr[j] += arr[i] - arr[j]; } + + // Increment operation count. + minOperations++; } - return ans; + + return minOperations; } + public static void main(String[] args) { - int[] a = new int[]{1, 4, 5, 9, 1}; - System.out.println("Count of minimum operations is" + findMinOps(a, a.length)); + int[] arr = {1, 4, 5, 9, 1}; + int minOps = findMinOps(arr, arr.length); + System.out.println("Count of minimum operations is: " + minOps); } - } diff --git a/arrays/Array_Problem_6.java b/arrays/Array_Problem_6.java index 901acec..238cd31 100644 --- a/arrays/Array_Problem_6.java +++ b/arrays/Array_Problem_6.java @@ -9,110 +9,89 @@ public class Array_Problem_6 { - - void printUnion(int[] arr1, int[] arr2, int m, int n) { - // Before finding union, make sure arr1[0..m-1] - // is smaller - if (m > n) { - int[] tempp = arr1; - arr1 = arr2; - arr2 = tempp; - - int temp = m; - m = n; - n = temp; - } - - // Now arr1[] is smaller - // Sort the first arrays.array and print its elements - // (these two steps can be swapped as order in - // output is not important) - Arrays.sort(arr1); - for (int i = 0; i < m; i++) - System.out.print(arr1[i] + " "); - - // Search every element of bigger arrays.array in smaller - // arrays.array and print the element if not found - for (int i = 0; i < n; i++) { - if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) - System.out.print(arr2[i] + " "); - } - } - - // Prints intersection of arr1[0..m-1] and arr2[0..n-1] - void printIntersection(int[] arr1, int[] arr2, int m, - int n) - { - // Before finding intersection, make sure - // arr1[0..m-1] is smaller - if (m > n) { - int[] tempp = arr1; - arr1 = arr2; - arr2 = tempp; - - int temp = m; - m = n; - n = temp; - } - - // Now arr1[] is smaller - // Sort smaller arrays.array arr1[0..m-1] - Arrays.sort(arr1); - - // Search every element of bigger arrays.array in smaller - // arrays.array and print the element if found - for (int i = 0; i < n; i++) { - if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) - System.out.print(arr2[i] + " "); - } - } - - // A recursive binary search function. It returns - // location of x in given arrays.array arr[l..r] is present, - // otherwise -1 - int binarySearch(int[] arr, int l, int r, int x) { - if (r >= l) { - int mid = l + (r - l) / 2; - - // If the element is present at the middle - // itself - if (arr[mid] == x) - return mid; - - // If element is smaller than mid, then it can - // only be present in left subarray - if (arr[mid] > x) - return binarySearch(arr, l, mid - 1, x); - - // Else the element can only be present in right - // subarray - return binarySearch(arr, mid + 1, r, x); - } - - // We reach here when element is not present in - // arrays.array - return -1; - } - - // Driver code - public static void main(String[] args) { - - Array_Problem_6 u_i= new Array_Problem_6(); - - int[] arr1 = { 7, 1, 5, 2, 3, 6 }; - int[] arr2 = { 3, 8, 6, 20, 7 }; - - int m = arr1.length; - int n = arr2.length; - - // Function call - System.out.println("Union of two arrays is "); - u_i.printUnion(arr1, arr2, m, n); - - System.out.println(); - - System.out.println("Intersection of two arrays is "); - u_i.printIntersection(arr1, arr2, m, n); - } + void printUnion(int[] firstArray, int[] secondArray, int firstArrayLength, int secondArrayLength) { + // Ensure the first array is smaller or equal in length + if (firstArrayLength > secondArrayLength) { + int[] temp = firstArray; + firstArray = secondArray; + secondArray = temp; + + int tempLength = firstArrayLength; + firstArrayLength = secondArrayLength; + secondArrayLength = tempLength; + } + + // Sort the smaller array + Arrays.sort(firstArray); + for (int element : firstArray) { + System.out.print(element + " "); + } + + // Find elements in the larger array not present in the smaller array + for (int i = 0; i < secondArrayLength; i++) { + if (binarySearch(firstArray, 0, firstArrayLength - 1, secondArray[i]) == -1) { + System.out.print(secondArray[i] + " "); + } + } + } + + void printIntersection(int[] firstArray, int[] secondArray, int firstArrayLength, int secondArrayLength) { + // Ensure the first array is smaller or equal in length + if (firstArrayLength > secondArrayLength) { + int[] temp = firstArray; + firstArray = secondArray; + secondArray = temp; + + int tempLength = firstArrayLength; + firstArrayLength = secondArrayLength; + secondArrayLength = tempLength; + } + + // Sort the smaller array + Arrays.sort(firstArray); + + // Find elements in the larger array present in the smaller array + for (int i = 0; i < secondArrayLength; i++) { + if (binarySearch(firstArray, 0, firstArrayLength - 1, secondArray[i]) != -1) { + System.out.print(secondArray[i] + " "); + } + } + } + + int binarySearch(int[] array, int low, int high, int element) { + if (high >= low) { + int mid = low + (high - low) / 2; + + if (array[mid] == element) { + return mid; + } + + if (array[mid] > element) { + return binarySearch(array, low, mid - 1, element); + } + + return binarySearch(array, mid + 1, high, element); + } + + return -1; + } + + public static void main(String[] args) { + Array_Problem_6 unionAndIntersection = new Array_Problem_6(); + + int[] firstArray = {7, 1, 5, 2, 3, 6}; + int[] secondArray = {3, 8, 6, 20, 7}; + + int firstArrayLength = firstArray.length; + int secondArrayLength = secondArray.length; + + System.out.println("Union of two arrays is: "); + unionAndIntersection.printUnion(firstArray, secondArray, firstArrayLength, secondArrayLength); + + System.out.println(); + + System.out.println("Intersection of two arrays is: "); + unionAndIntersection.printIntersection(firstArray, secondArray, firstArrayLength, secondArrayLength); + } } diff --git a/arrays/Array_Problem_7.java b/arrays/Array_Problem_7.java index c62119b..14bf325 100644 --- a/arrays/Array_Problem_7.java +++ b/arrays/Array_Problem_7.java @@ -1,34 +1,59 @@ -package arrays; - /* * Write a program to cyclically rotate an arrays.array by one. */ +package arrays; + import java.util.Arrays; import java.util.Scanner; public class Array_Problem_7 { - static void rotate(int[] a){ - int x = a[a.length-1], i; - for (i = a.length-1; i > 0; i--) - a[i] = a[i-1]; - a[0] = x; - } - public static void main(String[] args) { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Get the size of the array from the user + System.out.print("Enter the size of the array: "); + int arraySize = scanner.nextInt(); + + // Create an array to store the input elements + int[] inputArray = new int[arraySize]; + + // Get the elements of the array from the user + System.out.println("Enter the elements of the array:"); + for (int i = 0; i < arraySize; i++) { + inputArray[i] = scanner.nextInt(); + } + + // Print the original array + System.out.println("Original array:"); + System.out.println(Arrays.toString(inputArray)); + + // Perform the cyclic rotation + rotateArray(inputArray); + + // Print the rotated array + System.out.println("Rotated array:"); + System.out.println(Arrays.toString(inputArray)); + + scanner.close(); // Close the scanner resource + } - Scanner sc = new Scanner(System.in); - int n = sc.nextInt(); - int[] a = new int[n]; - for (int i = 0; i < n; i++) - a[i] = sc.nextInt(); + // Function to cyclically rotate an array by one element + public static void rotateArray(int[] array) { + if (array.length == 0) { + return; // Handle empty array case + } - System.out.println("Given Array is"); - System.out.println(Arrays.toString(a)); + // Store the last element of the array + int lastElement = array[array.length - 1]; - rotate(a); + // Shift elements one position to the right + for (int i = array.length - 2; i >= 0; i--) { + array[i + 1] = array[i]; + } - System.out.println("Rotated Array is"); - System.out.println(Arrays.toString(a)); - } + // Place the last element at the beginning + array[0] = lastElement; + } } diff --git a/arrays/Array_Problem_8.java b/arrays/Array_Problem_8.java index 44abd04..939c3b8 100644 --- a/arrays/Array_Problem_8.java +++ b/arrays/Array_Problem_8.java @@ -4,29 +4,58 @@ * find Largest sum contiguous Sub-arrays.array */ +// public class Array_Problem_8 { + +// public static void main (String[] args) +// { +// int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; +// System.out.println("Maximum contiguous sum is " + maxSubArraySum(a)); +// } + +// static int maxSubArraySum(int a[]) +// { +// int size = a.length; +// int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + +// for (int i = 0; i < size; i++) +// { +// max_ending_here = max_ending_here + a[i]; +// if (max_so_far < max_ending_here) +// max_so_far = max_ending_here; + +// if (max_ending_here < 0) +// max_ending_here = 0; +// } +// return max_so_far; +// } + +// } + public class Array_Problem_8 { - public static void main (String[] args) - { - int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; - System.out.println("Maximum contiguous sum is " + maxSubArraySum(a)); - } - - static int maxSubArraySum(int a[]) - { - int size = a.length; - int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; - - for (int i = 0; i < size; i++) - { - max_ending_here = max_ending_here + a[i]; - if (max_so_far < max_ending_here) - max_so_far = max_ending_here; - - if (max_ending_here < 0) - max_ending_here = 0; - } - return max_so_far; - } + public static void main(String[] args) { + int[] inputArray = {-2, -3, 4, -1, -2, 1, 5, -3}; + int maximumContiguousSum = findMaximumContiguousSubarraySum(inputArray); + System.out.println("Maximum contiguous sum is: " + maximumContiguousSum); + } + + static int findMaximumContiguousSubarraySum(int[] inputArray) { + int arrayLength = inputArray.length; + int currentMaximumSum = Integer.MIN_VALUE; // Tracks the maximum sum found so far + int currentSubarraySum = 0; // Tracks the sum of the current subarray + + for (int currentIndex = 0; currentIndex < arrayLength; currentIndex++) { + currentSubarraySum += inputArray[currentIndex]; + + if (currentMaximumSum < currentSubarraySum) { + currentMaximumSum = currentSubarraySum; + } + + if (currentSubarraySum < 0) { // Start a new subarray if the sum becomes negative + currentSubarraySum = 0; + } + } + return currentMaximumSum; + } } diff --git a/arrays/Array_Problem_9.java b/arrays/Array_Problem_9.java index d843283..0750372 100644 --- a/arrays/Array_Problem_9.java +++ b/arrays/Array_Problem_9.java @@ -3,63 +3,59 @@ //Minimize the maximum difference between heights [V.IMP] public class Array_Problem_9 { + // Modifies the array by subtracting/adding k to every element such that the difference + // between maximum and minimum is minimized + static int getMinimumDifference(int[] numbers, int numberOfElements, int adjustmentValue) { + if (numberOfElements == 1) { + return 0; + } - // Modifies the arrays.array by subtracting/adding k to every element such that the difference - // between maximum and minimum is minimized - static int getMinDiff(int arr[], int n, int k) - { - if (n == 1) - return 0; - - // Sort all elements - Arrays.sort(arr); - - // Initialize result - int ans = arr[n-1] - arr[0]; - - // Handle corner elements - int small = arr[0] + k; - int big = arr[n-1] - k; - int temp = 0; - - if (small > big) - { - temp = small; - small = big; - big = temp; - } - - // Traverse middle elements - for (int i = 1; i < n-1; i ++) - { - int subtract = arr[i] - k; - int add = arr[i] + k; - - // If both subtraction and addition - // do not change diff - if (subtract >= small || add <= big) - continue; - - // Either subtraction causes a smaller number or addition causes a greater number. - // Update small or big using greedy approach (If big - subtract causes smaller difference , - // update small Else update big) - if (big - subtract <= add - small) - small = subtract; - else - big = add; - } - - return Math.min(ans, big - small); - } - - // Driver function to test the above function - public static void main(String[] args) - { - int arr[] = {4, 6}; - int n = arr.length; - int k = 10; - System.out.println("Maximum difference is "+ - getMinDiff(arr, n, k)); - } + // Sort all elements + Arrays.sort(numbers); + + // Initialize result + int difference = numbers[numberOfElements - 1] - numbers[0]; + + // Handle corner elements + int smallestAdjustedValue = numbers[0] + adjustmentValue; + int largestAdjustedValue = numbers[numberOfElements - 1] - adjustmentValue; + int temp; + + if (smallestAdjustedValue > largestAdjustedValue) { + temp = smallestAdjustedValue; + smallestAdjustedValue = largestAdjustedValue; + largestAdjustedValue = temp; + } + + // Traverse middle elements + for (int i = 1; i < numberOfElements - 1; i++) { + int subtractValue = numbers[i] - adjustmentValue; + int addValue = numbers[i] + adjustmentValue; + + // If both subtraction and addition do not change the difference, skip + if (subtractValue >= smallestAdjustedValue || addValue <= largestAdjustedValue) { + continue; + } + + // Update smallest or largest value based on their impact on the difference + if (largestAdjustedValue - subtractValue <= addValue - smallestAdjustedValue) { + smallestAdjustedValue = subtractValue; + } else { + largestAdjustedValue = addValue; + } + } + + return Math.min(difference, largestAdjustedValue - smallestAdjustedValue); + } + + // Driver function to test the above function + public static void main(String[] args) { + int[] numbers = {4, 6}; + int numberOfElements = numbers.length; + int adjustmentValue = 10; + + System.out.println("Minimum difference after adjustment: " + + getMinimumDifference(numbers, numberOfElements, adjustmentValue)); + } } diff --git a/arrays/FRE.java b/arrays/FRE.java index 5813ff5..1841166 100644 --- a/arrays/FRE.java +++ b/arrays/FRE.java @@ -4,37 +4,51 @@ //Java Program for First Repeating Element public class FRE { - public static void main(String[] args) { - - @SuppressWarnings("resource") - Scanner sc = new Scanner(System.in); - int n = sc.nextInt(); - - int a[] = new int[n]; - for(int i = 0; i < n; i++) - a[i] = sc.nextInt(); - - int N = (int) (1e6+2); - - //Array Input in Java - int idx[] = new int[N]; - for (int i = 0; i < N; i++) - idx[i] = -1; - - int minidx = Integer.MAX_VALUE; - - for (int i = 0; i < n; i++){ - if(idx[a[i]] != -1) - minidx = Math.min(minidx, idx[a[i]]); - else - idx[a[i]] = i; - } - - if(minidx == Integer.MAX_VALUE) - System.out.println("-1"); - - else - System.out.println(minidx + 1); - } - -} + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Get the number of elements in the array + System.out.print("Enter the number of elements: "); + int numberOfElements = scanner.nextInt(); + + // Create an array to store the input elements + int[] inputArray = new int[numberOfElements]; + + // Get the input elements from the user + System.out.println("Enter the elements of the array:"); + for (int i = 0; i < numberOfElements; i++) { + inputArray[i] = scanner.nextInt(); + } + + // Create an array to store indices of first occurrences (large enough to avoid overflow) + int[] firstOccurrenceIndices = new int[1000002]; // Can be adjusted based on expected input range + + // Initialize all indices to -1 (not seen) + for (int i = 0; i < firstOccurrenceIndices.length; i++) { + firstOccurrenceIndices[i] = -1; + } + + // Find the first repeating element and its index + int minIndex = Integer.MAX_VALUE; // Initialize with largest possible value + for (int i = 0; i < numberOfElements; i++) { + int element = inputArray[i]; + + // If the element has already been seen, update the minimum index + if (firstOccurrenceIndices[element] != -1) { + minIndex = Math.min(minIndex, firstOccurrenceIndices[element]); + } else { + // Store the current index as the first occurrence of this element + firstOccurrenceIndices[element] = i; + } + } + + // Print the result + if (minIndex == Integer.MAX_VALUE) { + System.out.println("No repeating element found"); + } else { + System.out.println("First repeating element index: " + (minIndex + 1)); + } + + scanner.close(); // Close the scanner resource + } +} \ No newline at end of file diff --git a/arrays/KadanesAlgorithm.java b/arrays/KadanesAlgorithm.java index de15f21..2adcb29 100644 --- a/arrays/KadanesAlgorithm.java +++ b/arrays/KadanesAlgorithm.java @@ -4,28 +4,39 @@ /* * Kadane's Algorithm to find the maxSubarray Sum in O(n)[Linear Time Complexity] */ + public class KadanesAlgorithm { - public static void main(String[] args) { - @SuppressWarnings("resource") - Scanner sc = new Scanner(System.in); - int n = sc.nextInt(); - int a[]=new int[n]; - - for(int i=0;i Minimum no. of operations required to make an arrays.array palindrome */ // class Array_Problem_35 { class FindMinOps { diff --git a/dp/Coin_change_problem.java b/dp/Coin_change_problem.java index 2948f53..4ca95ee 100644 --- a/dp/Coin_change_problem.java +++ b/dp/Coin_change_problem.java @@ -1,14 +1,14 @@ package dp; -class Coin_change_problem { - static int count(int[] S, int m, int n) { +Class Coin_change_problem { + static int count(int[] array, int m, int n) { if (n == 0) return 1; if (n < 0) return 0; if (m <= 0) return 0; - return count(S, m - 1, n) + count(S, m, n - S[m - 1]); + return count(array, m - 1, n) + count(array, m, n - array[m - 1]); } public static void main(String[] args) { diff --git a/graphs/DFS.java b/graphs/DFS.java index c0f11cf..f6af91f 100644 --- a/graphs/DFS.java +++ b/graphs/DFS.java @@ -3,8 +3,13 @@ /* Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. - The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. - So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. + The algorithm starts at the root node + (selecting some arbitrary node as the root node in the case of a graph) + and explores as far as possible along each branch before backtracking. + So the basic idea is to + start from the root or any arbitrary node + and mark the node and move to the adjacent unmarked node + and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally, print the nodes in the path. */ diff --git a/graphs/Graph_Problem_06.java b/graphs/Graph_Problem_06.java index 0ddd428..6cd5864 100644 --- a/graphs/Graph_Problem_06.java +++ b/graphs/Graph_Problem_06.java @@ -3,64 +3,68 @@ // Problem Title => Search in a Maze. -/* -* Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N - 1, N - 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it. -Note: In a path, no cell can be visited more than one time. - -Example 1: - -Input: -N = 4 -m[][] = {{1, 0, 0, 0}, - {1, 1, 0, 1}, - {1, 1, 0, 0}, - {0, 1, 1, 1}} -Output: -DDRDRR DRDDRR -Explanation: -The rat can reach the destination at -(3, 3) from (0, 0) by two paths - DRDDRR -and DDRDRR, when printed in sorted order -we get DDRDRR DRDDRR. -Example 2: -Input: -N = 2 -m[][] = {{1, 0}, - {1, 0}} -Output: --1 -Explanation: -No path exists and destination cell is -blocked.*/ +/** + * Consider a rat placed at (0, 0) in a square matrix of order N * N. + * It has to reach the destination at (N - 1, N - 1). + * Find all possible paths that the rat can take to reach from source to destination. + * The directions in which the rat can move are 'U'(up), 'D'(down), 'L' (left), 'R' (right). + * Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it. + * + * Note: In a path, no cell can be visited more than one time. +*/ + +/** + * Example 1: + * Input: + * N = 4 + * m[][] = {{1, 0, 0, 0},{1, 1, 0, 1},{1, 1, 0, 0}, {0, 1, 1, 1}} + * + * Output: DDRDRR DRDDRR + * Explanation: The rat can reach the destination at (3, 3) from (0, 0) by two paths - DRDDRR +and DDRDRR, when printed in sorted order we get -> DDRDRR DRDDRR. + */ + +/** + * Example 2: + * Input: + * N = 2 + * m[][] = {{1, 0}, {1, 0}} + * + * Output: -1 + * Explanation: No path exists and destination cell is blocked. + * */ /* -* Approach => -* 1. Start from the initial index (i.e. (0,0)) and look for the valid moves through the adjacent cells in the order Down->Left->Right->Up (to get the sorted paths) in the grid. -* 2. If the move is possible, then move to that cell while storing the character corresponding to the move(D,L,R,U) and again start looking for the valid move until the last index (i.e. (n-1,n-1)) is reached. -* 3. Also, keep on marking the cells as visited and when we traversed all the paths possible from that cell, -* then unmark that cell for other different paths and remove the character from the path formed. + +/** Approach => + * 1. Start from the initial index (i.e. (0,0)) and look for the valid moves through the adjacent cells in the order Down->Left->Right->Up (to get the sorted paths) in the grid. + * + * 2. If the move is possible, then move to that cell while storing the character corresponding to the move(D,L,R,U) and again start looking for the valid move until the last index (i.e. (n-1,n-1)) is reached. + * + * 3. Also, keep on marking the cells as visited and when we traversed all the paths possible from that cell, then unmark that cell for other different paths and remove the character from the path formed. * 4. As the last index of the grid(bottom right) is reached, then store the traversed path. -* */ +*/ + public class Graph_Problem_06{ // Vector to store all the possible paths static Vector possiblePaths = new Vector<>(); static String path = ""; - static final int MAX = 5; + static final int MAX = 5; // Function returns true if the move taken is valid else it will return false. - static boolean isSafe(int row, int col, int[][] m, int n, boolean[][] visited) { - return ( row != -1 && row != n && col != -1 && col != n && !visited[row][col] && m[row][col] != 0) ; + static boolean isSafe(int row, int col, int[][] maze, int lengthOfMaze, boolean[][] visited) { + return ( row != -1 && row != lengthOfMaze && col != -1 && col != lengthOfMaze && !visited[row][col] && maze[row][col] != 0) ; } // Function to print all the possible paths from (0, 0) to (n-1, n-1). - static void printPathUtil(int row, int col, int[][] m, int n, boolean[][] visited) { + static void printPathUtil(int row, int col, int[][] maze, int lengthOfMaze, boolean[][] visited) { // This will check the initial point (i.e. (0, 0)) to start the paths. - if (row == -1 || row == n || col == -1 || col == n || visited[row][col] || m[row][col] == 0) + if (row == -1 || row == lengthOfMaze || col == -1 || col == lengthOfMaze || visited[row][col] || maze[row][col] == 0) return; // If reach the last cell (n-1, n-1) then store the path and return - if (row == n - 1 && col == n - 1) { + if (row == lengthOfMaze - 1 && col == lengthOfMaze - 1) { possiblePaths.add(path); return; } @@ -71,30 +75,30 @@ static void printPathUtil(int row, int col, int[][] m, int n, boolean[][] visite // Try for all the 4 directions (down, left, right, up) in the given order to get the paths in lexicographical order // Check if downward move is valid - if (isSafe(row + 1, col, m, n, visited)) { + if (isSafe(row + 1, col, maze, lengthOfMaze, visited)) { path += 'D'; - printPathUtil(row + 1, col, m, n, visited); + printPathUtil(row + 1, col, maze, lengthOfMaze, visited); path = path.substring(0, path.length() - 1); } // Check if the left move is valid - if (isSafe(row, col - 1, m, n, visited)) { + if (isSafe(row, col - 1, maze, lengthOfMaze, visited)) { path += 'L'; - printPathUtil(row, col - 1, m, n, visited); + printPathUtil(row, col - 1, maze, lengthOfMaze, visited); path = path.substring(0, path.length() - 1); } // Check if the right move is valid - if (isSafe(row, col + 1, m, n, visited)) { + if (isSafe(row, col + 1, maze, lengthOfMaze, visited)) { path += 'R'; - printPathUtil(row, col + 1, m, n, visited); + printPathUtil(row, col + 1, maze, lengthOfMaze, visited); path = path.substring(0, path.length() - 1); } // Check if the upper move is valid - if (isSafe(row - 1, col, m, n, visited)) { + if (isSafe(row - 1, col, maze, lengthOfMaze, visited)) { path += 'U'; - printPathUtil(row - 1, col, m, n, visited); + printPathUtil(row - 1, col, maze, lengthOfMaze, visited); path = path.substring(0, path.length() - 1); } @@ -103,11 +107,11 @@ static void printPathUtil(int row, int col, int[][] m, int n, boolean[][] visite } // Function to store and print all the valid paths - static void printPath(int[][] m, int n) { - boolean [][]visited = new boolean[n][MAX]; + static void printPath(int[][] maze, int lengthOfMaze) { + boolean [][]visited = new boolean[lengthOfMaze][MAX]; // Call the utility function to find the valid paths - printPathUtil(0, 0, m, n, visited); + printPathUtil(0, 0, maze, lengthOfMaze, visited); // Print all possible paths for (String possiblePath : possiblePaths) System.out.print(possiblePath + " "); diff --git a/graphs/a b/graphs/a deleted file mode 100644 index e69de29..0000000 diff --git a/index.html b/index.html index 93c0c0a..aa5dba6 100644 --- a/index.html +++ b/index.html @@ -18,7 +18,7 @@ @@ -36,10 +36,9 @@

Menu

@@ -49,7 +48,7 @@

Menu

This is DSA 450 Questions repo, a free, fully java based resource to find code of Love babber 450 DSA Sheet

-

Etiam quis viverra lorem, in semper lorem. Sed nisl arcu euismod sit amet nisi euismod sed cursus arcu elementum ipsum arcu vivamus quis venenatis orci lorem ipsum et magna feugiat veroeros aliquam. Lorem ipsum dolor sit amet nullam dolore.

+

This repository provides Java code solutions for the problems in Love Babbar's popular DSA 450 cheat sheet, a valuable resource for programmers preparing for coding interviews and practicing fundamental data structures and algorithms.

@@ -115,7 +114,7 @@

Recursion & Backtracking

Linked List

-

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

+

Unordered collection, dynamic size, sequential access.

@@ -137,7 +136,7 @@

Greedy

Trees & Heaps

-

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

+

Hierarchical structure, efficient searching/sorting.

@@ -148,7 +147,7 @@

Trees & Heaps

Graphs

-

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

+

Network of nodes (vertices) connected by edges.

@@ -170,7 +169,7 @@

Bit Manipulation

Stack & Queues

-

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

+

Stack a LIFO (Last In First Out), efficient push/pop. Queue a FIFO (First In First Out), efficient enqueue/dequeue.

diff --git a/linkedList/Problem_12.java b/linkedList/Problem_12.java index ba148ee..77c58d7 100644 --- a/linkedList/Problem_12.java +++ b/linkedList/Problem_12.java @@ -1,76 +1,101 @@ package linkedList; -// Pronblem Title => Merge Sort for linked lists [Very Important]. + public class Problem_12 { - static Node head1, head2; static class Node { - int data; Node next; - Node(int d) { - data = d; - next = null; + Node(int data) { + this.data = data; + this.next = null; } } -static Node mergeSort(Node head) { - if(head == null || head.next == null) - return head; - - Node middle = getMiddle(head); - Node right = middle.next; - middle.next = null; - Node left = mergeSort(left); - Node left1 = mergeSort(left); - Node left2 = mergeSort(right); - return merge(left1, left2); -} + static Node head; // Assuming a single head for the merged list -static Node getMiddle(Node head) { - Node slow = head; - Node fast = head.next; + public static void main(String[] args) { + + // Sample linked lists + Problem_12.head = insert(head, 7); + Problem_12.head = insert(head, 5); + Problem_12.head = insert(head, 3); + Problem_12.head = insert(head, 1); - while(fasty != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; + Node sortedHead = mergeSort(head); + printList(sortedHead); } - return slow; -} + static Node insert(Node head, int data) { + Node newNode = new Node(data); + newNode.next = head; + return newNode; + } + + static Node getMiddle(Node head) { + if (head == null || head.next == null) { + return head; // Handle empty or single-node lists + } -static Node merge(Node head1, Node head2) { - if(head1 == null) - return head2; + Node slow = head; + Node fast = head.next; - if(head2 == null) - return head1; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } - if(head1.data < head2.data) { - head1.next = merge(head1.next, head2); - return head1; - } else { - head2.next = merge(head1, head2.next); - return head2; + return slow; } -} - public static void main(String[] args) { - Problem_12 list = new Problem_12(); + static Node mergeSort(Node head) { + if (head == null || head.next == null) { + return head; // Handle empty or single-node lists + } + + Node middle = getMiddle(head); + Node right = middle.next; + middle.next = null; // Separate the lists + + Node left = mergeSort(head); // Recursive call for the left half + Node rightSorted = mergeSort(right); // Recursive call for the right half - list.head1 = new Node(1); - list.head1.next = new Node(3); - list.head1.next.next = new Node(5); - list.head1.next.next.next = new Node(7); + return merge(left, rightSorted); // Merge the sorted halves + } - list.head2 = new Node(2); - list.head2.next = new Node(4); - list.head2.next.next = new Node(6); - list.head2.next.next.next = new Node(8); + static Node merge(Node left, Node right) { + if (left == null) { + return right; + } else if (right == null) { + return left; + } - Node result = mergeSort(head1); - printList(result); + // Merge the linked lists in sorted order + Node mergedHead = (left.data < right.data) ? left : right; + Node current = mergedHead; + + while (left != null && right != null) { + if (left.data < right.data) { + current.next = left; + left = left.next; + } else { + current.next = right; + right = right.next; + } + current = current.next; + } - + // Append the remaining elements (if any) + current.next = (left != null) ? left : right; + + return mergedHead; } -} \ No newline at end of file + + static void printList(Node head) { + while (head != null) { + System.out.print(head.data + " -> "); + head = head.next; + } + System.out.println("null"); + } +} diff --git a/searchingSortingProblems/SSP_Problem_09.java b/searchingSortingProblems/SSP_Problem_09.java index ccfb1f4..d0d0c36 100644 --- a/searchingSortingProblems/SSP_Problem_09.java +++ b/searchingSortingProblems/SSP_Problem_09.java @@ -1,13 +1,13 @@ -import java.util.*; -import java.lang.*; +package searchingSortingProblems; + import java.util.Scanner; // Program Title => Searching in an arrays.array where adjacent differ at most k. -/* example : +/* example : I/P = a[] = {4, 5, 6, 7, 6}, k = 1, x = 6. O/P = 2 - This first index of 6 is 2. + This first index of 6 is 2. */ public class SSP_Problem_09 { diff --git a/searchingSortingProblems/SSP_Problem_11.java b/searchingSortingProblems/SSP_Problem_11.java index 274f882..592c9ff 100644 --- a/searchingSortingProblems/SSP_Problem_11.java +++ b/searchingSortingProblems/SSP_Problem_11.java @@ -1,3 +1,5 @@ +package searchingSortingProblems; + // Problem Title => find four elements that sum to a given value import java.util.*; diff --git a/strings/Problem_1.java b/strings/Problem_1.java index 5f80714..bc27cbf 100644 --- a/strings/Problem_1.java +++ b/strings/Problem_1.java @@ -1,15 +1,59 @@ package strings; -import java.util.*; +import java.util.Scanner; -// Title ==> Reverse a string public class Problem_1 { + public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - String input = sc.nextLine(); - // conversion from String object to StringBuffer - StringBuffer sbr = new StringBuffer(input); - sbr.reverse(); - System.out.println(sbr); + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter a string to reverse: "); + String inputString = scanner.nextLine(); + + System.out.println("Choose reversal method (1 or 2):"); + System.out.println("1. Using StringBuffer"); + System.out.println("2. In-place character swapping"); + + int choice = scanner.nextInt(); + + String reversedString; + if (choice == 1) { + reversedString = reverseUsingStringBuilder(inputString); + } else if (choice == 2) { + reversedString = reverseUsingCharacterSwapping(inputString); + } else { + System.out.println("Invalid choice. Using default (StringBuffer)"); + reversedString = reverseUsingStringBuilder(inputString); + } + + System.out.println("Reversed String: " + reversedString); + + scanner.close(); + } + + public static String reverseUsingStringBuilder(String inputString) { + StringBuilder stringBuilder = new StringBuilder(inputString); + return stringBuilder.reverse().toString(); + } + + /** + * Reverses the string in-place by swapping characters from start and end. + * (This approach avoids creating a new String object) + */ + public static String reverseUsingCharacterSwapping(String inputString) { + int startIndex = 0; + int endIndex = inputString.length() - 1; + + char[] charArray = inputString.toCharArray(); + while (startIndex < endIndex) { + char temp = charArray[startIndex]; + charArray[startIndex] = charArray[endIndex]; + charArray[endIndex] = temp; + + startIndex++; + endIndex--; + } + + return String.valueOf(charArray); // Convert char array back to String } -} \ No newline at end of file +} diff --git a/strings/Problem_10.java b/strings/Problem_10.java index 5f5d843..c132d56 100644 --- a/strings/Problem_10.java +++ b/strings/Problem_10.java @@ -1,4 +1,5 @@ package strings; + import java.util.*; // Problem Title => Print all subsequences of a String @@ -7,29 +8,29 @@ public class Problem_10 { // str : Stores input string // n : Length of str. - // curr : Stores current permutation - // index : Index in current permutation, curr - static void printSubSeqRec(String str, int n, int idx, String curr){ - if(idx == n) + // currentPermutation : Stores current Permutation + // index : Index in current Permutation + static void printSubSeqRec(String str, int n, int idx, String currentPermutation) { + if (idx == n) return; - if(curr != null && !curr.trim().isEmpty()) - System.out.println(curr); + if (currentPermutation != null && !currentPermutation.trim().isEmpty()) + System.out.println(currentPermutation); for (int i = idx + 1; i < n; i++) { - curr += str.charAt(i); - printSubSeqRec(str, n, i, curr); + currentPermutation += str.charAt(i); + printSubSeqRec(str, n, i, currentPermutation); // backtracking - curr = curr.substring(0, curr.length() - 1); + currentPermutation = currentPermutation.substring(0, currentPermutation.length() - 1); } } // Generates power set in lexicographic order. - static void printSubSeq(String str){ + static void printSubSeq(String str) { int index = -1; - String curr = ""; - printSubSeqRec(str, str.length(), index, curr); + String currentPermutation = ""; + printSubSeqRec(str, str.length(), index, currentPermutation); } // Driver Code @@ -37,5 +38,6 @@ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); printSubSeq(str); + sc.close(); } } \ No newline at end of file diff --git a/strings/Problem_11_1.java b/strings/Problem_11_1.java index 4d04c75..f661a38 100644 --- a/strings/Problem_11_1.java +++ b/strings/Problem_11_1.java @@ -1,4 +1,5 @@ package strings; + import java.util.*; // Problem Title => Print all Subsequences of a string. @@ -7,27 +8,26 @@ public class Problem_11_1 { // Declare a global linkedList.list static List al = new ArrayList<>(); - - private static void findSubSequences(String s, String ans){ - if(s.length() == 0){ + private static void findSubSequences(String s, String ans) { + if (s.length() == 0) { al.add(ans); return; } // We add add-ing 1st character in string - findSubSequences(s.substring(1), ans+s.charAt(0)); + findSubSequences(s.substring(1), ans + s.charAt(0)); - // Not adding first character of the string because the concept of subsequence either character will present or not. - findSubSequences(s.substring(1),ans); + // Not adding first character of the string because the concept of subsequence + // either character will present or not. + findSubSequences(s.substring(1), ans); } - - // Creating a public static Arraylist such that we can store values // IF there is any question of returning then we can directly return too // public static ArrayList al = new ArrayList(); - public static void main(String[] args){ + public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); + sc.close(); findSubSequences(s, ""); System.out.println(al); } diff --git a/strings/Problem_11_2.java b/strings/Problem_11_2.java index d8b4692..086a6fb 100644 --- a/strings/Problem_11_2.java +++ b/strings/Problem_11_2.java @@ -29,6 +29,7 @@ static void subSequence(String str){ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); + sc.close(); subSequence(s); System.out.println(st); } diff --git a/strings/Problem_11_3.java b/strings/Problem_11_3.java index 541e07a..a50ee2b 100644 --- a/strings/Problem_11_3.java +++ b/strings/Problem_11_3.java @@ -37,6 +37,7 @@ static void printSubSeq(String str) { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); + sc.close(); printSubSeq(str); } } diff --git a/strings/Problem_12.java b/strings/Problem_12.java index ef6594f..ff76b86 100644 --- a/strings/Problem_12.java +++ b/strings/Problem_12.java @@ -1,4 +1,5 @@ package strings; + import java.util.*; // Problem Title => Split the Binary string into two substring with equal 0’s and 1’s @@ -6,22 +7,22 @@ public class Problem_12 { // Function to return the count of maximum substrings str can be divided into - static int maxSubStr(String str, int n){ + static int maxSubStr(String str, int n) { // To store the count of 0s and 1s int count0 = 0, count1 = 0; // To store the count of maximum substrings str can be divided into int cnt = 0; - for (int i = 0; i < n; i++){ - if(str.charAt(i) == 0) + for (int i = 0; i < n; i++) { + if (str.charAt(i) == 0) count0++; else count1++; - if(count0 == count1) + if (count0 == count1) cnt++; } // it is not possible to split the string - if(cnt == 0) + if (cnt == 0) return -1; return cnt; } @@ -31,8 +32,9 @@ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String str = sc.nextLine(); + sc.close(); - System.out.println(maxSubStr(str,n)); + System.out.println(maxSubStr(str, n)); } } diff --git a/strings/Problem_15.java b/strings/Problem_15.java index 44ccd76..d19c98b 100644 --- a/strings/Problem_15.java +++ b/strings/Problem_15.java @@ -1,4 +1,5 @@ package strings; + import java.util.*; // Problem Title => Find next greater number with same set of digits. [Very Most IMP] @@ -14,29 +15,32 @@ static void swap(char[] ar, int i, int j) { // Given a number as a char arrays.array number[], // this function finds the next greater number. // It modifies the same arrays.array to store the result - static void findNext(char[] ar, int n){ + static void findNext(char[] ar, int n) { int i; - // I) Start from the right most digit and find the first digit that is smaller than the digit next to it. - for (i = n - 1; i > 0; i--){ + // I) Start from the right most digit and find the first digit that is smaller + // than the digit next to it. + for (i = n - 1; i > 0; i--) { if (ar[i] > ar[i - 1]) break; } - // If no such digit is found, then all digits are in descending order means there cannot be a greater number with same set of digits + // If no such digit is found, then all digits are in descending order means + // there cannot be a greater number with same set of digits if (i == 0) System.out.println("Not possible"); - else{ + else { int x = ar[i - 1], min = i; - // II) Find the smallest digit on right side of (i-1)'th digit that is greater than number[i-1] - for (int j = i + 1; j < n; j++){ + // II) Find the smallest digit on right side of (i-1)'th digit that is greater + // than number[i-1] + for (int j = i + 1; j < n; j++) { if (ar[j] > x && ar[j] < ar[min]) min = j; } - // III) Swap the above found the smallest digit with number[i-1] + // III) Swap the above found the smallest digit with number[i-1] swap(ar, i - 1, min); // IV) Sort the digits after (i-1) in ascending order @@ -48,7 +52,7 @@ static void findNext(char[] ar, int n){ } public static void main(String[] args) { - char[] digits = { '5','3','4','9','7','6' }; + char[] digits = { '5', '3', '4', '9', '7', '6' }; int n = digits.length; findNext(digits, n); } diff --git a/strings/Problem_16.java b/strings/Problem_16.java new file mode 100644 index 0000000..f82938d --- /dev/null +++ b/strings/Problem_16.java @@ -0,0 +1,65 @@ +package strings; +// Blanaced + +import java.util.Stack; + +public class Problem_16 { + + public static boolean isBalanced(String expression) { + if (expression == null || expression.isEmpty()) { + return true; // Empty string is considered balanced + } + + Stack openingBrackets = new Stack<>(); + char[] chars = expression.toCharArray(); + + for (char c : chars) { + switch (c) { + case '{': + case '(': + case '[': + openingBrackets.push(c); // Push opening brackets to the stack + break; + case '}': + if (openingBrackets.isEmpty() || openingBrackets.pop() != '{') { + return false; // Mismatched closing bracket + } + break; + case ')': + if (openingBrackets.isEmpty() || openingBrackets.pop() != '(') { + return false; // Mismatched closing bracket + } + break; + case ']': + if (openingBrackets.isEmpty() || openingBrackets.pop() != '[') { + return false; // Mismatched closing bracket + } + break; + default: + // Ignore non-bracket characters + break; + } + } + + // After iterating through all characters, check if any opening brackets remain + // unclosed + return openingBrackets.isEmpty(); + } + + public static void main(String[] args) { + String expression1 = "{([])}"; + String expression2 = "[(])"; + + if (isBalanced(expression1)) { + System.out.println(expression1 + " is balanced."); + } else { + System.out.println(expression1 + " is not balanced."); + } + + if (isBalanced(expression2)) { + System.out.println(expression2 + " is balanced."); + } else { + System.out.println(expression2 + " is not balanced."); + } + } +} diff --git a/strings/Problem_17.java b/strings/Problem_17.java new file mode 100644 index 0000000..80261b9 --- /dev/null +++ b/strings/Problem_17.java @@ -0,0 +1,44 @@ +package strings; + +import java.util.Arrays; +import java.util.List; + +//* word break with dp +public class Problem_17 { + + public static boolean canBreak(String s, List wordDict) { + int n = s.length(); + // dp[i] represents if the first i characters of the string can be formed using + // words from the dictionary + boolean[] dp = new boolean[n + 1]; + + // Base case: an empty string can be formed using empty words + dp[0] = true; + + for (int i = 1; i <= n; i++) { + for (String word : wordDict) { + // Check if the current word is a prefix of the remaining string + if (word.length() <= i && s.substring(0, i).equals(word)) { + // Inherit the state from the remaining string (i - word.length()) + dp[i] = dp[i - word.length()]; + if (dp[i]) { // If a solution is found, break out of the inner loop + break; + } + } + } + } + + return dp[n]; + } + + public static void main(String[] args) { + String s = "leetcode"; + List wordDict = Arrays.asList("leet", "code"); + + if (canBreak(s, wordDict)) { + System.out.println(s + " can be segmented using words from the dictionary."); + } else { + System.out.println(s + " cannot be segmented using words from the dictionary."); + } + } +} diff --git a/strings/Problem_18.java b/strings/Problem_18.java new file mode 100644 index 0000000..38f759d --- /dev/null +++ b/strings/Problem_18.java @@ -0,0 +1,63 @@ +package strings; + +//* rabin karp algo +public class Problem_18 { + public static final int d = 256; // Number of characters in the input alphabet + + public static void search(String pattern, String text) { + int patternLength = pattern.length(); + int textLength = text.length(); + + // Precompute hash value for the pattern + int patternHash = calculateHash(pattern, patternLength); + + // Initialize a hash value for the first window of the text + int textHash = calculateHash(text, patternLength); + + // Slide the pattern over the text + for (int i = 0; i <= textLength - patternLength; i++) { + // Check if current window hash matches pattern hash + if (patternHash == textHash && checkCharacters(pattern, text, i)) { + System.out.println("Pattern found at index " + i); + } + + // Update hash value for the next window in the text + if (i < textLength - patternLength) { + textHash = recalculateHash(textHash, text.charAt(i), text.charAt(i + patternLength)); + } + } + } + + // Function to calculate the hash value of a string using a prime base + private static int calculateHash(String str, int length) { + int hash = 0; + for (int i = 0; i < length; i++) { + hash = (d * hash + str.charAt(i)) % Integer.MAX_VALUE; + } + return hash; + } + + // Function to recalculate the hash value for the next window in the text + private static char recalculateHash(int oldHash, char oldChar, char newChar) { + // Modify calculations here to ensure the result fits within char range + // (0-65535) + var intermediateValue = (d * (oldHash - oldChar * Math.pow(d, d - 1)) + newChar); + return (char) (intermediateValue % Character.MAX_VALUE); // Ensure result is within char range + } + + // Function to compare characters of pattern and text window + private static boolean checkCharacters(String pattern, String text, int startIndex) { + for (int i = 0; i < pattern.length(); i++) { + if (pattern.charAt(i) != text.charAt(startIndex + i)) { + return false; + } + } + return true; + } + + public static void main(String[] args) { + String text = "COURSEWAVE EXAMPLE"; + String pattern = "FOR"; + search(pattern, text); + } +} diff --git a/strings/Problem_19.java b/strings/Problem_19.java new file mode 100644 index 0000000..8f9f89a --- /dev/null +++ b/strings/Problem_19.java @@ -0,0 +1,70 @@ +package strings; + +//* KMP algo +public class Problem_19 { + + public static void search(String text, String pattern) { + int n = text.length(); + int m = pattern.length(); + + // Preprocess the pattern to compute the longest prefix-suffix (LPS) array + int[] lps = computeLPSArray(pattern); + + int i = 0; // index for text + int j = 0; // index for pattern + + while (i < n) { + if (text.charAt(i) == pattern.charAt(j)) { + i++; + j++; + } + + if (j == m) { + // Pattern found at index i - j + System.out.println("Pattern found at index " + (i - j)); + j = lps[j - 1]; // Shift the pattern using LPS + } else if (i < n && text.charAt(i) != pattern.charAt(j)) { + // Mismatch occurred, use LPS + if (j != 0) { + j = lps[j - 1]; + } else { + i++; + } + } + } + } + + private static int[] computeLPSArray(String pattern) { + int m = pattern.length(); + int[] lps = new int[m]; + int len = 0; // length of the previous longest prefix suffix + + lps[0] = 0; // lps[0] is always 0 + + int i = 1; + while (i < m) { + if (pattern.charAt(i) == pattern.charAt(len)) { + len++; + lps[i] = len; + i++; + } else { + // mismatch occurred, check previous prefix if any + if (len != 0) { + len = lps[len - 1]; + } else { + // No prefix found, set lps[i] to 0 + lps[i] = 0; + i++; + } + } + } + + return lps; + } + + public static void main(String[] args) { + String text = "ABABDABACDABABCABAB"; + String pattern = "ABABCABAB"; + search(text, pattern); + } +} diff --git a/strings/Problem_2.java b/strings/Problem_2.java index eb3fdce..7cb5841 100644 --- a/strings/Problem_2.java +++ b/strings/Problem_2.java @@ -2,27 +2,46 @@ import java.util.Scanner; -// Problem Title ==> Check String is Palindrome or not +//* Problem Title ==> Check String is Palindrome or not public class Problem_2 { - static boolean isPalindrome(String str){ - int i = 0, j = str.length() - 1; - while(i < j){ - if(str.charAt(i) != str.charAt(j)) + public static boolean isStringPalindrome(String inputString) { + int startIndex = 0; + int endIndex = inputString.length() - 1; + + // Iterate through the string while start and end haven't met + while (startIndex < endIndex) { + char startChar = inputString.charAt(startIndex); + char endChar = inputString.charAt(endIndex); + + // Convert characters to lowercase for case-insensitive comparison + startChar = Character.toLowerCase(startChar); + endChar = Character.toLowerCase(endChar); + + // If characters are not the same (ignoring case), return false + if (startChar != endChar) { return false; - i++; - j--; + } + + startIndex++; + endIndex--; } + + // If the loop completes, all characters matched (palindrome) return true; } public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - String str = sc.nextLine(); + Scanner scanner = new Scanner(System.in); + System.out.print("Enter a string: "); + String inputString = scanner.nextLine(); + + if (isStringPalindrome(inputString)) { + System.out.println("Yes, it is a palindrome."); + } else { + System.out.println("No, it is not a palindrome."); + } - if (isPalindrome(str)) - System.out.print("Yes"); - else - System.out.print("No"); + scanner.close(); } } \ No newline at end of file diff --git a/strings/Problem_20.java b/strings/Problem_20.java new file mode 100644 index 0000000..c6b2a6a --- /dev/null +++ b/strings/Problem_20.java @@ -0,0 +1,33 @@ +package strings; + +//* Convert a Sentence into its equivalent mobile numeric keypad sequence. +public class Problem_20 { + + public static String convert(String sentence) { + sentence = sentence.toUpperCase(); // Convert to uppercase for consistent mapping + StringBuilder numberSequence = new StringBuilder(); + + for (char c : sentence.toCharArray()) { + if (Character.isLetter(c)) { + int digit = (c - 'A') / 3 + 2; // Map letter to corresponding number on keypad + // Add extra press for letters on 7, 8, and 9 + if (digit == 8 || digit == 9) { + digit++; + } + numberSequence.append(digit); + } else if (c == ' ') { + numberSequence.append(0); // Add 0 for space + } + // Ignore other characters + } + + return numberSequence.toString(); + } + + public static void main(String[] args) { + String sentence = "Welcome to Coursewave!"; + String numberSequence = convert(sentence); + System.out.println(sentence + " converted to: " + numberSequence); + } +} + diff --git a/strings/Problem_21.java b/strings/Problem_21.java new file mode 100644 index 0000000..f5b03e5 --- /dev/null +++ b/strings/Problem_21.java @@ -0,0 +1,57 @@ + +package strings; + +import java.util.Stack; + +//* Minimum number of bracket reversals needed to make an expression balanced. +public class Problem_21 { + + public static int countMinReversals(String expr) { + if (expr.length() % 2 != 0) { // Odd length expressions cannot be balanced + return -1; + } + + int openCount = 0; + int closeCount = 0; + Stack stack = new Stack<>(); + + for (char c : expr.toCharArray()) { + if (c == '{') { + openCount++; + stack.push(c); + } else if (c == '}') { + closeCount++; + if (!stack.isEmpty() && stack.peek() == '{') { + stack.pop(); + } else { + // Unbalanced closing bracket, need reversal + openCount++; + } + } + } + + // Calculate remaining unbalanced brackets + int unbalanced = Math.abs(openCount - closeCount); + return (unbalanced + 1) / 2; // Need to reverse half of the remaining unbalanced brackets + } + + public static void main(String[] args) { + String expression1 = "{([)]}"; + String expression2 = "[(])"; + + int reversals1 = countMinReversals(expression1); + int reversals2 = countMinReversals(expression2); + + if (reversals1 != -1) { + System.out.println(expression1 + " requires " + reversals1 + " reversals to be balanced."); + } else { + System.out.println(expression1 + " cannot be balanced."); + } + + if (reversals2 != -1) { + System.out.println(expression2 + " requires " + reversals2 + " reversals to be balanced."); + } else { + System.out.println(expression2 + " cannot be balanced."); + } + } +} diff --git a/strings/Problem_22.java b/strings/Problem_22.java new file mode 100644 index 0000000..a12d496 --- /dev/null +++ b/strings/Problem_22.java @@ -0,0 +1,75 @@ +package strings; + +// Count All Palindromic Subsequence in a given String. +public class Problem_22 { + public static int countPalindromicSubsequences(String str) { + int n = str.length(); + int[][] dp = new int[n][n]; + + // Single-character strings are palindromes + for (int i = 0; i < n; i++) { + dp[i][i] = 1; + } + + // Consider substrings of length 2 + for (int i = 0; i < n - 1; i++) { + if (str.charAt(i) == str.charAt(i + 1)) { + dp[i][i + 1] = 2; // Two possibilities: single character or both characters + } else { + dp[i][i + 1] = 1; // Only single character is a palindrome + } + } + + // Fill the DP table for substrings of length 3 or more + for (int len = 3; len <= n; len++) { + for (int i = 0; i <= n - len; i++) { + int j = i + len - 1; + + if (str.charAt(i) == str.charAt(j)) { + dp[i][j] = dp[i + 1][j - 1] + 2; // Include the current pair and exclude the pair + // +2 accounts for single character palindromes at i and j (already counted in + // dp) + } else { + dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]; + // Exclude the current pair, consider palindromes without current characters + } + } + } + + // dp[0][n - 1] contains the total count of palindromic subsequences + return dp[0][n - 1]; + } + + public static int countPalindromicSubsequences(String str, int start, int end) { + if (start == end) { + return 1; // Single character is a palindrome subsequence + } + + if (start > end) { + return 0; // Empty string has no subsequences + } + + int count = 0; + + // Case 1: Include the current character + if (str.charAt(start) == str.charAt(end)) { + count = countPalindromicSubsequences(str, start + 1, end - 1) + 1; // Include the pair and exclude the pair + } else { + count = countPalindromicSubsequences(str, start + 1, end); // Exclude the current character + } + + // Case 2: Exclude the current character + count += countPalindromicSubsequences(str, start, end - 1); + + return count; + } + + public static int countPalindromicSubsequencesWithoutDP(String str) { + return countPalindromicSubsequences(str, 0, str.length() - 1); + } + public static void main(String[] args) { + String str = "aabcb"; + int count = countPalindromicSubsequences(str); + System.out.println("Total palindromic subsequences in " + str + ": " + count); + } +} diff --git a/strings/Problem_23.java b/strings/Problem_23.java new file mode 100644 index 0000000..0083ae4 --- /dev/null +++ b/strings/Problem_23.java @@ -0,0 +1,53 @@ +package strings; + +// ** Count of number of given string in 2D character array +public class Problem_23 { + public static int countOccurrences(char[][] grid, String str) { + int rows = grid.length; + int cols = grid[0].length; + int count = 0; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == str.charAt(0) && isValidMatch(grid, i, j, str, 0)) { + count++; + } + } + } + + return count; + } + + private static boolean isValidMatch(char[][] grid, int row, int col, String str, int index) { + if (index == str.length()) { + return true; // Entire string matched + } + + if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] != str.charAt(index)) { + return false; // Out of bounds or character mismatch + } + + // Check all eight directions recursively + return isValidMatch(grid, row - 1, col, str, index + 1) // Up + || isValidMatch(grid, row + 1, col, str, index + 1) // Down + || isValidMatch(grid, row, col - 1, str, index + 1) // Left + || isValidMatch(grid, row, col + 1, str, index + 1) // Right + || isValidMatch(grid, row - 1, col - 1, str, index + 1) // Up-Left diagonal + || isValidMatch(grid, row - 1, col + 1, str, index + 1) // Up-Right diagonal + || isValidMatch(grid, row + 1, col - 1, str, index + 1) // Down-Left diagonal + || isValidMatch(grid, row + 1, col + 1, str, index + 1); // Down-Right diagonal + } + + public static void main(String[] args) { + char[][] grid = { + { 'F', 'A', 'C', 'E' }, + { 'S', 'E', 'A', 'R' }, + { 'C', 'H', 'T', 'S' }, + { 'A', 'I', 'D', 'E' } + }; + String str = "SEARCH"; + + int count = countOccurrences(grid, str); + System.out.println("Total occurrences of '" + str + "' in the grid: " + count); + } +} diff --git a/strings/Problem_24.java b/strings/Problem_24.java new file mode 100644 index 0000000..f9af392 --- /dev/null +++ b/strings/Problem_24.java @@ -0,0 +1,60 @@ +package strings; + +//* Search a Word in a 2D Grid of characters. +public class Problem_24 { + + public static boolean exist(char[][] board, String word) { + int rows = board.length; + int cols = board[0].length; + + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (board[i][j] == word.charAt(0) && dfs(board, i, j, word, 0)) { + return true; // Word found starting from this cell + } + } + } + + return false; // Word not found in the grid + } + + private static boolean dfs(char[][] board, int row, int col, String word, int index) { + if (index == word.length()) { + return true; // Entire word found + } + + if (row < 0 || row >= board.length || col < 0 || col >= board[0].length + || board[row][col] != word.charAt(index)) { + return false; // Out of bounds or character mismatch + } + + // Mark the current cell as visited to avoid revisiting + char temp = board[row][col]; + board[row][col] = '#'; + + boolean found = dfs(board, row - 1, col, word, index + 1) // Up + || dfs(board, row + 1, col, word, index + 1) // Down + || dfs(board, row, col - 1, word, index + 1) // Left + || dfs(board, row, col + 1, word, index + 1); // Right + + // Backtrack: reset the cell value after exploration + board[row][col] = temp; + + return found; + } + + public static void main(String[] args) { + char[][] board = { + { 'A', 'B', 'C', 'E' }, + { 'S', 'F', 'C', 'S' }, + { 'A', 'D', 'E', 'E' } + }; + String word = "ABCCED"; + + if (exist(board, word)) { + System.out.println("Word '" + word + "' found in the grid."); + } else { + System.out.println("Word '" + word + "' not found in the grid."); + } + } +} diff --git a/strings/Problem_25.java b/strings/Problem_25.java new file mode 100644 index 0000000..0912f57 --- /dev/null +++ b/strings/Problem_25.java @@ -0,0 +1,59 @@ +package strings; + +//* Boyer Moore Algorithm for Pattern Searching. +public class Problem_25 { + public static int search(String text, String pattern) { + int n = text.length(); + int m = pattern.length(); + + // Preprocessing: create bad character table + int[] badCharTable = buildBadCharTable(pattern); + + int shift = m - 1; // Initial shift + + while (shift <= n - m) { + int j = m - 1; // Index for pattern + + while (j >= 0 && text.charAt(shift + j) == pattern.charAt(j)) { + j--; // Characters match, move to previous character + } + + if (j == -1) { // Pattern found + return shift; + } + + // Mismatch occurred, use bad character table + shift += Math.max(badCharTable[text.charAt(shift + j)] - j, 1); + } + + return -1; // Pattern not found + } + + private static int[] buildBadCharTable(String pattern) { + int[] badCharTable = new int[256]; // Assuming ASCII characters + + // Fill the table with the maximum distance between the current character + // and its rightmost occurrence in the pattern (except the last character) + for (int i = 0; i < pattern.length() - 1; i++) { + badCharTable[pattern.charAt(i)] = pattern.length() - 1 - i; + } + + // The last character of the pattern always gets a shift of 1 + badCharTable[pattern.charAt(pattern.length() - 1)] = 1; + + return badCharTable; + } + + public static void main(String[] args) { + String text = "THIS IS A TEXT BOOK EXAMPLE"; + String pattern = "EXAMPLE"; + + int index = search(text, pattern); + + if (index != -1) { + System.out.println("Pattern found at index: " + index); + } else { + System.out.println("Pattern not found in the text."); + } + } +} \ No newline at end of file diff --git a/strings/Problem_26.java b/strings/Problem_26.java new file mode 100644 index 0000000..18ef882 --- /dev/null +++ b/strings/Problem_26.java @@ -0,0 +1,43 @@ +package strings; + +import java.util.HashMap; + +// * Converting Roman Numerals to Decimal +public class Problem_26 { + + public static int convert(String romanNumeral) { + int decimal = 0; + int n = romanNumeral.length(); + + // Map for Roman symbols and their corresponding decimal values + HashMap map = new HashMap<>(); + map.put('I', 1); + map.put('V', 5); + map.put('X', 10); + map.put('L', 50); + map.put('C', 100); + map.put('D', 500); + map.put('M', 1000); + + for (int i = 0; i < n; i++) { + int current = map.get(romanNumeral.charAt(i)); + + // Check for subtractive notation (IV, IX, XL, XC, CM) + if (i + 1 < n && current < map.get(romanNumeral.charAt(i + 1))) { + decimal += map.get(romanNumeral.charAt(i + 1)) - current; + i++; // Skip the next character as it was used for subtraction + } else { + decimal += current; + } + } + + return decimal; + } + + public static void main(String[] args) { + String romanNumeral = "MCMIV"; + int decimal = convert(romanNumeral); + + System.out.println(romanNumeral + " in decimal is: " + decimal); + } +} diff --git a/strings/Problem_27.java b/strings/Problem_27.java new file mode 100644 index 0000000..e4ed88f --- /dev/null +++ b/strings/Problem_27.java @@ -0,0 +1,34 @@ +package strings; + +// *Find Longest Common Prefix +public class Problem_27 { + + public static String findLongestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) { + return ""; // Empty array or null input + } + + String prefix = strs[0]; // Initialize with the first string + + for (int i = 1; i < strs.length; i++) { + while (strs[i].indexOf(prefix) != 0) { + // Shorten the prefix if it's not a prefix of the current string + prefix = prefix.substring(0, prefix.length() - 1); + + // Handle cases where there is no common prefix + if (prefix.isEmpty()) { + return ""; + } + } + } + + return prefix; + } + + public static void main(String[] args) { + String[] strs = { "flower", "flow", "flight" }; + String lcp = findLongestCommonPrefix(strs); + + System.out.println("Longest Common Prefix for [" + String.join(", ", strs) + "] is: " + lcp); + } +} diff --git a/strings/Problem_28.java b/strings/Problem_28.java new file mode 100644 index 0000000..3a08c99 --- /dev/null +++ b/strings/Problem_28.java @@ -0,0 +1,31 @@ +package strings; + +// Number of flips to make binary string alternate +public class Problem_28 { + public static int minFlips(String A) { + int flipTo0 = 0, flipTo1 = 0; + + // Iterate through the string + for (int i = 0; i < A.length(); i++) { + char expected = (i % 2 == 0) ? '0' : '1'; // Expected character based on even/odd position + + // Count flips if the current character is different from expected + if (A.charAt(i) != expected) { + if (expected == '0') { + flipTo0++; + } else { + flipTo1++; + } + } + } + + // Return the minimum number of flips + return Math.min(flipTo0, flipTo1); + } + + public static void main(String[] args) { + String A = "001"; + int minFlips = minFlips(A); + System.out.println("Minimum number of flips for " + A + ": " + minFlips); + } +} diff --git a/strings/Problem_29.java b/strings/Problem_29.java new file mode 100644 index 0000000..7925e3b --- /dev/null +++ b/strings/Problem_29.java @@ -0,0 +1,33 @@ +package strings; + +// * Find the first repeated word in string. +public class Problem_29 { + + public static String findFirstRepeatedWord(String str) { + if (str == null || str.isEmpty()) { + return null; // Empty string has no repeated words + } + + int slow = 0, fast = 1; + while (fast < str.length() && slow < str.length()) { + if (str.charAt(slow) == str.charAt(fast)) { + return str.substring(slow, fast + 1); // Repeated word found + } + slow++; + fast += 2; + } + + return null; // No repeated words found + } + + public static void main(String[] args) { + String str = "This is a string with a repeated word this"; + String firstRepeatedWord = findFirstRepeatedWord(str); + + if (firstRepeatedWord != null) { + System.out.println("First repeated word: " + firstRepeatedWord); + } else { + System.out.println("No repeated words found in the string."); + } + } +} diff --git a/strings/Problem_3.java b/strings/Problem_3.java index f2b8c96..57c4315 100644 --- a/strings/Problem_3.java +++ b/strings/Problem_3.java @@ -2,34 +2,31 @@ import java.util.Scanner; -// Problem Title ==> Find Duplicate characters in a string +//* Problem Title ==> Find Duplicate characters in a string public class Problem_3 { static final int NO_OF_CHARS = 256; - /* Fills count arrays.array with - frequency of characters */ + // Fills count array with frequency of characters static void fillCharCounts(String str, int[] count) { for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; } - static void printDups(String str){ - // Create an arrays.array of size - // 256 and fill count of - // every character in it + static void printDups(String str) { + // Create an array of size 256 and fill count of every character in it int[] count = new int[NO_OF_CHARS]; fillCharCounts(str, count); for (int i = 0; i < NO_OF_CHARS; i++) if (count[i] > 1) - System.out.println((char)(i) + - ", count = " + count[i]); + System.out.println((char) (i) + ", count = " + count[i]); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); printDups(str); + sc.close(); } } \ No newline at end of file diff --git a/strings/Problem_30.java b/strings/Problem_30.java new file mode 100644 index 0000000..be6e4f8 --- /dev/null +++ b/strings/Problem_30.java @@ -0,0 +1,29 @@ +package strings; + +// Minimum number of swaps for bracket balancing. +public class Problem_30 { + public static int minSwaps(String str) { + int countOpen = 0; + int countClose = 0; + + for (char ch : str.toCharArray()) { + if (ch == '[') { + countOpen++; + } else if (ch == ']') { + if (countOpen > 0) { + countOpen--; // Balanced an opening bracket + } else { + countClose++; // Extra closing bracket + } + } + } + + return countOpen + countClose; // Minimum number of swaps + } + + public static void main(String[] args) { + String str = "]]][[[["; + int minSwaps = minSwaps(str); + System.out.println("Minimum swaps required for balancing: " + minSwaps); + } +} diff --git a/strings/Problem_31.java b/strings/Problem_31.java new file mode 100644 index 0000000..0cea152 --- /dev/null +++ b/strings/Problem_31.java @@ -0,0 +1,32 @@ +package strings; + +public class Problem_31 { + public static int lcs(String text1, String text2) { + int m = text1.length(); + int n = text2.length(); + + // Create a DP table to store LCS lengths + int[][] dp = new int[m + 1][n + 1]; + + // Fill the DP table + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; // Match, add 1 to LCS length + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // Choose the larger LCS from previous calculations + } + } + } + + return dp[m][n]; // LCS length is in the bottom right corner of the DP table + } + + public static void main(String[] args) { + String text1 = "AGGTAB"; + String text2 = "GXTXAYB"; + + int lcsLength = lcs(text1, text2); + System.out.println("Length of LCS for '" + text1 + "' and '" + text2 + "' is: " + lcsLength); + } +} diff --git a/strings/Problem_32.java b/strings/Problem_32.java new file mode 100644 index 0000000..96e4e8b --- /dev/null +++ b/strings/Problem_32.java @@ -0,0 +1,49 @@ +package strings; + +import java.util.ArrayList; +import java.util.List; + +public class Problem_32 { + + public static void generateIPAddresses(String str, List addresses, int start, int dots) { + if (dots == 4 && start == str.length()) { + addresses.add(str); // Valid IP address with 4 parts and reaching string end + return; + } + + if (dots > 4 || start >= str.length() || (dots == 4 && start < str.length())) { + return; // Invalid scenarios: too many dots, exceeding string length, or incomplete address with 4 dots + } + + for (int i = 1; i <= 3 && start + i <= str.length(); i++) { + String part = str.substring(start, start + i); + int num = Integer.parseInt(part); + + // Check for valid IP part (between 0 and 255, not starting with 0 except 0 itself) + if (num >= 0 && num <= 255 && (part.length() == 1 || part.charAt(0) != '0' || num == 0)) { + generateIPAddresses(str, addresses, start + i, dots + 1); // Recursively explore possibilities with the current part + if (dots == 3) { // Don't add dot after the third part + return; + } + addresses.add("."); // Add dot before next part (except after the third part) + } + } + } + + public static List findValidIPAddresses(String str) { + List addresses = new ArrayList<>(); + generateIPAddresses(str, addresses, 0, 0); + return addresses; + } + + public static void main(String[] args) { + String str = "25525511135"; + List validAddresses = findValidIPAddresses(str); + + System.out.println("Valid IP addresses for '" + str + "':"); + for (String address : validAddresses) { + System.out.println(address); + } + } + } + \ No newline at end of file diff --git a/strings/Problem_33.java b/strings/Problem_33.java new file mode 100644 index 0000000..ea14ca1 --- /dev/null +++ b/strings/Problem_33.java @@ -0,0 +1,63 @@ +package strings; + +import java.util.HashMap; + +public class Problem_33 { + + public static String findMinWindow(String s, String t) { + if (s == null || t == null || t.isEmpty()) { + return ""; + } + + // Count occurrences of each character in the target string + HashMap charCount = new HashMap<>(); + for (char c : t.toCharArray()) { + charCount.put(c, charCount.getOrDefault(c, 0) + 1); + } + + // Initialize variables for tracking the window + int windowStart = 0, minWindowLength = Integer.MAX_VALUE, count = 0; + + // Slide the window across the string + for (int windowEnd = 0; windowEnd < s.length(); windowEnd++) { + char endChar = s.charAt(windowEnd); + + // If the character is in the target string, increment the count + if (charCount.containsKey(endChar)) { + charCount.put(endChar, charCount.get(endChar) - 1); + if (charCount.get(endChar) >= 0) { + count++; // Found a character needed by the target string + } + } + + // Shrink the window if all characters from the target string are found + while (count == t.length()) { + int currentWindowLength = windowEnd - windowStart + 1; + if (currentWindowLength < minWindowLength) { + minWindowLength = currentWindowLength; + // Update the window to reflect the smallest valid window so far + } + + char startChar = s.charAt(windowStart); + if (charCount.containsKey(startChar)) { + if (charCount.get(startChar) == 0) { + count--; // Lost a character needed by the target string + } + charCount.put(startChar, charCount.get(startChar) + 1); + } + windowStart++; + } + } + + // Return the smallest window if found, otherwise an empty string + return minWindowLength != Integer.MAX_VALUE ? s.substring(windowStart, windowStart + minWindowLength) : ""; + } + + public static void main(String[] args) { + String s = "ADOBECODEBANC"; + String t = "ABC"; + String smallestWindow = findMinWindow(s, t); + System.out.println("Smallest window containing all characters of '" + t + "' in '" + s + "' is: " + smallestWindow); + } + } + \ No newline at end of file diff --git a/strings/Problem_34.java b/strings/Problem_34.java new file mode 100644 index 0000000..a375d9d --- /dev/null +++ b/strings/Problem_34.java @@ -0,0 +1,65 @@ +package strings; + +import java.util.HashMap; +import java.util.PriorityQueue; + +public class Problem_34 { + public static String rearrangeString(String str) { + if (str == null || str.isEmpty()) { + return str; // Empty string has no characters to rearrange + } + + // Count character frequencies + HashMap charCount = new HashMap<>(); + for (char c : str.toCharArray()) { + charCount.put(c, charCount.getOrDefault(c, 0) + 1); + } + + // Create a priority queue to store characters based on their frequencies + // (highest frequency first) + PriorityQueue pq = new PriorityQueue<>((a, b) -> charCount.get(b) - charCount.get(a)); + pq.addAll(charCount.keySet()); + + // Characters to be used in the rearranged string + StringBuilder result = new StringBuilder(); + + // Previous character used (initialize with a special character not present in + // the string) + char prev = '#'; + + while (!pq.isEmpty()) { + char curr = pq.poll(); + + // Check if the previous character is the same, skip if so (to avoid adjacent + // duplicates) + if (curr == prev) { + if (pq.isEmpty()) { + return ""; // Not possible to rearrange without adjacent duplicates + } + char temp = pq.poll(); // Get the next character and put the current one back for later processing + pq.offer(curr); + curr = temp; + } + + // Add the current character to the result and update the previous character + result.append(curr); + charCount.put(curr, charCount.get(curr) - 1); // Decrement frequency + + // If the frequency of the current character is not zero (can be used again + // later), add it back to the queue + if (charCount.get(curr) > 0) { + pq.offer(curr); + } + + prev = curr; + } + + return result.toString(); + } + + public static void main(String[] args) { + String str = "aab"; + String rearrangedString = rearrangeString(str); + System.out.println("Rearranged string without adjacent duplicates: " + rearrangedString); + } +} diff --git a/strings/Problem_35.java b/strings/Problem_35.java new file mode 100644 index 0000000..e8e3aab --- /dev/null +++ b/strings/Problem_35.java @@ -0,0 +1,33 @@ +package strings; + +public class Problem_35 { + + public static int minChars(String str) { + int n = str.length(); + + // Create a table to store longest palindrome ending at each index (LCP) + int[][] lcp = new int[n][n]; + + // Calculate length of longest common prefix (LCP) for all substrings + for (int i = n - 1; i >= 0; i--) { + for (int j = i; j < n; j++) { + if (str.charAt(i) == str.charAt(j)) { + lcp[i][j] = (i + 1 == j) ? 1 : 1 + lcp[i + 1][j - 1]; + } else { + lcp[i][j] = 0; + } + } + } + + // Minimum characters to add is the length of the string minus the length of the + // longest suffix palindrome + int longestSuffixPalindrome = lcp[0][n - 1]; + return n - longestSuffixPalindrome; + } + + public static void main(String[] args) { + String str = "aacecaaa"; + int minChars = minChars(str); + System.out.println("Minimum characters to add at front to make '" + str + "' a palindrome: " + minChars); + } +} diff --git a/strings/Problem_36.java b/strings/Problem_36.java new file mode 100644 index 0000000..c884aab --- /dev/null +++ b/strings/Problem_36.java @@ -0,0 +1,38 @@ +package strings; +// Given a sequence of words, print all anagrams together + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class Problem_36 { + + public static List> groupAnagrams(String[] strs) { + HashMap> anagramMap = new HashMap<>(); + + for (String word : strs) { + // Sort the characters of the word (anagrams have the same sorted characters) + char[] charArray = word.toCharArray(); + Arrays.sort(charArray); + String sortedWord = new String(charArray); + + // Add the word to the list of anagrams for its sorted form (key) in the HashMap + anagramMap.putIfAbsent(sortedWord, new ArrayList<>()); + anagramMap.get(sortedWord).add(word); + } + + // Convert the HashMap values (lists of anagrams) to a List of Lists for the output + return new ArrayList<>(anagramMap.values()); + } + + public static void main(String[] args) { + String[] words = {"act", "god", "cat", "dog", "tac"}; + List> anagramGroups = groupAnagrams(words); + + System.out.println("Anagram groups:"); + for (List group : anagramGroups) { + System.out.println(group); + } + } +} diff --git a/strings/Problem_37.java b/strings/Problem_37.java new file mode 100644 index 0000000..9d0de2e --- /dev/null +++ b/strings/Problem_37.java @@ -0,0 +1,63 @@ +package strings; + +import java.util.HashMap; + +// Find the smallest window in a string containing all characters of another string +public class Problem_37 { + public static String findMinWindow(String s, String t) { + if (s == null || t == null || t.isEmpty()) { + return ""; + } + + // Count occurrences of each character in the target string + HashMap charCount = new HashMap<>(); + for (char c : t.toCharArray()) { + charCount.put(c, charCount.getOrDefault(c, 0) + 1); + } + + // Initialize variables for tracking the window + int windowStart = 0, minWindowLength = Integer.MAX_VALUE, count = 0; + + // Slide the window across the string + for (int windowEnd = 0; windowEnd < s.length(); windowEnd++) { + char endChar = s.charAt(windowEnd); + + // If the character is in the target string, increment the count + if (charCount.containsKey(endChar)) { + charCount.put(endChar, charCount.get(endChar) - 1); + if (charCount.get(endChar) >= 0) { + count++; // Found a character needed by the target string + } + } + + // Shrink the window if all characters from the target string are found + while (count == t.length()) { + int currentWindowLength = windowEnd - windowStart + 1; + if (currentWindowLength < minWindowLength) { + minWindowLength = currentWindowLength; + // Update the window to reflect the smallest valid window so far + } + + char startChar = s.charAt(windowStart); + if (charCount.containsKey(startChar)) { + if (charCount.get(startChar) == 0) { + count--; // Lost a character needed by the target string + } + charCount.put(startChar, charCount.get(startChar) + 1); + } + windowStart++; + } + } + + // Return the smallest window if found, otherwise an empty string + return minWindowLength != Integer.MAX_VALUE ? s.substring(windowStart, windowStart + minWindowLength) : ""; + } + + public static void main(String[] args) { + String s = "ADOBECODEBANC"; + String t = "ABC"; + String smallestWindow = findMinWindow(s, t); + System.out.println( + "Smallest window containing all characters of '" + t + "' in '" + s + "' is: " + smallestWindow); + } +} diff --git a/strings/Problem_38.java b/strings/Problem_38.java new file mode 100644 index 0000000..9e625e4 --- /dev/null +++ b/strings/Problem_38.java @@ -0,0 +1,27 @@ +package strings; + +// Recursively remove all adjacent duplicates +public class Problem_38 { + public static String removeDuplicates(String str) { + if (str == null || str.length() <= 1) { + return str; // Empty or single-character string has no duplicates to remove + } + + // Check if the first two characters are duplicates + if (str.charAt(0) == str.charAt(1)) { + // Remove the first character and recursively call the function on the remaining + // string + return removeDuplicates(str.substring(1)); + } else { + // If first two characters are different, prepend the first character to the + // result of the recursive call on the remaining string + return str.charAt(0) + removeDuplicates(str.substring(1)); + } + } + + public static void main(String[] args) { + String str = "AABBCCCD"; + String result = removeDuplicates(str); + System.out.println("String after removing adjacent duplicates: " + result); + } +} diff --git a/strings/Problem_39.java b/strings/Problem_39.java new file mode 100644 index 0000000..98bc5f2 --- /dev/null +++ b/strings/Problem_39.java @@ -0,0 +1,52 @@ +package strings; + +// String matching where one string contains wildcard characters +public class Problem_39 { + + public static boolean isMatch(String text, String pattern) { + int textIndex = 0; + int patternIndex = 0; + + // Track the last matched position of '*' in the pattern + int starIndex = -1; + int i = 0; + + while (textIndex < text.length()) { + char textChar = text.charAt(textIndex); + char patternChar = pattern.charAt(patternIndex); + + // If the characters match or the pattern character is '?' (match any character) + if (textChar == patternChar || patternChar == '?') { + textIndex++; + patternIndex++; + } else if (patternChar == '*') { + // '*' can match any sequence of characters (including empty sequence) + starIndex = patternIndex; + i = textIndex; // Mark the position to backtrack from if needed + patternIndex++; // Move on in the pattern + } else if (starIndex != -1) { + // Mismatch after '*', try backtracking + patternIndex = starIndex + 1; // Move to the character after '*' + i++; // Try matching the next character in the text + textIndex = i; // Backtrack to the position after the last match with '*' + } else { + // No match, return false + return false; + } + } + + // Handle remaining characters in the pattern after reaching the end of the text + while (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') { + patternIndex++; + } + + return patternIndex == pattern.length(); // Return true if all characters in the pattern are matched + } + + public static void main(String[] args) { + String text = "baaabab"; + String pattern = "ba*a*b*ab"; + boolean isMatch = isMatch(text, pattern); + System.out.println("Text '" + text + "' matches pattern '" + pattern + "'? " + isMatch); + } +} diff --git a/strings/Problem_40.java b/strings/Problem_40.java new file mode 100644 index 0000000..632f39e --- /dev/null +++ b/strings/Problem_40.java @@ -0,0 +1,45 @@ +package strings; + +// Function to find Number of customers who could not get a computer +public class Problem_40 { + public static int numCustomersNotGettingComputer(int totalCustomers, int numComputers, char[] customerPrefs) { + if (totalCustomers <= 0 || numComputers < 0 || customerPrefs == null + || customerPrefs.length != totalCustomers) { + return -1; // Invalid input + } + + // Count the number of customers needing laptops and desktops + int laptopsNeeded = 0; + int desktopsNeeded = 0; + for (char pref : customerPrefs) { + if (pref == 'L') { + laptopsNeeded++; + } else if (pref == 'D') { + desktopsNeeded++; + } else { + // Invalid preference character, ignore + } + } + + // Check if there are enough computers to satisfy all preferences + if (laptopsNeeded <= numComputers && desktopsNeeded <= numComputers) { + return 0; // All customers get a computer + } + + // Determine the type of computer in short supply + int computersShort = Math.min(laptopsNeeded, desktopsNeeded); + int customersShort = Math.max(laptopsNeeded, desktopsNeeded); + + // Calculate the number of customers who cannot get their preferred computer + return customersShort - computersShort; + } + + public static void main(String[] args) { + int totalCustomers = 8; + int numComputers = 5; + char[] customerPrefs = { 'L', 'L', 'D', 'D', 'L', 'D', 'L', 'D' }; + + int numNotGettingComputer = numCustomersNotGettingComputer(totalCustomers, numComputers, customerPrefs); + System.out.println(numNotGettingComputer + " customers could not get their preferred computer."); + } +} diff --git a/strings/Problem_41.java b/strings/Problem_41.java new file mode 100644 index 0000000..8e668d2 --- /dev/null +++ b/strings/Problem_41.java @@ -0,0 +1,28 @@ +package strings; + +// Transform One String to Another using Minimum Number of Given Operation +public class Problem_41 { + public static int minOperations(String A, String B, char replaceChar) { + if (A == null || B == null || A.length() != B.length()) { + return -1; // Invalid input (strings must be of the same length) + } + + int operations = 0; + for (int i = 0; i < A.length(); i++) { + if (A.charAt(i) != B.charAt(i)) { + operations++; // Increment for each character that needs replacement + } + } + + return operations; + } + + public static void main(String[] args) { + String A = "APPLE"; + String B = "APPLES"; + char replaceChar = 'S'; + int minOps = minOperations(A, B, replaceChar); + System.out.println("Minimum operations to transform '" + A + "' to '" + B + "' (replace with '" + replaceChar + + "'): " + minOps); + } +} diff --git a/strings/Problem_42.java b/strings/Problem_42.java new file mode 100644 index 0000000..310d578 --- /dev/null +++ b/strings/Problem_42.java @@ -0,0 +1,41 @@ +package strings; + +import java.util.HashMap; + +// Check if two given strings are isomorphic to each other +public class Problem_42 { + public static boolean isIsomorphic(String str1, String str2) { + if (str1 == null || str2 == null || str1.length() != str2.length()) { + return false; // Invalid input (strings must be of the same length) + } + + // Create two HashMaps to store mappings between characters in str1 and str2 + HashMap map1 = new HashMap<>(); + HashMap map2 = new HashMap<>(); + + for (int i = 0; i < str1.length(); i++) { + char char1 = str1.charAt(i); + char char2 = str2.charAt(i); + + // Check if the characters in str1 and str2 at the same index have already been mapped differently + if (map1.containsKey(char1) && map1.get(char1) != char2) { + return false; + } else if (map2.containsKey(char2) && map2.get(char2) != char1) { + return false; + } + + // Add mappings to the HashMaps if not already present + map1.put(char1, char2); + map2.put(char2, char1); + } + + return true; + } + + public static void main(String[] args) { + String str1 = "egg"; + String str2 = "add"; + boolean isIsomorphic = isIsomorphic(str1, str2); + System.out.println("Strings '" + str1 + "' and '" + str2 + "' are isomorphic: " + isIsomorphic); + } +} diff --git a/strings/Problem_43.java b/strings/Problem_43.java new file mode 100644 index 0000000..f2289cf --- /dev/null +++ b/strings/Problem_43.java @@ -0,0 +1,43 @@ +package strings; + +import java.util.ArrayList; +import java.util.List; + +// Recursively print all sentences that can be formed from list of word lists +public class Problem_43 { + public static void printSentences(List> wordLists) { + printSentencesHelper(wordLists, new ArrayList<>(), 0); + } + + private static void printSentencesHelper(List> wordLists, List currentSentence, int level) { + // Base case: reached the end of the word lists + if (level == wordLists.size()) { + // Print the complete sentence + System.out.println(String.join(" ", currentSentence)); + return; + } + + // Get the list of words for the current level + List words = wordLists.get(level); + + // Loop through each word in the current list + for (String word : words) { + // Add the word to the current sentence + currentSentence.add(word); + // Recursively explore sentences starting from the next level + printSentencesHelper(wordLists, currentSentence, level + 1); + // Backtrack: remove the added word after recursion + currentSentence.remove(currentSentence.size() - 1); + } + } + + public static void main(String[] args) { + List> wordLists = new ArrayList<>(); + wordLists.add(List.of("love", "like")); + wordLists.add(List.of("dogs", "cats")); + wordLists.add(List.of("are", "a")); + + System.out.println("All possible sentences:"); + printSentences(wordLists); + } +} diff --git a/strings/Problem_5.java b/strings/Problem_5.java index 737fbeb..648e09b 100644 --- a/strings/Problem_5.java +++ b/strings/Problem_5.java @@ -1,21 +1,26 @@ package strings; + import java.util.Scanner; // Problem Title => Write a Code to check whether one string is a rotation of another public class Problem_5 { - //function to check whether the strings are rotations or not - static boolean areRotations(String str1, String str2){ + // function to check whether the strings are rotations or not + static boolean areRotations(String str1, String str2) { return (str1.length() == str2.length() && ((str1 + str2).contains(str2))); } - //driver function + + // driver function public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str1 = sc.nextLine(); String str2 = sc.nextLine(); + if (areRotations(str1, str2)) System.out.println("Strings are rotations of each other"); else System.out.print("Strings are not rotations of each other"); + + sc.close(); } } \ No newline at end of file diff --git a/strings/Problem_6.java b/strings/Problem_6.java index 2ebbce4..407ea6a 100644 --- a/strings/Problem_6.java +++ b/strings/Problem_6.java @@ -2,59 +2,45 @@ import java.util.Scanner; +// * Check whether a string is valid shuffle of two strings or not public class Problem_6 { - static boolean compare(int []arr1, int []arr2) { - for(int i = 0; i < 256; i++) - if (arr1[i] != arr2[i]) + // function to compareCharacterCounts + static boolean compareCharacterCounts(int[] charCount1, int[] charCount2) { + for (int i = 0; i < 256; i++) + if (charCount1[i] != charCount2[i]) return false; return true; } - // This function search for all - // permutations of pat[] in txt[] - static boolean search(String pat, String txt) { - int M = pat.length(); - int N = txt.length(); + // This function searchForPattern for all permutations of pat[] in txt[] + static boolean searchForPattern(String pattern, String text) { + int patternLength = pattern.length(); + int textLength = text.length(); - // countP[]: Store count of all - // characters of pattern - // countTW[]: Store count of - // current window of text - int []countP = new int [256]; - int []countTW = new int [256]; - for(int i = 0; i < 256; i++) - { - countP[i] = 0; - countTW[i] = 0; - } + int[] patternCharCount = new int[256]; + int[] currentWindowCharCount = new int[256]; - for(int i = 0; i < M; i++) { - (countP[pat.charAt(i)])++; - (countTW[txt.charAt(i)])++; + for (int i = 0; i < 256; i++) { + patternCharCount[i] = 0; + currentWindowCharCount[i] = 0; } - // Traverse through remaining - // characters of pattern - for(int i = M; i < N; i++) { + for (int i = 0; i < patternLength; i++) { + (patternCharCount[pattern.charAt(i)])++; + (currentWindowCharCount[text.charAt(i)])++; + } - // Compare counts of current - // window of text with - // counts of pattern[] - if (compare(countP, countTW)) + for (int i = patternLength; i < textLength; i++) { + if (compareCharacterCounts(patternCharCount, currentWindowCharCount)) return true; - // Add current character to - // current window - (countTW[txt.charAt(i)])++; - - // Remove the first character - // of previous window - countTW[txt.charAt(i - M)]--; + (currentWindowCharCount[text.charAt(i)])++; // Add current character to current window + currentWindowCharCount[text.charAt(i - patternLength)]--; // Remove the first character of previous window } // Check for the last window in text - return compare(countP, countTW); + return compareCharacterCounts(patternCharCount, currentWindowCharCount); } // Driver code @@ -63,9 +49,11 @@ public static void main(String[] args) { String txt = sc.nextLine(); String pat = sc.nextLine(); - if (search(pat, txt)) + if (searchForPattern(pat, txt)) System.out.println("Yes"); else System.out.println("NO"); + + sc.close(); } } \ No newline at end of file diff --git a/strings/Problem_7.java b/strings/Problem_7.java index 2303ce4..e2e556a 100644 --- a/strings/Problem_7.java +++ b/strings/Problem_7.java @@ -1,52 +1,56 @@ package strings; -// Problem Title => Count and Say problem + +// * Problem Title: Count and Say public class Problem_7 { - static String countAndSay(int n){ - if(n == 1) return "1"; - if(n == 2) return "11"; - - // Find n'th term by generating - // all terms from 3 to n-1. - // Every term is generated using previous term Initialize previous term - String str = "11"; - for (int i = 3; i <= n; i++) { - // In below for loop, previous character is processed in current iteration. - // That is why a dummy character is added to make sure that loop runs one extra iteration. - str += '$'; - int len = str.length(); - - int cnt = 1; - // Initialize count of matching chars - String tmp = ""; // Initialize i'th - - // term in series - char []arr = str.toCharArray(); - - // Process previous term to find the next term - for (int j = 1; j < len; j++) { - // If current character does not match - if (arr[j] != arr[j - 1]) { - // Append count of str[j-1] to temp - tmp += cnt; - - // Append str[j-1] - tmp += arr[j - 1]; - - // Reset count - cnt = 1; - } + public static String countAndSay(int n) { + if (n == 1) { + return "1"; // Base case: first term is "1" + } else if (n == 2) { + return "11"; // Base case: second term is "11" + } - // If matches, then increment count of matching characters - else cnt++; + // Initialize result string with the base case + String result = "11"; + + // Generate terms from 3 to n based on previous terms + for (int termNumber = 3; termNumber <= n; termNumber++) { + StringBuilder nextTerm = new StringBuilder(); + + // Process previous term character by character + char previousChar = result.charAt(0); // Initialize with first character + int currentCharCount = 1; // Count of consecutive occurrences of previous character + + for (int charIndex = 1; charIndex < result.length(); charIndex++) { + char currentChar = result.charAt(charIndex); + + // If character changes, append count and character to next term + if (currentChar != previousChar) { + nextTerm.append(currentCharCount); + nextTerm.append(previousChar); + previousChar = currentChar; + currentCharCount = 1; + } else { + // If character is same, increment count + currentCharCount++; + } } - // Update str - str = tmp; + // Append the last character and its count (if applicable) + nextTerm.append(currentCharCount); + nextTerm.append(previousChar); + + // Update result string with the generated next term + result = nextTerm.toString(); } - return str; + + return result; } - public static void main(String[] args) { + public static void main(String[] args) { + // Example usage: + int n = 4; + String sequenceTerm = countAndSay(n); + System.out.println("Term " + n + ": " + sequenceTerm); } -} \ No newline at end of file +} diff --git a/strings/Problem_8_BF.java b/strings/Problem_8_BF.java index d4979ae..ef00564 100644 --- a/strings/Problem_8_BF.java +++ b/strings/Problem_8_BF.java @@ -1,59 +1,64 @@ package strings; + import java.util.*; -// Problem Title => Write a program to find the longest Palindrome in a string. [ The Longest palindromic Substring ] +//* Problem Title => Write a program to find the longest Palindrome in a string. [ The Longest palindromic Substring ] public class Problem_8_BF { - - // function to print a substring - static void printSubString(String str, int low, int high){ - for(int i = low; i <= high; ++i) - System.out.print(str.charAt(i)); + // Function to print a substring + static void printSubString(String inputString, int low, int high) { + for (int i = low; i <= high; ++i) { + System.out.print(inputString.charAt(i)); + } } - // This function prints the longest palindrome substring. + // This function prints the longest palindrome substring in a string. // It also returns the length of the longest palindrome - static int longestPalSubString(String str){ + static int findLongestPalindromicSubString(String inputString) { - // get length of input string - int n = str.length(); + // Get length of the input string + int stringLength = inputString.length(); - // All subStrings of length 1 are palindrome - int maxLength = 1, start = 0; + // All substrings of length 1 are palindromes + int maxLength = 1; + int startIndex = 0; - // Nested loop to mark start and end index - for (int i = 0; i < n; i++){ - for (int j = i; j < n; j++){ - int flag = 1; + // Nested loop to find starting and ending indexes of the longest palindrome + for (int i = 0; i < stringLength; i++) { + for (int j = i; j < stringLength; j++) { + boolean isPalindrome = true; - //check palindrome - for(int k = 0; k <(j - i + 1)/2; k++) - if (str.charAt(i + k) != str.charAt(j - k)) { - flag = 0; + // Check if the substring is a palindrome + for (int k = 0; k < (j - i + 1) / 2; k++) { + if (inputString.charAt(i + k) != inputString.charAt(j - k)) { + isPalindrome = false; break; } + } - // palindrome - if(flag != 0 && (j - i + 1) > maxLength){ - start = i; + // If a palindrome is found and its length is greater than the current maximum + if (isPalindrome && (j - i + 1) > maxLength) { + startIndex = i; maxLength = j - i + 1; } } } - System.out.println("Longest palindrome subString is : "); - printSubString(str, start, start + maxLength - 1); + System.out.println("Longest palindrome substring is: "); + printSubString(inputString, startIndex, startIndex + maxLength - 1); - // return length of LPS + // Return length of the longest palindrome substring return maxLength; } // Driver Code public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - System.out.println("Enter the input string : "); + Scanner scanner = new Scanner(System.in); + System.out.println("Enter the input string: "); - String str = sc.nextLine(); - System.out.println("Length is : " + longestPalSubString(str)); + String inputString = scanner.nextLine(); + System.out.println( + "Length of the longest palindrome substring is: " + findLongestPalindromicSubString(inputString)); + scanner.close(); } } \ No newline at end of file diff --git a/strings/Problem_9.java b/strings/Problem_9.java index 58cc70e..b2ed71d 100644 --- a/strings/Problem_9.java +++ b/strings/Problem_9.java @@ -1,21 +1,23 @@ package strings; + import java.util.*; // Problem Title => Find The Longest Recurring Subsequence in String public class Problem_9 { - // This function mainly returns LCS(str, str) with a condition that same characters at same index are not considered. - static int[][] dp = new int[1000][1000]; + // This function mainly returns LCS(str, str) with a condition that same + // characters at same index are not considered. + static int[][] dp = new int[1000][1000]; // Longest Repeated Subsequence Problem - static int findLongestRepeatingSubSeq(char[] X, int m, int n){ + static int findLongestRepeatingSubSeq(char[] X, int m, int n) { - if(dp[m][n] != -1) + if (dp[m][n] != -1) return dp[m][n]; // return if we have reached the end of either string - if(m == 0 || n == 0) + if (m == 0 || n == 0) return dp[m][n] = 0; // if characters at index m and n matches and index is different @@ -34,6 +36,9 @@ public static void main(String[] args) { for (int[] row : dp) Arrays.fill(row, -1); - System.out.println("The length of the largest subsequence that repeats itself is : " + findLongestRepeatingSubSeq(str.toCharArray(), m, m)); + System.out.println("The length of the largest subsequence that repeats itself is : " + + findLongestRepeatingSubSeq(str.toCharArray(), m, m)); + + sc.close(); } } \ No newline at end of file diff --git a/strings/Remove_Duplicates.java b/strings/Remove_Duplicates.java index f86d12e..c7af5c7 100644 --- a/strings/Remove_Duplicates.java +++ b/strings/Remove_Duplicates.java @@ -22,6 +22,7 @@ public static void removeDuplicates(String s){ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); + sc.close(); removeDuplicates(str); } } \ No newline at end of file diff --git a/trees/binarySearchTree/Problem_1.java b/trees/binarySearchTree/Problem_1.java index 7ef9e75..0eaa407 100644 --- a/trees/binarySearchTree/Problem_1.java +++ b/trees/binarySearchTree/Problem_1.java @@ -1,4 +1,4 @@ - +package trees.binarySearchTree; public class Problem_1 { diff --git a/trees/binarySearchTree/Problem_2.java b/trees/binarySearchTree/Problem_2.java index a5eb5f4..80a3621 100644 --- a/trees/binarySearchTree/Problem_2.java +++ b/trees/binarySearchTree/Problem_2.java @@ -1,4 +1,4 @@ - +package trees.binarySearchTree; // Problem Title => Deletion_of_a_node_in_bst public class Problem_2 { diff --git a/trees/binarySearchTree/Problem_3.java b/trees/binarySearchTree/Problem_3.java index 42d142c..3df2dec 100644 --- a/trees/binarySearchTree/Problem_3.java +++ b/trees/binarySearchTree/Problem_3.java @@ -1,3 +1,5 @@ +package trees.binarySearchTree; + // Problem Tiitle => Find min and max value in a BST public class Problem_3 { @@ -27,7 +29,7 @@ Node insert(Node node, int data) { return node; } } - + // Returns the min value in a binary tree int minValue(Node node) { Node current = node; diff --git a/trees/binarySearchTree/Problem_4.java b/trees/binarySearchTree/Problem_4.java index 6e7bd17..7e16091 100644 --- a/trees/binarySearchTree/Problem_4.java +++ b/trees/binarySearchTree/Problem_4.java @@ -1,3 +1,4 @@ +package trees.binarySearchTree; // Problem Tiitle => Find inorder successor and inorder predecessor in a BST public class Problem_4 { @@ -14,10 +15,10 @@ public Node(int key) { this.left = this.right = null; } } - + static Node pre = new Node(), suc = new Node(); - // This function finds predecessor and successor of key in BST. + // This function finds predecessor and successor of key in BST. // It sets pre and suc as predecessor and successor respectively static void findPreSuc(Node root, int key) { @@ -65,6 +66,6 @@ static void findPreSuc(Node root, int key) { // A utility function to insert a public static void main(String[] args) { - + } } diff --git a/trees/binarySearchTree/Problem_5.java b/trees/binarySearchTree/Problem_5.java index 86405fb..796d8ad 100644 --- a/trees/binarySearchTree/Problem_5.java +++ b/trees/binarySearchTree/Problem_5.java @@ -1,4 +1,6 @@ -// Problem Title => Check if a tree is a BST or not +package trees.binarySearchTree; + +// Problem Title => Check if a tree is a BST or not public class Problem_5 { diff --git a/trees/binaryTree/Tree.java b/trees/binaryTree/Tree.java index 0e79c30..66e142f 100644 --- a/trees/binaryTree/Tree.java +++ b/trees/binaryTree/Tree.java @@ -1,4 +1,4 @@ -package basic_idea_of_DS; +package trees.binaryTree; //class containing left & right child of current node & key value class Node{ @@ -12,15 +12,15 @@ public Node(int item) { // A java program to introduce Binary Tree public class Tree { - + //Root node of binary tree Node root; - + //Constructors Tree(int key){ root = new Node(key); } - + Tree(){ root = null; } @@ -28,12 +28,12 @@ public static void main(String[] args) { Tree t = new Tree(); //create root t.root = new Node(1); - + /* following is the tree after above statement 1 / \ null null*/ - + t.root.left = new Node(2); t.root.right = new Node(3); /* 2 & 3 become left & right children of 1 @@ -47,6 +47,6 @@ public static void main(String[] args) { t.root.right.right = new Node(5); t.root.right.left = new Node(6); t.root.left.right = new Node(7); - + } }