diff --git a/Arrays/Hard/FourNumberSum/FourNumberSum.cpp b/Arrays/Hard/FourNumberSum/FourNumberSum.cpp new file mode 100644 index 00000000..1eb5cd1a --- /dev/null +++ b/Arrays/Hard/FourNumberSum/FourNumberSum.cpp @@ -0,0 +1,88 @@ +#include +#include +#include + +std::vector> fourSum(std::vector& num, int target) { + std::vector> res; + + if (num.empty()) { + std::cout << "Input vector is empty. Returning empty result." << std::endl; + return res; + } + + int n = num.size(); + std::sort(num.begin(), num.end()); + + for (int i = 0; i < n; i++) { + // Reduce the problem to finding a 3-sum + int target_3 = target - num[i]; + + for (int j = i + 1; j < n; j++) { + // Reduce the problem to finding a 2-sum + int target_2 = target_3 - num[j]; + + int front = j + 1; + int back = n - 1; + + while (front < back) { + int two_sum = num[front] + num[back]; + + if (two_sum < target_2) front++; + else if (two_sum > target_2) back--; + else { + // Found a valid quadruplet, add to the result + std::vector quadruplet(4, 0); + quadruplet[0] = num[i]; + quadruplet[1] = num[j]; + quadruplet[2] = num[front]; + quadruplet[3] = num[back]; + res.push_back(quadruplet); + + // Processing the duplicates of number 3 + while (front < back && num[front] == quadruplet[2]) ++front; + + // Processing the duplicates of number 4 + while (front < back && num[back] == quadruplet[3]) --back; + } + } + + // Processing the duplicates of number 2 + while (j + 1 < n && num[j + 1] == num[j]) ++j; + } + + // Processing the duplicates of number 1 + while (i + 1 < n && num[i + 1] == num[i]) ++i; + } + + return res; +} + +int main() { + // Read the array elements from STDIN + std::vector v; + int num; + while (std::cin >> num) { + v.push_back(num); + } + + // Check if the input vector is empty + if (v.empty()) { + std::cout << "Input vector is empty. Exiting program." << std::endl; + return 0; + } + + // Read the target sum from STDIN + int target; + std::cin >> target; + + // Find and print the unique quadruplets + std::vector> sum = fourSum(v, target); + std::cout << "Result:" << std::endl; + for (int i = 0; i < sum.size(); i++) { + for (int j = 0; j < sum[i].size(); j++) + std::cout << sum[i][j] << " "; + std::cout << std::endl; + } + + return 0; +} diff --git a/Arrays/Hard/FourNumberSum/FourNumberSum.java b/Arrays/Hard/FourNumberSum/FourNumberSum.java new file mode 100644 index 00000000..73c1ff0c --- /dev/null +++ b/Arrays/Hard/FourNumberSum/FourNumberSum.java @@ -0,0 +1,108 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +public class Main { + static List> fourSum(int[] arr, int target) { + ArrayList> res = new ArrayList<>(); + + if (arr == null || arr.length == 0) { + System.out.println("Input array is empty or null. Returning empty result."); + return res; + } + + int n = arr.length; + + // Sort the input array in ascending order + Arrays.sort(arr); + + for (int i = 0; i < n; i++) { + // Reduce the problem to finding a 3-sum + int target_3 = target - arr[i]; + + for (int j = i + 1; j < n; j++) { + // Reduce the problem to finding a 2-sum + int target_2 = target_3 - arr[j]; + + int front = j + 1; + int back = n - 1; + + while (front < back) { + int two_sum = arr[front] + arr[back]; + + if (two_sum < target_2) front++; + else if (two_sum > target_2) back--; + else { + // Found a valid quadruplet, add to the result + List quad = new ArrayList<>(); + quad.add(arr[i]); + quad.add(arr[j]); + quad.add(arr[front]); + quad.add(arr[back]); + res.add(quad); + + // Move pointers to avoid duplicates + while (front < back && arr[front] == quad.get(2)) ++front; + while (front < back && arr[back] == quad.get(3)) --back; + } + } + + // Move pointer to avoid duplicates + while (j + 1 < n && arr[j + 1] == arr[j]) ++j; + } + + // Move pointer to avoid duplicates + while (i + 1 < n && arr[i + 1] == arr[i]) ++i; + } + + return res; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Read the array elements from STDIN + String[] arrString = scanner.nextLine().split(""); + + // Check if the input array is empty + if (arrString.length == 0) { + System.out.println("Input array is empty. Exiting program."); + scanner.close(); + return; + } + + int[] arr = new int[arrString.length]; + try { + for (int i = 0; i < arrString.length; i++) { + arr[i] = Integer.parseInt(arrString[i]); + } + } catch (NumberFormatException e) { + System.out.println("Invalid input. Please enter valid integers. Exiting program."); + scanner.close(); + return; + } + + // Read the target sum from STDIN + int target; + try { + target = scanner.nextInt(); + } catch (Exception e) { + System.out.println("Invalid input for target sum. Exiting program."); + scanner.close(); + return; + } + + List> result = fourSum(arr, target); + + // Print the result + for (List quad : result) { + for (int num : quad) { + System.out.print(num + " "); + } + System.out.println(); + } + + scanner.close(); + } +} diff --git a/Arrays/Hard/FourNumberSum/FourNumberSum.py b/Arrays/Hard/FourNumberSum/FourNumberSum.py new file mode 100644 index 00000000..2ab4b08d --- /dev/null +++ b/Arrays/Hard/FourNumberSum/FourNumberSum.py @@ -0,0 +1,84 @@ +# Copyrights to venkys.io +# For more programs visit venkys.io +# Python program for FourNumberSum + +#Time Complexity : O(n^k-1) +#Space Complexity : O(n^k-1)+O(k) + +def twosum(arr, target): + """ + Helper function for finding pairs that sum up to the target. + """ + res = [] + low, high = 0, len(arr) - 1 + + while low < high: + # Calculate the current sum of elements at low and high indices + cursum = arr[low] + arr[high] + + # Check conditions to adjust low and high indices + if cursum < target or (low > 0 and arr[low] == arr[low - 1]): + low += 1 + elif cursum > target or (high < len(arr) - 1 and arr[high] == arr[high + 1]): + high -= 1 + else: + # Append the pair to the result and move indices + res.append([arr[low], arr[high]]) + low += 1 + high -= 1 + return res + + +def ksum(arr, target, k): + """ + Main function for finding k elements that sum up to the target. + """ + res = [] + if not arr: + # Return an empty list if the input array is empty + return res + + avg = target // k + + # Check if the average is outside the range of the array + if avg < arr[0] or avg > arr[-1]: + return res + + if k == 2: + # If k is 2, call the twosum function + return twosum(arr, target) + + for i in range(len(arr)): + # Iterate through the array and avoid duplicate elements + if i == 0 or arr[i - 1] != arr[i]: + # Recursive call to find (k-1)-sum in the rest of the array + for s in ksum(arr[i + 1:], target - arr[i], k - 1): + # Append the current element to the solution + res.append([arr[i]] + s) + return res +if __name__ == "__main__": + # Read the array from STDIN + arr_input = input() + target_input = input() + k_input = input() + + # Check if inputs are provided + if not arr_input or not target_input or not k_input: + print("Please provide valid inputs.") + exit() + + try: + # Convert inputs to the required types + arr = list(map(int, arr_input.split())) + target = int(target_input) + k = int(k_input) + except ValueError: + print("Invalid input. Please enter valid numbers.") + exit() + + arr.sort() + # Call the ksum function with the input values + result = ksum(arr, target, k) + + # Print the result + print(result) diff --git a/Arrays/Hard/README.md b/Arrays/Hard/FourNumberSum/README.md similarity index 74% rename from Arrays/Hard/README.md rename to Arrays/Hard/FourNumberSum/README.md index 12499de6..dcd96ece 100644 --- a/Arrays/Hard/README.md +++ b/Arrays/Hard/FourNumberSum/README.md @@ -1,5 +1,5 @@ ## Problem Statement - Four Number Sum -Given an array of integers, find anyone combination of four elements in the array whose sum is equal to a given value X. +Given an array of integers,find anyone combination of four elements in the array whose sum is equal to a given value X. ## Introduction The Four Number Sum Problem is a mathematical challenge that involves finding all unique sets of four integers within a given array that add up to a specific target sum. This problem requires algorithmic solutions to efficiently identify and return these sets of four numbers. It is a combinatorial problem that often requires careful consideration of various edge cases and optimization strategies to achieve a solution with optimal time and space complexity. The problem's complexity increases with the size of the input array and the magnitude of the target sum, making it an interesting problem for algorithmic and computational thinking. Efficient solutions to the Four Number Sum Problem can have applications in various fields, including data analysis, cryptography, and optimization. @@ -9,9 +9,12 @@ The Four Number Sum Problem involves finding all unique quadruplets within an ar ### Python ```python # Copyrights to venkys.io -# For more programs, visit venkys.io +# For more programs visit venkys.io # Python program for FourNumberSum +#Time Complexity : O(n^k-1) +#Space Complexity : O(n^k-1)+O(k) + def twosum(arr, target): """ Helper function for finding pairs that sum up to the target. @@ -63,13 +66,32 @@ def ksum(arr, target, k): # Append the current element to the solution res.append([arr[i]] + s) return res - if __name__ == "__main__": - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + # Read the array from STDIN + arr_input = input() + target_input = input() + k_input = input() + + # Check if inputs are provided + if not arr_input or not target_input or not k_input: + print("Please provide valid inputs.") + exit() + + try: + # Convert inputs to the required types + arr = list(map(int, arr_input.split())) + target = int(target_input) + k = int(k_input) + except ValueError: + print("Invalid input. Please enter valid numbers.") + exit() + arr.sort() - target = 10 - print(ksum(arr, target, 4)) + # Call the ksum function with the input values + result = ksum(arr, target, k) + # Print the result + print(result) ``` ### Step-by-Step Explanation The provided Python program addresses the Four Number Sum problem, aiming to find all unique sets of four integers within a sorted array that add up to a specified target sum. The code consists of two functions: `twosum` and `ksum`. The `twosum` function serves as a helper to identify pairs in the array that sum up to a given target. It utilizes two pointers, 'low' and 'high,' which traverse the array inwards. The function efficiently skips duplicate elements and adjusts pointers based on the calculated current sum. @@ -80,85 +102,112 @@ In the provided example within the `__main__` block, an array [1, 2, 3, 4, 5, 6, ### Java ```java -// Copyrights to venkys.io -// For more programs visit venkys.io -// Java program for FourNumberSum import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Scanner; public class Main { static List> fourSum(int[] arr, int target) { - ArrayList> res = new ArrayList>(); - - if (arr == null || arr.length == 0) + ArrayList> res = new ArrayList<>(); + + if (arr == null || arr.length == 0) { + System.out.println("Input array is empty or null. Returning empty result."); return res; - + } + int n = arr.length; - + // Sort the input array in ascending order - Arrays.sort(arr); - + Arrays.sort(arr); + for (int i = 0; i < n; i++) { - // Reduce the problem to finding a 3-sum int target_3 = target - arr[i]; - + for (int j = i + 1; j < n; j++) { - // Reduce the problem to finding a 2-sum int target_2 = target_3 - arr[j]; - + int front = j + 1; int back = n - 1; - - while(front < back) { - + + while (front < back) { int two_sum = arr[front] + arr[back]; - + if (two_sum < target_2) front++; - else if (two_sum > target_2) back--; - else { // Found a valid quadruplet, add to the result - List quad = new ArrayList<>(); + List quad = new ArrayList<>(); quad.add(arr[i]); quad.add(arr[j]); quad.add(arr[front]); quad.add(arr[back]); res.add(quad); - + // Move pointers to avoid duplicates while (front < back && arr[front] == quad.get(2)) ++front; while (front < back && arr[back] == quad.get(3)) --back; } } - + // Move pointer to avoid duplicates - while(j + 1 < n && arr[j + 1] == arr[j]) ++j; + while (j + 1 < n && arr[j + 1] == arr[j]) ++j; } - + // Move pointer to avoid duplicates while (i + 1 < n && arr[i + 1] == arr[i]) ++i; } - + return res; } - public static void main (String[] args) { - int arr[] = {1, 0, -1, 0, -2, 2}; - int target = 0; + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + // Read the array elements from STDIN + String[] arrString = scanner.nextLine().split(""); + + // Check if the input array is empty + if (arrString.length == 0) { + System.out.println("Input array is empty. Exiting program."); + scanner.close(); + return; + } + + int[] arr = new int[arrString.length]; + try { + for (int i = 0; i < arrString.length; i++) { + arr[i] = Integer.parseInt(arrString[i]); + } + } catch (NumberFormatException e) { + System.out.println("Invalid input. Please enter valid integers. Exiting program."); + scanner.close(); + return; + } + + // Read the target sum from STDIN + int target; + try { + target = scanner.nextInt(); + } catch (Exception e) { + System.out.println("Invalid input for target sum. Exiting program."); + scanner.close(); + return; + } - List> ls = fourSum(arr, target); + List> result = fourSum(arr, target); // Print the result - for(int i = 0; i < ls.size(); i++) { - for(int j = 0; j < ls.get(i).size(); j++) { - System.out.print(ls.get(i).get(j) + " "); + for (List quad : result) { + for (int num : quad) { + System.out.print(num + " "); } - System.out.println(); + System.out.println(); } + + scanner.close(); } } ``` @@ -174,28 +223,26 @@ In the provided example within the `main` function, an array [1, 0, -1, 0, -2, 2 ### CPP ```cpp -// Copyrights to venkys.io -// For more programs visit venkys.io -// CPP program for FourNumberSum +#include +#include +#include -#include -using namespace std; +std::vector> fourSum(std::vector& num, int target) { + std::vector> res; -vector> fourSum(vector& num, int target) { - vector> res; - - if (num.empty()) + if (num.empty()) { + std::cout << "Input vector is empty. Returning empty result." << std::endl; return res; - int n = num.size(); - sort(num.begin(), num.end()); + } - for (int i = 0; i < n; i++) { + int n = num.size(); + std::sort(num.begin(), num.end()); + for (int i = 0; i < n; i++) { // Reduce the problem to finding a 3-sum int target_3 = target - num[i]; for (int j = i + 1; j < n; j++) { - // Reduce the problem to finding a 2-sum int target_2 = target_3 - num[j]; @@ -203,16 +250,13 @@ vector> fourSum(vector& num, int target) { int back = n - 1; while (front < back) { - int two_sum = num[front] + num[back]; if (two_sum < target_2) front++; - else if (two_sum > target_2) back--; - else { // Found a valid quadruplet, add to the result - vector quadruplet(4, 0); + std::vector quadruplet(4, 0); quadruplet[0] = num[i]; quadruplet[1] = num[j]; quadruplet[2] = num[front]; @@ -238,17 +282,34 @@ vector> fourSum(vector& num, int target) { return res; } -int main() -{ - vector v{1,0,-1,0,-2,2}; - int target=0; - vector> sum=fourSum(v,target); - cout<<"The unique quadruplets are"< v; + int num; + while (std::cin >> num) { + v.push_back(num); + } + + // Check if the input vector is empty + if (v.empty()) { + std::cout << "Input vector is empty. Exiting program." << std::endl; + return 0; + } + + // Read the target sum from STDIN + int target; + std::cin >> target; + + // Find and print the unique quadruplets + std::vector> sum = fourSum(v, target); + std::cout << "Result:" << std::endl; for (int i = 0; i < sum.size(); i++) { for (int j = 0; j < sum[i].size(); j++) - cout << sum[i][j] << " "; - cout << endl; + std::cout << sum[i][j] << " "; + std::cout << std::endl; } + + return 0; } ``` ### Step-by-Step Explanation @@ -262,14 +323,14 @@ In the 'main' function, a sample vector [1, 0, -1, 0, -2, 2] and a target sum of The time and space complexity of the provided Python program for the Four Number Sum problem can be analyzed as follows: ### Time Complexity: -The time complexity of the program primarily depends on the `ksum` function, which recursively breaks down the problem. Let \(n\) be the length of the input array 'arr.' The main loop iterates through the array, and for each element, a recursive call is made to find \((k-1)\)-sum. In the worst case, the function explores all possible combinations of \(k\) elements, leading to a time complexity of \(O(n^k)\). The recursive calls within the loop contribute to the overall time complexity. +The time complexity of the program primarily depends on the `ksum` function, which recursively breaks down the problem. Let \(n\) be the length of the input array 'arr.' The main loop iterates through the array, and for each element, a recursive call is made to find \((k-1)\)-sum. In the worst case, the function explores all possible combinations of \(k\) elements, leading to a time complexity of \(O(n^k-1)\). The recursive calls within the loop contribute to the overall time complexity. ### Space Complexity: -The space complexity is determined by the auxiliary space used during the recursion and the storage of the results. In each recursive call, a new list is created to store the current combination. The depth of the recursion is \(k\), so the maximum stack space required is \(O(k)\). Additionally, the 'res' list accumulates the final result, and in the worst case, it can store \(O(n^k)\) combinations. Therefore, the space complexity is \(O(k) + O(n^k)\). +The space complexity is determined by the auxiliary space used during the recursion and the storage of the results. In each recursive call, a new list is created to store the current combination. The depth of the recursion is \(k\), so the maximum stack space required is \(O(k)\). Additionally, the 'res' list accumulates the final result, and in the worst case, it can store \(O(n^k-1)\) combinations. Therefore, the space complexity is \(O(k) + O(n^k-1)\). ### Summary: -- Time Complexity: \(O(n^k)\) -- Space Complexity: \(O(k) + O(n^k)\) +- Time Complexity: \(O(n^k-1)\) +- Space Complexity: \(O(k) + O(n^k-1)\) ## Real-World Applications 1. **Finance and Investment Strategies:** - In finance, particularly portfolio optimization and risk management, the Four Number Sum problem can be applied to identify combinations of financial assets that collectively meet certain criteria. For instance, investors may look for groups of stocks whose values sum up to a target, representing a balanced and diversified investment. @@ -285,3 +346,45 @@ The space complexity is determined by the auxiliary space used during the recurs 5. **Chemical Compound Discovery in Drug Development:** - In pharmaceutical research, scientists can utilize the Four Number Sum problem to explore combinations of chemical compounds that exhibit desired properties for drug development. Identifying sets of compounds whose characteristics sum up to specific criteria can accelerate the process of discovering novel drugs with desired therapeutic effects. + +## Test Cases: + +Test Case 1: +**Input:** +``` +1 0 -1 0 -2 2 +0 +4 +``` + +**Output:** +``` +[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] +``` + +**Explanation:** +- The program takes the input array `[1, 0, -1, 0, -2, 2]`, target `0`, and `k = 4`. +- It then sorts the input array. +- Using the `ksum` function, it finds all combinations of `k` elements that sum up to the target. +- In this case, it finds three unique combinations: `[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]`. +- The program prints the resulting combinations. + +Test Case 2: +**Input:** +``` +3 7 8 10 12 14 +18 +3 +``` + +**Output:** +``` +[[3, 7, 8]] +``` + +**Explanation:** +- The program takes the input array `[3, 7, 8, 10, 12, 14]`, target `18`, and `k = 3`. +- It then sorts the input array. +- Using the `ksum` function, it finds all combinations of `k` elements that sum up to the target. +- In this case, it finds one unique combination: `[[3, 7, 8]]`. +- The program prints the resulting combination. diff --git a/Strings/Easy/ValidPalindrome/Java.md b/Strings/Easy/ValidPalindrome/Java.md index 1ba0f374..8b1d2d9b 100644 --- a/Strings/Easy/ValidPalindrome/Java.md +++ b/Strings/Easy/ValidPalindrome/Java.md @@ -7,10 +7,15 @@ In the Valid Palindrome problem, the task is to create an algorithm or function ## Overview The Valid Palindrome problem entails designing a solution to determine whether a given string is a valid palindrome, considering only alphanumeric characters and ignoring differences in case. The task involves evaluating whether the string reads the same forward and backward after removing non-alphanumeric characters. This problem is a classic exercise in string manipulation and often requires an efficient algorithm to address various edge cases. The solution involves traversing the string from both ends, comparing corresponding characters, and adjusting for case differences and non-alphanumeric characters. The Valid Palindrome problem is frequently encountered in algorithmic interviews and serves as an essential challenge for honing skills in string processing and logical reasoning. ## Code -```cpp +```java //Copyrights to venkys.io //For more programs visit venkys.io //Java program for ValidPalindrome + +//Time Complexity : O(n) +//Space Complexity : O(1) + +import java.util.Scanner; public class Main { // Function to check if a given string is a palindrome @@ -43,16 +48,23 @@ public class Main { // Main function public static void main(String[] args) { - // Example string - String s = "A man, a plan, a canal: Panama"; + // Create a Scanner object to read input from STDIN + Scanner scanner = new Scanner(System.in); + + // Read the input string from STDIN + String s = scanner.nextLine(); // Check if the string is a palindrome using the isPalindrome function if (isPalindrome(s)) System.out.println("It is a palindrome"); else System.out.println("It is not a palindrome"); + + // Close the Scanner object + scanner.close(); } } + ``` ## Step-by-Step Explanation diff --git a/Strings/Easy/ValidPalindrome/Python.md b/Strings/Easy/ValidPalindrome/Python.md index c57811d5..bd9bb07d 100644 --- a/Strings/Easy/ValidPalindrome/Python.md +++ b/Strings/Easy/ValidPalindrome/Python.md @@ -8,7 +8,14 @@ In the Valid Palindrome problem, the task is to create an algorithm or function The Valid Palindrome problem entails designing a solution to determine whether a given string is a valid palindrome, considering only alphanumeric characters and ignoring differences in case. The task involves evaluating whether the string reads the same forward and backward after removing non-alphanumeric characters. This problem is a classic exercise in string manipulation and often requires an efficient algorithm to address various edge cases. The solution involves traversing the string from both ends, comparing corresponding characters, and adjusting for case differences and non-alphanumeric characters. The Valid Palindrome problem is frequently encountered in algorithmic interviews and serves as an essential challenge for honing skills in string processing and logical reasoning. ## Code ```python -def ispalindrome(string): +# Copyrights to venkys.io +# For more programs visit venkys.io +# Python program for ValidPalindrome + +# Time Complexity : O(n) +# Space Complexity : O(1) + +def is_palindrome(string): rev = "" for char in string: if char.isalpha(): @@ -22,9 +29,19 @@ def ispalindrome(string): high -= 1 return True -s = "A man, a plan, a canal: Panama" -a = ispalindrome(s) -print(a) +def main(): + # Read the input string from STDIN + s = input( + # Check if the string is a palindrome using the is_palindrome function + result = is_palindrome(s) + # Print the result + if result: + print("It is a palindrome") + else: + print("It is not a palindrome") +if __name__ == "__main__": + main() + ``` ## Step-by-Step Explanation diff --git a/Strings/Easy/ValidPalindrome/cpp.md b/Strings/Easy/ValidPalindrome/cpp.md index f3e8f6e4..88340c26 100644 --- a/Strings/Easy/ValidPalindrome/cpp.md +++ b/Strings/Easy/ValidPalindrome/cpp.md @@ -8,35 +8,41 @@ In the Valid Palindrome problem, the task is to create an algorithm or function The Valid Palindrome problem entails designing a solution to determine whether a given string is a valid palindrome, considering only alphanumeric characters and ignoring differences in case. The task involves evaluating whether the string reads the same forward and backward after removing non-alphanumeric characters. This problem is a classic exercise in string manipulation and often requires an efficient algorithm to address various edge cases. The solution involves traversing the string from both ends, comparing corresponding characters, and adjusting for case differences and non-alphanumeric characters. The Valid Palindrome problem is frequently encountered in algorithmic interviews and serves as an essential challenge for honing skills in string processing and logical reasoning. ## Code ```cpp + //Copyrights to venkys.io //For more programs visit venkys.io //CPP program for ValidPalindrome -#include + +//Time Complexity : O(n) +//Space Complexity : O(1) + +#include +#include using namespace std; // Function to check if a given string is a palindrome -bool isPalindrome(string s){ +bool isPalindrome(string s) { + if (s.empty()) { + // If the string is empty, consider it not a palindrome + return false; + } string rev = ""; // Iterate through each character in the string - for(char ch : s){ - // Check if the character is a lowercase letter (ASCII values 97 to 122) - if(ch >= 97 && ch <= 122) - rev += ch; - // Check if the character is an uppercase letter (ASCII values 65 to 90) - else if(ch >= 65 && ch <= 90) - // Convert the uppercase letter to lowercase and add it to the 'rev' string - rev += ch + 32; + for (char ch : s) { + // Check if the character is an alphabet letter + if (isalpha(ch)) + rev += tolower(ch); // Convert the character to lowercase and add it to the 'rev' string } // Initialize two pointers for comparing characters from both ends of the 'rev' string int i = 0, j = rev.length() - 1; // Iterate until the pointers meet in the middle - while(i < j){ + while (i < j) { // Compare characters at the current positions, and move the pointers accordingly - if(rev[i++] != rev[j--]) return false; + if (rev[i++] != rev[j--]) return false; } // If the loop completes without finding any mismatches, the string is a palindrome @@ -44,12 +50,12 @@ bool isPalindrome(string s){ } // Main function -int main(){ - // Example string - string s = "A man, a plan, a canal: Panama"; - +int main() { + // Read the input string from STDIN + string s; + getline(cin, s); // Check if the string is a palindrome using the isPalindrome function - if(isPalindrome(s)) + if (isPalindrome(s)) cout << "It is a palindrome"; else cout << "It is not a palindrome"; @@ -57,6 +63,7 @@ int main(){ return 0; } + ``` ## Step-by-Step Explanation diff --git a/Strings/Medium/README.md b/Strings/Medium/README.md index 355fec30..189bb592 100644 --- a/Strings/Medium/README.md +++ b/Strings/Medium/README.md @@ -12,8 +12,12 @@ The Longest Palindromic Substring problem involves finding the longest contiguou #Copyrights to venkys.io #For more programs visit venkys.io #Python program for LongestPalindromicSubstring -def expandFromCenter(string, left, right): - global maxlength + +# Time Complexity - O(n^2) +# Space Complexity - O(1) + +def expand_from_center(string, left, right): + global max_length global start # Keep expanding while the characters at left and right indices are equal @@ -22,38 +26,42 @@ def expandFromCenter(string, left, right): right += 1 # Update the maximum length and start index if a longer palindrome is found - if maxlength < right - left - 1: - maxlength = right - left - 1 + if max_length < right - left - 1: + max_length = right - left - 1 start = left + 1 -# Initialize global variables maxlength and start -global maxlength -maxlength = 0 +# Initialize global variables max_length and start +global max_length +max_length = 0 global start start = 0 -def longestPalindrome(string): - global maxlength +def longest_palindrome(string): + global max_length global start # Iterate through each character in the string for i in range(len(string)): # Find the length of palindrome when the center is a single character - expandFromCenter(string, i, i) + expand_from_center(string, i, i) # Find the length of palindrome when the center is between two characters - expandFromCenter(string, i, i + 1) + expand_from_center(string, i, i + 1) - # Return the longest palindrome substring using start and maxlength - return string[start:start + maxlength] + # Return the longest palindrome substring using start and max_length + return string[start:start + max_length] if __name__ == "__main__": - # Example usage - string = "badab" - - # Print the longest palindrome in the given string - print(longestPalindrome(string)) + # Read the input string from STDIN + string = input() + + # Check for null safety + if not string: + print("Input string is empty.") + else: + # Print the longest palindrome in the given string + print(longest_palindrome(string)) ``` ### Step-by-Step Explanation @@ -66,9 +74,15 @@ The `longestPalindrome` function iterates through each character in the input st In the example usage section, the code demonstrates finding the longest palindrome in the string "badab" and prints the result. The provided implementation has a time complexity of O(n^2), where n is the length of the input string, as each expansion process takes linear time. This efficient algorithm allows for the identification of palindromic substrings within a given string. ### Java ```java -#Copyrights to venkys.io -#For more programs visit venkys.io -#Java program for LongestPalindromicSubstring +// Copyrights to venkys.io +// For more programs visit venkys.io +// Java program for LongestPalindromicSubstring + +// Time Complexity - O(n^2) +// Space Complexity- O(1) + +import java.util.Scanner; + public class Main { // Function to find the longest palindrome in the given string @@ -115,11 +129,22 @@ public class Main { // Main method for testing public static void main(String[] args) { - // Example usage - String s = "badab"; - - // Print the longest palindrome in the given string - System.out.println(longestPalindrome(s)); + // Create a Scanner object to read input from STDIN + Scanner scanner = new Scanner(System.in); + + // Read the input string from STDIN + String s = scanner.nextLine(); + + // Check for null safety + if (s.isEmpty()) { + System.out.println("Input string is empty."); + } else { + // Print the longest palindrome in the given string + System.out.println(longestPalindrome(s)); + } + + // Close the Scanner object + scanner.close(); } } @@ -132,56 +157,92 @@ Within the main loop of `longestPalindrome`, the lengths `len1` and `len2` are c After the iteration, the function returns the substring of the input string that corresponds to the longest palindrome, using the updated `start` and `end` indices. In the example usage section, the code demonstrates finding the longest palindrome in the string "badab" and prints the result. The time complexity of the algorithm is O(n^2), where n is the length of the input string, as each expansion process takes linear time. The provided implementation efficiently identifies palindromic substrings within the given string. ### CPP ```cpp -#Copyrights to venkys.io -#For more programs visit venkys.io -#cpp program for LongestPalindromicSubstring -#include -using namespace std; - -// Function to expand around the center and find the length of the palindrome -int expandFromCenter(std::string& string, int left, int right) { - // Keep expanding while the characters at left and right indices are equal - while (left > -1 && right < string.length() && string[left] == string[right]) { - left--; - right++; +#include +#include +#include + +std::vector> fourSum(std::vector& num, int target) { + std::vector> res; + + if (num.empty()) { + std::cout << "Input vector is empty. Returning empty result." << std::endl; + return res; } - // Return the length of the palindrome found - return right - left - 1; -} -// Function to find the longest palindrome in a given string -string longestPalindrome(std::string& string) { - // Initialize start and end indices for the longest palindrome found - int start = 0, end = 0; - - // Iterate through each character in the string - for (int i = 0; i < string.length(); i++) { - // Find the length of palindrome when the center is a single character - int len1 = expandFromCenter(string, i, i); - // Find the length of palindrome when the center is between two characters - int len2 = expandFromCenter(string, i, i + 1); - - // Find the maximum length between len1 and len2 - int len = std::max(len1, len2); - - // If the current palindrome is longer than the previous one, update start and end indices - if (len > end - start) { - start = i - (len - 1) / 2; - end = i + len / 2; + int n = num.size(); + std::sort(num.begin(), num.end()); + + for (int i = 0; i < n; i++) { + // Reduce the problem to finding a 3-sum + int target_3 = target - num[i]; + + for (int j = i + 1; j < n; j++) { + // Reduce the problem to finding a 2-sum + int target_2 = target_3 - num[j]; + + int front = j + 1; + int back = n - 1; + + while (front < back) { + int two_sum = num[front] + num[back]; + + if (two_sum < target_2) front++; + else if (two_sum > target_2) back--; + else { + // Found a valid quadruplet, add to the result + std::vector quadruplet(4, 0); + quadruplet[0] = num[i]; + quadruplet[1] = num[j]; + quadruplet[2] = num[front]; + quadruplet[3] = num[back]; + res.push_back(quadruplet); + + // Processing the duplicates of number 3 + while (front < back && num[front] == quadruplet[2]) ++front; + + // Processing the duplicates of number 4 + while (front < back && num[back] == quadruplet[3]) --back; + } + } + + // Processing the duplicates of number 2 + while (j + 1 < n && num[j + 1] == num[j]) ++j; } + + // Processing the duplicates of number 1 + while (i + 1 < n && num[i + 1] == num[i]) ++i; } - - // Return the longest palindrome substring - return string.substr(start, end + 1); + + return res; } int main() { - // Example usage - string str = "badab"; - - // Print the longest palindrome in the given string - cout << longestPalindrome(str); - + // Read the array elements from STDIN + std::vector v; + int num; + while (std::cin >> num) { + v.push_back(num); + } + + // Check if the input vector is empty + if (v.empty()) { + std::cout << "Input vector is empty. Exiting program." << std::endl; + return 0; + } + + // Read the target sum from STDIN + int target; + std::cin >> target; + + // Find and print the unique quadruplets + std::vector> sum = fourSum(v, target); + std::cout << "Result:" << std::endl; + for (int i = 0; i < sum.size(); i++) { + for (int j = 0; j < sum[i].size(); j++) + std::cout << sum[i][j] << " "; + std::cout << std::endl; + } + return 0; }