Program to check we can find four elements whose sum is same as k or not in Python

Suppose we have a list of numbers called nums and a value k, we have to check whether there are four unique elements in the list that add up to k.

So, if the input is like nums = [11, 4, 6, 10, 5, 1] and k = 25, then the output will be True, as we have [4, 6, 10, 5] whose sum is 25.

Algorithm

To solve this, we will follow these steps ?

  • Sort the list nums

  • n := size of nums

  • For i in range 0 to n ? 4, do

    • For j in range i + 1 to n ? 3, do

      • l := j + 1, h := size of nums ? 1

      • While l < h, do

        • summ := nums[i] + nums[j] + nums[l] + nums[h]

        • If summ is same as k, then return True

        • Otherwise when summ < k, then l := l + 1

        • Otherwise, h := h ? 1

  • Return False

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, nums, k):
        nums.sort()
        n = len(nums)
        for i in range(n - 3):
            for j in range(i + 1, n - 2):
                l, h = j + 1, len(nums) - 1
                while l < h:
                    summ = nums[i] + nums[j] + nums[l] + nums[h]
                    if summ == k:
                        return True
                    elif summ < k:
                        l += 1
                    else:
                        h -= 1
        return False

ob1 = Solution()
nums = [11, 4, 6, 10, 5, 1]
k = 25
print(ob1.solve(nums, k))
True

How It Works

The algorithm uses a two?pointer technique combined with nested loops:

  • First, we sort the array to enable the two?pointer approach

  • We fix the first two elements using nested loops (i and j)

  • For the remaining two elements, we use two pointers (l and h) from both ends

  • If the sum equals k, we found our answer. If sum is less than k, we move the left pointer right. If sum is greater than k, we move the right pointer left

Alternative Approach Using Combinations

We can also solve this using Python's itertools.combinations ?

from itertools import combinations

def find_four_sum(nums, k):
    for combo in combinations(nums, 4):
        if sum(combo) == k:
            return True
    return False

nums = [11, 4, 6, 10, 5, 1]
k = 25
print(find_four_sum(nums, k))
print("Found combination:", [combo for combo in combinations(nums, 4) if sum(combo) == k][0])
True
Found combination: (11, 4, 10, 1)

Conclusion

The two?pointer approach has O(n³) time complexity and is more efficient than brute force. The combinations approach is simpler to understand but has O(n?) time complexity for checking all possible combinations.

Updated on: 2026-03-25T11:40:21+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements