K Sum Problem

K sum problems are the sort of problems that asking you to find the k numbers whose sum is the target when given a number array or list. On LeetCode, there are two sum and three sum problems. Today, I am gonna discuss such kind of problems. 

Two sum

Given nums = [2, 7, 11, 15],

target = 9,

Because num[0] + nums[1] = 2 + 7 = 9,

return [0, 1].


Easily, we can think of two simple and direct solutions. One is to try all possible combinations. Another one is to use two pointers beginning at the head and the tail of the sorted list to traverse the list in a O(n)  time. 

Obviously, nobody wants the first solution happens. So let us focus on the second one. 

You may write code in this way. 

Unfortunately, you will find you got WA on LeetCode. The reason is this problem ask you to return the index of the numbers in the original array. So you may find another method so as to get rid of using sorting. That should be  .

Actually,   in Python is a O(n) time complexity operation. Though this code works, it may not be the best one. Other thoughts can be considering save the original list or use dict as a hash map, which can be regarded as a tradeoff between time-consuming and space-consuming to keep the time complexity as O(n2) . 

Three Sum

With one more element enrolled, what we can do here is to traverse all elements, and then find the other two elements with a similar method in problem two sum. 

The time complexity is O(n2) .

Actually we can still use hash map here to ensure the complexity as O(n2).

Four Sum

Similar to the problem three sum, we can fix two elements and find the other two elements with the method we use in two sum. In this way, the time complexity is O(n3) .

Is there any more optimal ways? Hashmap. 

  1. define a hashmap whose key=a+b and value=(a, b)
  2. use two   to traverse all c and d. 

The time complexity is O(n2logn).

Google Adv. below


2 Replies to “K Sum Problem”

Leave a Reply