From cebfc1d56d399e98bc4657d544a156898b7b7b13 Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 9 Dec 2023 21:07:41 +0530 Subject: [PATCH 01/15] Update README.md --- Arrays/Hard/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/Hard/README.md b/Arrays/Hard/README.md index 12499de6..9248b28a 100644 --- a/Arrays/Hard/README.md +++ b/Arrays/Hard/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. From 2d35d318db832103df69d6c4d657f29756d3ca91 Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Fri, 5 Jan 2024 12:53:36 +0530 Subject: [PATCH 02/15] Made necessary changes in Four Number Sum problem Made pull request 2nd review --- Arrays/Hard/README.md | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Arrays/Hard/README.md b/Arrays/Hard/README.md index 9248b28a..d6ee90e2 100644 --- a/Arrays/Hard/README.md +++ b/Arrays/Hard/README.md @@ -12,6 +12,9 @@ The Four Number Sum Problem involves finding all unique quadruplets within an ar # 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. @@ -83,6 +86,9 @@ In the provided example within the `__main__` block, an array [1, 2, 3, 4, 5, 6, // Copyrights to venkys.io // For more programs visit venkys.io // Java program for FourNumberSum + +//Time Complexity : O(n^k-1) +//Space Complexity : O(n^k-1)+O(k) import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -178,6 +184,9 @@ In the provided example within the `main` function, an array [1, 0, -1, 0, -2, 2 // For more programs visit venkys.io // CPP program for FourNumberSum +//Time Complexity : O(n^k-1) +//Space Complexity : O(n^k-1)+O(k) + #include using namespace std; @@ -262,14 +271,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. From 6d64901601936a581d8931789110ce31dc71f36d Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:36:20 +0530 Subject: [PATCH 03/15] Update README.md for Four number sum (updated STDIN in code) --- Arrays/Hard/README.md | 58 ++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/Arrays/Hard/README.md b/Arrays/Hard/README.md index d6ee90e2..a2264657 100644 --- a/Arrays/Hard/README.md +++ b/Arrays/Hard/README.md @@ -9,7 +9,7 @@ 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) @@ -68,11 +68,22 @@ def ksum(arr, target, k): return res if __name__ == "__main__": - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + # Read the array from STDIN + arr = list(map(int, input().split())) + + # Read the target sum from STDIN + target = int(input()) + + # Read the value of k from STDIN + k = int(input()) + 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. @@ -88,10 +99,12 @@ In the provided example within the `__main__` block, an array [1, 2, 3, 4, 5, 6, // Java program for FourNumberSum //Time Complexity : O(n^k-1) -//Space Complexity : O(n^k-1)+O(k) +//Space Complexity : O(n^k-1)+O(k)\ + 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) { @@ -152,12 +165,15 @@ public class Main { 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(" "); + int[] arr = Arrays.stream(arrString).mapToInt(Integer::parseInt).toArray(); + // Read the target sum from STDIN + int target = scanner.nextInt(); List> ls = fourSum(arr, target); - // Print the result for(int i = 0; i < ls.size(); i++) { for(int j = 0; j < ls.get(i).size(); j++) { @@ -165,6 +181,8 @@ public class Main { } System.out.println(); } + + scanner.close(); } } ``` @@ -249,16 +267,28 @@ vector> fourSum(vector& num, int target) { 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 (cin >> num) { + v.push_back(num); + } + + // Read the target sum from STDIN + int target; + cin >> target; + + // Find and print the unique quadruplets + vector> sum = fourSum(v, target); for (int i = 0; i < sum.size(); i++) { for (int j = 0; j < sum[i].size(); j++) cout << sum[i][j] << " "; cout << endl; } + + return 0; } + ``` ### Step-by-Step Explanation This C++ program addresses the Four Number Sum problem, aiming to find all unique quadruplets within a given vector 'num' that add up to a specified target. The 'fourSum' function employs a systematic approach, starting with sorting the input vector in ascending order, a critical step for efficient solutions. The program then utilizes nested loops to iterate through the vector, considering each element as a potential starting point for the quadruplet. It reduces the problem to finding a 3-sum by subtracting the current element from the target. From 4216251f61223e1583d05876464d68234bf272e5 Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:40:29 +0530 Subject: [PATCH 04/15] Update Java.md for valid Palindrome (updated STDIN for code) --- Strings/Easy/ValidPalindrome/Java.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) 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 From 841e3a9d15ab496a62b83d65326acc9c3cf5c748 Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:42:52 +0530 Subject: [PATCH 05/15] Update Python.md for Valid Palindrome (Updated STDIN for code) --- Strings/Easy/ValidPalindrome/Python.md | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) 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 From fb93c8fd20db2e001ada44dee1d59dffc1eca7da Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:45:32 +0530 Subject: [PATCH 06/15] Update cpp.md for valid Palindrome (Updated STDIN for code) --- Strings/Easy/ValidPalindrome/cpp.md | 37 ++++++++++++++++------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/Strings/Easy/ValidPalindrome/cpp.md b/Strings/Easy/ValidPalindrome/cpp.md index f3e8f6e4..e43f8dc5 100644 --- a/Strings/Easy/ValidPalindrome/cpp.md +++ b/Strings/Easy/ValidPalindrome/cpp.md @@ -8,35 +8,37 @@ 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) { 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 +46,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 +59,7 @@ int main(){ return 0; } + ``` ## Step-by-Step Explanation From c14ef2e0c7bf5f7fe5257f46872674eb47ff4ccf Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:47:15 +0530 Subject: [PATCH 07/15] Update cpp.md --- Strings/Easy/ValidPalindrome/cpp.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Strings/Easy/ValidPalindrome/cpp.md b/Strings/Easy/ValidPalindrome/cpp.md index e43f8dc5..88340c26 100644 --- a/Strings/Easy/ValidPalindrome/cpp.md +++ b/Strings/Easy/ValidPalindrome/cpp.md @@ -23,6 +23,10 @@ using namespace std; // Function to check if a given string is a palindrome 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 From ce3165b8e846f5c7229a420795e5427f346158b3 Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:54:01 +0530 Subject: [PATCH 08/15] Update README.md of Longest Palindrome Substring (added STDIN and null safety) --- Strings/Medium/README.md | 88 +++++++++++++++++++++++++++------------- 1 file changed, 59 insertions(+), 29 deletions(-) diff --git a/Strings/Medium/README.md b/Strings/Medium/README.md index 355fec30..25c044a2 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,9 +157,14 @@ 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 +// Copyrights to venkys.io +// For more programs visit venkys.io +// cpp program for LongestPalindromicSubstring + +// Time Complexity - O(n^2) +// Space Complexity- O(1) + + #include using namespace std; From 01d1855c9a39a477f31fb01e70ed1a6f1425dc7c Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Sat, 6 Jan 2024 10:56:03 +0530 Subject: [PATCH 09/15] Update README.md of Longest Palindrome substring (updated cpp code --- Strings/Medium/README.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/Strings/Medium/README.md b/Strings/Medium/README.md index 25c044a2..de04ff87 100644 --- a/Strings/Medium/README.md +++ b/Strings/Medium/README.md @@ -164,14 +164,15 @@ After the iteration, the function returns the substring of the input string that // Time Complexity - O(n^2) // Space Complexity- O(1) +#include +#include -#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) { +int expand_from_center(string& s, 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]) { + while (left > -1 && right < s.length() && s[left] == s[right]) { left--; right++; } @@ -180,19 +181,19 @@ int expandFromCenter(std::string& string, int left, int right) { } // Function to find the longest palindrome in a given string -string longestPalindrome(std::string& string) { +string longest_palindrome(string& s) { // 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++) { + for (int i = 0; i < s.length(); i++) { // Find the length of palindrome when the center is a single character - int len1 = expandFromCenter(string, i, i); + int len1 = expand_from_center(s, i, i); // Find the length of palindrome when the center is between two characters - int len2 = expandFromCenter(string, i, i + 1); + int len2 = expand_from_center(s, i, i + 1); // Find the maximum length between len1 and len2 - int len = std::max(len1, len2); + int len = max(len1, len2); // If the current palindrome is longer than the previous one, update start and end indices if (len > end - start) { @@ -202,15 +203,16 @@ string longestPalindrome(std::string& string) { } // Return the longest palindrome substring - return string.substr(start, end + 1); + return s.substr(start, end + 1); } int main() { - // Example usage - string str = "badab"; + // Read the input string from STDIN + string str; + getline(cin, str); // Print the longest palindrome in the given string - cout << longestPalindrome(str); + cout << longest_palindrome(str); return 0; } From ccd65656e7a806dfb8b08fc979e82e94fdad1b2f Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Wed, 10 Jan 2024 13:02:20 +0530 Subject: [PATCH 10/15] Update README.md of four number sum (added null safety) --- Arrays/Hard/README.md | 178 ++++++++++++++++++++++++------------------ 1 file changed, 100 insertions(+), 78 deletions(-) diff --git a/Arrays/Hard/README.md b/Arrays/Hard/README.md index a2264657..f10542a7 100644 --- a/Arrays/Hard/README.md +++ b/Arrays/Hard/README.md @@ -66,22 +66,30 @@ def ksum(arr, target, k): # Append the current element to the solution res.append([arr[i]] + s) return res - if __name__ == "__main__": # Read the array from STDIN - arr = list(map(int, input().split())) - - # Read the target sum from STDIN - target = int(input()) - - # Read the value of k from STDIN - k = int(input()) - + 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) ``` @@ -94,13 +102,6 @@ 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 - -//Time Complexity : O(n^k-1) -//Space Complexity : O(n^k-1)+O(k)\ - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -108,78 +109,102 @@ 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) { Scanner scanner = new Scanner(System.in); + // Read the array elements from STDIN - String[] arrString = scanner.nextLine().split(" "); - int[] arr = Arrays.stream(arrString).mapToInt(Integer::parseInt).toArray(); + 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 = scanner.nextInt(); - List> ls = fourSum(arr, target); + 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(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(); @@ -198,31 +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 - -//Time Complexity : O(n^k-1) -//Space Complexity : O(n^k-1)+O(k) +#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]; @@ -230,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]; @@ -265,30 +282,35 @@ vector> fourSum(vector& num, int target) { return res; } -int main() -{ +int main() { // Read the array elements from STDIN - vector v; + std::vector v; int num; - while (cin >> 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; - cin >> target; + std::cin >> target; // Find and print the unique quadruplets - vector> sum = fourSum(v, target); + 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 This C++ program addresses the Four Number Sum problem, aiming to find all unique quadruplets within a given vector 'num' that add up to a specified target. The 'fourSum' function employs a systematic approach, starting with sorting the input vector in ascending order, a critical step for efficient solutions. The program then utilizes nested loops to iterate through the vector, considering each element as a potential starting point for the quadruplet. It reduces the problem to finding a 3-sum by subtracting the current element from the target. From d4765de9f1d9bb25c05267ac36018fe2962b9e2a Mon Sep 17 00:00:00 2001 From: Chilla Mahananda Reddy <110614784+mahananda123@users.noreply.github.com> Date: Wed, 10 Jan 2024 13:11:09 +0530 Subject: [PATCH 11/15] Update README.md of Lonest Palindrome Substring (updated cpp code) --- Strings/Medium/README.md | 123 ++++++++++++++++++++++++--------------- 1 file changed, 76 insertions(+), 47 deletions(-) diff --git a/Strings/Medium/README.md b/Strings/Medium/README.md index de04ff87..189bb592 100644 --- a/Strings/Medium/README.md +++ b/Strings/Medium/README.md @@ -157,63 +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 - -// Time Complexity - O(n^2) -// Space Complexity- O(1) - #include -#include +#include +#include -using namespace std; +std::vector> fourSum(std::vector& num, int target) { + std::vector> res; -// Function to expand around the center and find the length of the palindrome -int expand_from_center(string& s, int left, int right) { - // Keep expanding while the characters at left and right indices are equal - while (left > -1 && right < s.length() && s[left] == s[right]) { - left--; - right++; + 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 longest_palindrome(string& s) { - // 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 < s.length(); i++) { - // Find the length of palindrome when the center is a single character - int len1 = expand_from_center(s, i, i); - // Find the length of palindrome when the center is between two characters - int len2 = expand_from_center(s, i, i + 1); - - // Find the maximum length between len1 and len2 - int len = 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 s.substr(start, end + 1); + + return res; } int main() { - // Read the input string from STDIN - string str; - getline(cin, str); - - // Print the longest palindrome in the given string - cout << longest_palindrome(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; } From 9c18745f788c227e32aadad9ccc783e4b0ad7376 Mon Sep 17 00:00:00 2001 From: Sneha Vellelath <129183233+vellsneha@users.noreply.github.com> Date: Sun, 31 Mar 2024 21:25:16 +0530 Subject: [PATCH 12/15] Update and rename Arrays/Hard/README.md to Arrays/Hard/FourNumberSum/README.md --- Arrays/Hard/{ => FourNumberSum}/README.md | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) rename Arrays/Hard/{ => FourNumberSum}/README.md (94%) diff --git a/Arrays/Hard/README.md b/Arrays/Hard/FourNumberSum/README.md similarity index 94% rename from Arrays/Hard/README.md rename to Arrays/Hard/FourNumberSum/README.md index f10542a7..dcd96ece 100644 --- a/Arrays/Hard/README.md +++ b/Arrays/Hard/FourNumberSum/README.md @@ -346,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. From f4c32d8056fd4dc2bb00fc9c43a1e121606a0004 Mon Sep 17 00:00:00 2001 From: Sneha Vellelath <129183233+vellsneha@users.noreply.github.com> Date: Sun, 31 Mar 2024 21:26:34 +0530 Subject: [PATCH 13/15] Create FourNumberSum.py --- Arrays/Hard/FourNumberSum/FourNumberSum.py | 84 ++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Arrays/Hard/FourNumberSum/FourNumberSum.py 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) From b52252538c1411ccd85893e1c81ed22aa777869e Mon Sep 17 00:00:00 2001 From: Sneha Vellelath <129183233+vellsneha@users.noreply.github.com> Date: Mon, 1 Apr 2024 10:50:58 +0530 Subject: [PATCH 14/15] Create FourNumberSum.java --- Arrays/Hard/FourNumberSum/FourNumberSum.java | 108 +++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Arrays/Hard/FourNumberSum/FourNumberSum.java 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(); + } +} From 0072684a4525a1994c1c950f79310fba742af3d0 Mon Sep 17 00:00:00 2001 From: Sneha Vellelath <129183233+vellsneha@users.noreply.github.com> Date: Mon, 1 Apr 2024 10:51:34 +0530 Subject: [PATCH 15/15] Create FourNumberSum.cpp --- Arrays/Hard/FourNumberSum/FourNumberSum.cpp | 88 +++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Arrays/Hard/FourNumberSum/FourNumberSum.cpp 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; +}