Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions Arrays/Hard/FourNumberSum/FourNumberSum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include <iostream>
#include <vector>
#include <algorithm>

std::vector<std::vector<int>> fourSum(std::vector<int>& num, int target) {
std::vector<std::vector<int>> 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<int> 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<int> 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<std::vector<int>> 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;
}
108 changes: 108 additions & 0 deletions Arrays/Hard/FourNumberSum/FourNumberSum.java
Original file line number Diff line number Diff line change
@@ -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<List<Integer>> fourSum(int[] arr, int target) {
ArrayList<List<Integer>> 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<Integer> 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<List<Integer>> result = fourSum(arr, target);

// Print the result
for (List<Integer> quad : result) {
for (int num : quad) {
System.out.print(num + " ");
}
System.out.println();
}

scanner.close();
}
}
84 changes: 84 additions & 0 deletions Arrays/Hard/FourNumberSum/FourNumberSum.py
Original file line number Diff line number Diff line change
@@ -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)
Loading