CSES Solutions Sum of Four Values (original) (raw)

Last Updated : 23 Jul, 2025

You are given an array arr[] of **N integers, and your task is to find four values (at distinct positions) whose sum is **X.

**Note: If there are multiple answers, print any one of them.

**Examples:

**Input: N = 8, X = 15, arr[] = {3, 2, 5, 8, 1, 3, 2, 3}
**Output: 2 4 6 7
**Explanation: Elements at position 2, 4, 6 and 7 are: 2, 8, 3 and 2 respectively. Total sum = 2 + 8 + 3 + 2 = 15

**Input: N = 6, X = 20, arr[] = {3, 4, 5, 6, 7, 8}
**Output: 1 2 3 6
**Explanation: Elements at position 1, 2, 3 and 6 are: 3, 4, 5 and 8 respectively. Total sum = 3 + 4 + 5 + 8 = 20

**Approach: To solve the problem, follow the below idea:

The problem is similar to Sum of Three Values except that we need to find four indices whose values which sum up to X. This can be done by maintain an extra pointer for the fourth index.

The problem can be solved using Sorting and Two Pointer approach. Store pair of values and index of arr[] in a 2D vector, say **vec[][]. Sort vec[][] in **ascending order of the values. Iterate two nested loops, outer loop **ptr1 from 0 to N - 3, for the first value and inner loop **ptr2 from (ptr1 + 1) to N - 2. We assume that vec[ptr1][0] is the first value and vec[ptr2][0] is the second value and now we need to search for the third and fourth value. For the third and fourth value, we can use two pointers(ptr3 and ptr4) on the ends of the remaining subarray (ptr3 = ptr2 + 1, ptr4 = N - 1). Let's say the sum of these four values is currentSum = vec[ptr1][0] + vec[ptr2][0] + vec[ptr3][0] + vec[ptr4][0]. Now, we can have three cases:

We keep on moving ptr3 and ptr4 closer till ptr3 < ptr4. If we didn't get any valid quadruplet ptr1, ptr2, ptr3 and ptr4 such that vec[ptr1][0] + vec[ptr2][0] + vec[ptr3][0] + vec[ptr4][0] = X, it means that our assumption that vec[ptr1][0] is the first value and vec[ptr2][0] is the second value is wrong, so we will shift ptr2 to ptr2 + 1 and assume that vec[ptr2][0] is the second value. Again, start finding a valid quadruplet with sum = X. After ptr2 reaches then end, we shift ptr1 by 1 and again start with ptr2 = ptr1 + 1.

If after all the cases we don't get any answer, then it is impossible to have sum = X.

**Step-by-step algorithm:

Below is the implementation of the algorithm:

