Is there a way to solve the 4Sum problem in better than O(n^3) time?

Viewed 962

Problem: Given an array of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

So there's the obvious n^3 solution with sorting, two nested for loops and then checking.

But is there a way to do better? Note this isn't the decision problem, just see if a solution exists but instead to return all unique quadruplets.

1 Answers

No, its not possible to find all unique quadruplets in more efficient way than O(n^3) time complexity. But if you want to only count the number of quadruples instead of listing, this can be possible in O(n^2) time complexity.

Related