Problem statement

https://binarysearch.com/problems/Sum-of-Four-Numbers/

Solution

Variation of Leetcode 454. 4Sum II, but no need to return all sums, and we can have O(n^2) time complexity

Complexity

It is O(n^2) for time and space.

Code

class Solution:
    def solve(self, nums, k):
        n, d = len(nums), {}
        for i in range(n - 1):
            for j in range(i + 1, n):
                d[nums[i] + nums[j]] = [i, j]

        for i in range(n - 1):
            for j in range(i + 1, n):
                summ = nums[i] + nums[j]
                if (k - summ) in d:
                    p = d[k - summ]
                    if p[0] != i and p[0] != j and p[1] != i and p[1] != j:
                        return True
        return False