C++ `

#include <bits/stdc++.h> #define ll long long int

using namespace std;

// function to find a quadruplet whose sum = X void solve(vector& arr, ll X, ll N) { // vector to store the values along with their indices vector<vector> vec(N, vector(2));

for (int i = 0; i < N; i++) {
    vec[i][0] = arr[i];
    vec[i][1] = i + 1;
}

// Sort the vector in increasing order of the values
sort(vec.begin(), vec.end());

// Iterate for all possible values of first element
for (ll ptr1 = 0; ptr1 < N - 3; ptr1++) {

    // Iterate for all possible values of second element
    for (ll ptr2 = ptr1 + 1; ptr2 < N - 2; ptr2++) {

        // Maintain two pointers for the third and
        // fourth element
        ll ptr3 = ptr2 + 1;
        ll ptr4 = N - 1;
        while (ptr3 < ptr4) {
            ll currentSum = vec[ptr1][0] + vec[ptr2][0]
                            + vec[ptr3][0]
                            + vec[ptr4][0];

            // If current sum is equal to X, then we
            // have found a quadruplet whose sum = X
            if (currentSum == X) {
                cout << vec[ptr1][1] << " "
                     << vec[ptr2][1] << " "
                     << vec[ptr3][1] << " "
                     << vec[ptr4][1] << "\n";
                return;
            }

            // Decrease the currentSum by moving ptr4 to
            // ptr4 - 1
            else if (currentSum > X) {
                ptr4--;
            }

            // Increase the currentSum by moving ptr3 to
            // ptr3 + 1
            else if (currentSum < X) {
                ptr3++;
            }
        }
    }
}
// If no quadruplet has sum = X, print "IMPOSSIBLE"
cout << "IMPOSSIBLE";

}

int main() { // Sample Input ll N = 6, X = 20; vector arr = { 3, 4, 5, 6, 7, 8 };

solve(arr, X, N);
// your code goes here
return 0;

}

Java

import java.util.*;

public class Main { // Function to find a quadruplet whose sum = X static void GFG(ArrayList arr, long X, int N) { ArrayList<ArrayList> vec = new ArrayList<>(N); for (int i = 0; i < N; i++) { vec.add(new ArrayList<>(Arrays.asList(arr.get(i), (long) (i + 1)))); } // Sort the ArrayList in increasing order of the values Collections.sort(vec, Comparator.comparingLong(a -> a.get(0))); for (int ptr1 = 0; ptr1 < N - 3; ptr1++) { // Iterate for all possible values of the second element for (int ptr2 = ptr1 + 1; ptr2 < N - 2; ptr2++) { int ptr3 = ptr2 + 1; int ptr4 = N - 1; while (ptr3 < ptr4) { long currentSum = vec.get(ptr1).get(0) + vec.get(ptr2).get(0) + vec.get(ptr3).get(0) + vec.get(ptr4).get(0); // If current sum is equal to X // then we have found a quadruplet whose sum = X if (currentSum == X) { System.out.println(vec.get(ptr1).get(1) + " " + vec.get(ptr2).get(1) + " " + vec.get(ptr3).get(1) + " " + vec.get(ptr4).get(1)); return; } // Decrease the currentSum by moving the ptr4 to ptr4 - 1 else if (currentSum > X) { ptr4--; } else if (currentSum < X) { ptr3++; } } } } // If no quadruplet has sum = X // print "IMPOSSIBLE" System.out.println("IMPOSSIBLE"); } public static void main(String[] args) { // Sample Input int N = 6; long X = 20; ArrayList arr = new ArrayList<>(Arrays.asList(3L, 4L, 5L, 6L, 7L, 8L)); GFG(arr, X, N); } }

Python

function to find a quadruplet whose sum = X

def solve(arr, X, N): # list to store the values along with their indices vec = [[arr[i], i + 1] for i in range(N)]

# Sort the list in increasing order of the values
vec.sort()

# Iterate for all possible values of first element
for ptr1 in range(N - 3):
    # Iterate for all possible values of second element
    for ptr2 in range(ptr1 + 1, N - 2):
        # Maintain two pointers for the third and fourth element
        ptr3 = ptr2 + 1
        ptr4 = N - 1
        while ptr3 < ptr4:
            currentSum = vec[ptr1][0] + vec[ptr2][0] + vec[ptr3][0] + vec[ptr4][0]

            # If current sum is equal to X, then we have found a quadruplet whose sum = X
            if currentSum == X:
                print(vec[ptr1][1], vec[ptr2][1], vec[ptr3][1], vec[ptr4][1])
                return
            # Decrease the currentSum by moving ptr4 to ptr4 - 1
            elif currentSum > X:
                ptr4 -= 1
            # Increase the currentSum by moving ptr3 to ptr3 + 1
            elif currentSum < X:
                ptr3 += 1

# If no quadruplet has sum = X, print "IMPOSSIBLE"
print("IMPOSSIBLE")

Sample Input

N = 6 X = 20 arr = [3, 4, 5, 6, 7, 8]

solve(arr, X, N)

C#

using System;

class Program { public static void Solve(int[] arr, int X, int N) { // Array to store the values along with their indices var vec = new (int Value, int Index)[N]; for (int i = 0; i < N; i++) { vec[i] = (arr[i], i + 1); }

    // Sort the array in increasing order of the values
    Array.Sort(vec, (a, b) => a.Value.CompareTo(b.Value));

    // Iterate for all possible values of the first element
    for (int ptr1 = 0; ptr1 < N - 3; ptr1++)
    {
        // Iterate for all possible values of the second element
        for (int ptr2 = ptr1 + 1; ptr2 < N - 2; ptr2++)
        {
            // Maintain two pointers for the third and fourth element
            int ptr3 = ptr2 + 1;
            int ptr4 = N - 1;
            while (ptr3 < ptr4)
            {
                int currentSum = vec[ptr1].Value + vec[ptr2].Value + vec[ptr3].Value + vec[ptr4].Value;

                // If current sum is equal to X, then we have found a quadruplet whose sum = X
                if (currentSum == X)
                {
                    Console.WriteLine($"{vec[ptr1].Index} {vec[ptr2].Index} {vec[ptr3].Index} {vec[ptr4].Index}");
                    return;
                }
                // Decrease the currentSum by moving ptr4 to ptr4 - 1
                else if (currentSum > X)
                {
                    ptr4 -= 1;
                }
                // Increase the currentSum by moving ptr3 to ptr3 + 1
                else if (currentSum < X)
                {
                    ptr3 += 1;
                }
            }
        }
    }

    // If no quadruplet has sum = X, print "IMPOSSIBLE"
    Console.WriteLine("IMPOSSIBLE");
}

static void Main(string[] args)
{
    int N = 6;
    int X = 20;
    int[] arr = { 3, 4, 5, 6, 7, 8 };

    Solve(arr, X, N);
}

}

JavaScript

// function to find a quadruplet whose sum = X function solve(arr, X, N) { let vec = new Array(N).fill(0).map(() => new Array(2));

for (let i = 0; i < N; i++) {
    vec[i][0] = arr[i];
    vec[i][1] = i + 1;
}

// Sort the vector in increasing order of the values
vec.sort((a, b) => a[0] - b[0]);

// Iterate for all possible values of first element
for (let ptr1 = 0; ptr1 < N - 3; ptr1++) {
    // Iterate for all possible values of second element
    for (let ptr2 = ptr1 + 1; ptr2 < N - 2; ptr2++) {
        // Maintain two pointers for the third and fourth element
        let ptr3 = ptr2 + 1;
        let ptr4 = N - 1;
        while (ptr3 < ptr4) {
            let currentSum = vec[ptr1][0] + vec[ptr2][0] + vec[ptr3][0] + vec[ptr4][0];

            // If current sum is equal to X, then we have found a quadruplet whose sum = X
            if (currentSum === X) {
                console.log(vec[ptr1][1], vec[ptr2][1], vec[ptr3][1], vec[ptr4][1]);
                return;
            } else if (currentSum > X) {
                ptr4--;
            } else if (currentSum < X) {
                ptr3++;
            }
        }
    }
}
// If no quadruplet has sum = X, print "IMPOSSIBLE"
console.log("IMPOSSIBLE");

}

// Sample Input let N = 6, X = 20; let arr = [3, 4, 5, 6, 7, 8];

solve(arr, X, N);

`

**Time Complexity: O(N * N * N), where **N is the size of input array **arr[].
**Auxiliary Space: O(1)

Approach2 (Using Map)

Create a function. We use an unordered_map pairSums to store the sums of pairs of elements and their indices. Now we iterate over all pairs of elements in the input array and store their sums in the Hashmap. Then, we iterate over all pairs of sums in the Hashmap and check if the complement exists in the Hashmap. If it exist, and all the indices are distinct, we return the indices of the four values.

Steps by steps Implementation of above Approach

Below is Implementation of above approach

C++ `

// C++ program to implement Sum of Four Values (CSES) #include #include #include

using namespace std;

// Function to find four indices such that their values sum // to the target vector findFourSum(const vector& arr, int target) { // Map to store sums of pairs and their indices unordered_map<int, vector<pair<int, int> > > pairSums;

// Iterate over all pairs of elements and store their
// sums
for (int i = 0; i < arr.size(); ++i) {
    for (int j = i + 1; j < arr.size(); ++j) {
        // Calculate the sum of the current pair
        int sum = arr[i] + arr[j];
        // Store the indices of the pair with this sum
        pairSums[sum].push_back({ i, j });
    }
}

// Iterate over all pairs of sums and check for the
// complement
for (auto it1 = pairSums.begin(); it1 != pairSums.end();
     ++it1) {
    int sum1 = it1->first;
    const auto& pairs1 = it1->second;

    // Calculate the complement sum we are looking for
    int complement = target - sum1;

    // Check if the complement sum exists in the map
    if (pairSums.count(complement)) {
        const auto& pairs2 = pairSums[complement];

        // Check all pairs from the first sum with all
        // pairs from the complement sum
        for (const auto& pair1 : pairs1) {
            for (const auto& pair2 : pairs2) {
                // Ensure that all indices are distinct
                if (pair1.first != pair2.first
                    && pair1.first != pair2.second
                    && pair1.second != pair2.first
                    && pair1.second != pair2.second) {
                    // Return the indices of the four
                    // numbers
                    return { pair1.first, pair1.second,
                             pair2.first,
                             pair2.second };
                }
            }
        }
    }
}

// If no such combination exists, return an empty vector
return {};

}

int main() { // Sample array and target value vector arr = { 3, 4, 5, 6, 7, 8 }; int target = 20;

// Find the indices of four numbers that sum up to the
// target
vector<int> indices = findFourSum(arr, target);
if (!indices.empty()) {
    // Output the indices with 1-based indexing
    for (int index : indices) {
        cout << index + 1 << " ";
    }
    cout << endl;
}
else {
    // Inform the user that no combination was found
    cout << "No combination of four numbers found."
         << endl;
}

return 0;

}

Java

// Java program to implement Sum of Four Values (CSES) import java.util.*;

public class GFG {

// Function to find four indices such that their values
// sum to the target
public static List<Integer> findFourSum(int[] arr,
                                        int target)
{
    // Map to store sums of pairs and their indices
    Map<Integer, List<int[]> > pairSums
        = new HashMap<>();

    // Iterate over all pairs of elements and store
    // their sums
    for (int i = 0; i < arr.length; ++i) {
        for (int j = i + 1; j < arr.length; ++j) {
            // Calculate the sum of the current pair
            int sum = arr[i] + arr[j];
            // Store the indices of the pair with this
            // sum
            pairSums
                .computeIfAbsent(sum,
                                 k -> new ArrayList<>())
                .add(new int[] { i, j });
        }
    }

    // Iterate over all pairs of sums and check for the
    // complement
    for (Map.Entry<Integer, List<int[]> > entry1 :
         pairSums.entrySet()) {
        int sum1 = entry1.getKey();
        List<int[]> pairs1 = entry1.getValue();

        // Calculate the complement sum we are looking
        // for
        int complement = target - sum1;

        // Check if the complement sum exists in the map
        if (pairSums.containsKey(complement)) {
            List<int[]> pairs2
                = pairSums.get(complement);

            // Check all pairs from the first sum with
            // all pairs from the complement sum
            for (int[] pair1 : pairs1) {
                for (int[] pair2 : pairs2) {
                    // Ensure that all indices are
                    // distinct
                    if (pair1[0] != pair2[0]
                        && pair1[0] != pair2[1]
                        && pair1[1] != pair2[0]
                        && pair1[1] != pair2[1]) {
                        // Return the indices of the
                        // four numbers
                        return Arrays.asList(
                            pair1[0], pair1[1],
                            pair2[0], pair2[1]);
                    }
                }
            }
        }
    }

    // If no such combination exists, return an empty
    // list
    return new ArrayList<>();
}

public static void main(String[] args)
{
    // Sample array and target value
    int[] arr = { 3, 4, 5, 6, 7, 8 };
    int target = 20;

    // Find the indices of four numbers that sum up to
    // the target
    List<Integer> indices = findFourSum(arr, target);
    if (!indices.isEmpty()) {
        // Output the indices with 1-based indexing
        for (int index : indices) {
            System.out.print((index + 1) + " ");
        }
        System.out.println();
    }
    else {
        // Inform the user that no combination was found
        System.out.println(
            "No combination of four numbers found.");
    }
}

}

Python

#Python program to implement Sum of Four Values (CSES) from typing import List, Tuple

Function to find four indices such that their values sum

to the target

def find_four_sum(arr: List[int], target: int) -> List[int]: # Dictionary to store sums of pairs and their indices pair_sums = {}

# Iterate over all pairs of elements and store their sums
for i in range(len(arr)):
    for j in range(i + 1, len(arr)):
        # Calculate the sum of the current pair
        sum_ = arr[i] + arr[j]
        # Store the indices of the pair with this sum
        if sum_ not in pair_sums:
            pair_sums[sum_] = []
        pair_sums[sum_].append((i, j))

# Iterate over all pairs of sums and check for the complement
for sum1, pairs1 in pair_sums.items():
    # Calculate the complement sum we are looking for
    complement = target - sum1

    # Check if the complement sum exists in the dictionary
    if complement in pair_sums:
        pairs2 = pair_sums[complement]

        # Check all pairs from the first sum with all pairs from the complement sum
        for pair1 in pairs1:
            for pair2 in pairs2:
                # Ensure that all indices are distinct
                if (pair1[0] != pair2[0]
                        and pair1[0] != pair2[1]
                        and pair1[1] != pair2[0]
                        and pair1[1] != pair2[1]):
                    # Return the indices of the four numbers
                    return [pair1[0], pair1[1], pair2[0], pair2[1]]

# If no such combination exists, return an empty list
return []

def main(): # Sample array and target value arr = [3, 4, 5, 6, 7, 8] target = 20

# Find the indices of four numbers that sum up to the target
indices = find_four_sum(arr, target)
if indices:
    # Output the indices with 1-based indexing
    for index in indices:
        print(index + 1, end=" ")
    print()
else:
    # Inform the user that no combination was found
    print("No combination of four numbers found.")

if name == "main": main()

C#

// C# program to implement Sum of Four Values (CSES) using System; using System.Collections.Generic;

class Program { // Function to find four indices such that their values // sum to the target static List FindFourSum(int[] arr, int target) { // Dictionary to store sums of pairs and their // indices var pairSums = new Dictionary<int, List<Tuple<int, int> > >();

    // Iterate over all pairs of elements and store
    // their sums
    for (int i = 0; i < arr.Length; ++i) {
        for (int j = i + 1; j < arr.Length; ++j) {
            // Calculate the sum of the current pair
            int sum = arr[i] + arr[j];
            // Store the indices of the pair with this
            // sum
            if (!pairSums.ContainsKey(sum)) {
                pairSums[sum]
                    = new List<Tuple<int, int> >();
            }
            pairSums[sum].Add(Tuple.Create(i, j));
        }
    }

    // Iterate over all pairs of sums and check for the
    // complement
    foreach(var kvp1 in pairSums)
    {
        int sum1 = kvp1.Key;
        var pairs1 = kvp1.Value;

        // Calculate the complement sum we are looking
        // for
        int complement = target - sum1;

        // Check if the complement sum exists in the
        // dictionary
        if (pairSums.ContainsKey(complement)) {
            var pairs2 = pairSums[complement];

            // Check all pairs from the first sum with
            // all pairs from the complement sum
            foreach(var pair1 in pairs1)
            {
                foreach(var pair2 in pairs2)
                {
                    // Ensure that all indices are
                    // distinct
                    if (pair1.Item1 != pair2.Item1
                        && pair1.Item1 != pair2.Item2
                        && pair1.Item2 != pair2.Item1
                        && pair1.Item2 != pair2.Item2) {
                        // Return the indices of the
                        // four numbers
                        return new List<int>{
                            pair1.Item1, pair1.Item2,
                            pair2.Item1, pair2.Item2
                        };
                    }
                }
            }
        }
    }

    // If no such combination exists, return an empty
    // list
    return new List<int>();
}

static void Main()
{
    // Sample array and target value
    int[] arr = { 3, 4, 5, 6, 7, 8};
    int target = 20;

    // Find the indices of four numbers that sum up to
    // the target
    List<int> indices = FindFourSum(arr, target);
    if (indices.Count > 0) {
        // Output the indices with 1-based indexing
        foreach(int index in indices)
        {
            Console.Write((index + 1) + " ");
        }
        Console.WriteLine();
    }
    else {
        // Inform the user that no combination was found
        Console.WriteLine(
            "No combination of four numbers found.");
    }
}

}

JavaScript

// javascript program to implement Sum of Four Values (CSES) // Function to find four indices such that their values sum // to the target function findFourSum(arr, target) { // Map to store sums of pairs and their indices const pairSums = new Map();

// Iterate over all pairs of elements and store their
// sums
for (let i = 0; i < arr.length; ++i) {
    for (let j = i + 1; j < arr.length; ++j) {
        // Calculate the sum of the current pair
        const sum = arr[i] + arr[j];
        // Store the indices of the pair with this sum
        if (!pairSums.has(sum)) {
            pairSums.set(sum, []);
        }
        pairSums.get(sum).push([ i, j ]);
    }
}

// Iterate over all pairs of sums and check for the
// complement
for (const [sum1, pairs1] of pairSums.entries()) {
    // Calculate the complement sum we are looking for
    const complement = target - sum1;

    // Check if the complement sum exists in the map
    if (pairSums.has(complement)) {
        const pairs2 = pairSums.get(complement);

        // Check all pairs from the first sum with all
        // pairs from the complement sum
        for (const pair1 of pairs1) {
            for (const pair2 of pairs2) {
                // Ensure that all indices are distinct
                if (pair1[0] !== pair2[0]
                    && pair1[0] !== pair2[1]
                    && pair1[1] !== pair2[0]
                    && pair1[1] !== pair2[1]) {
                    // Return the indices of the four
                    // numbers
                    return [
                        pair1[0], pair1[1], pair2[0],
                        pair2[1]
                    ];
                }
            }
        }
    }
}

// If no such combination exists, return an empty array
return [];

}

// Main function function main() { // Sample array and target value const arr = [ 3, 4, 5, 6, 7, 8 ]; const target = 20;

// Find the indices of four numbers that sum up to the
// target
const indices = findFourSum(arr, target);
if (indices.length > 0) {
    // Output the indices with 1-based indexing
    console.log(
        indices.map(index => index + 1).join(" "));
}
else {
    // Inform the user that no combination was found
    console.log(
        "No combination of four numbers found.");
}

}

// Run the main function main();

`

**Time Complexity: O(n^2)
**Auxiliary Space: O(n^2)