Python - K Summation from Two lists


List is an important data type in Python that can hold sequence of either homogeneous or heterogeneous data types. They are mutable. Finding the k summation from two lists means we need to find the combinations of the elements of two lists, which can add up to make the sum exactly equal to k. In this article, we will first explore the brute force method. Next, we would look into several optimized algorithms like two pointer approach, hashing algorithms, list comprehensions, etc.

Using The Brute Force Method

Brute force is the simplest approach. We write the logic without considering optimizing the code in this method. To find k summation, we can use two looping statements to iterate over the lists and check the sum of the elements. If the sum equals k, we can append the elements to any data structure, say a list.

Example

In the following code, we have used the brute force algorithm. Under the function k_sum_naive, we have initialized an empty list. Next, we used the for loop to iterate over the two lists, and under each iteration, we checked if the sum of the two elements equals k. If it equals k, we have appended the elements to the initialized list as tuple elements.

def k_sum_naive(list1, list2, k):
    result = []
    for num1 in list1:
        for num2 in list2:
            if num1 + num2 == k:
                result.append((num1, num2))
    return result
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
k = 10
print(f'The first list is: {list1}')
print(f'The second list is: {list2}')
print(f'The required list is: {k_sum_naive(list1, list2, k)}')

Output

The first list is: [1, 2, 3, 4, 5]
The second list is: [6, 7, 8, 9, 10]
The required list is: [(1, 9), (2, 8), (3, 7), (4, 6)]
  • Time Complexity: O(n^2)

  • Space Complexity: O(1)

Using Two−Pointer Approach

The Two−Pointer Approach is a popular algorithmic technique for efficiently solving various problems. It involves using two pointers, often called the "left" and "right" pointers, that traverse an array or a list simultaneously from different directions or speeds. This approach is particularly useful when dealing with problems that require finding a pair or a subarray that satisfies certain conditions. This approach is useful in many popular problems like detecting cycles in a graph, sliding window problems, sorting linked lists, etc.

Example

In the following example, we used k_sum_two_pointer to return the k summation from two lists. Under the function, we used the 'sort' method of Python to sort the lists. Next, we have defined two pointers named ptr1 and ptr2, respectively. We iterated over the lists and appended those elements, which sum up to k to the initialized list.

def k_sum_two_pointer(list1, list2, k):
    list1.sort()
    list2.sort()
    result = []
    ptr1, ptr2 = 0, len(list2) - 1
    while ptr1 < len(list1) and ptr2 >= 0:
        sum = list1[ptr1] + list2[ptr2]
        if sum == k:
            result.append((list1[ptr1], list2[ptr2]))
            ptr1 += 1
            ptr2 -= 1
        elif sum < k:
            ptr1 += 1
        else:
            ptr2 -= 1
    return result

list1 = [1, 2, 3, 4, 5]
list2 = [12, 7, 8, 9, 10]
k = 13
print(f'The first list is: {list1}')
print(f'The second list is: {list2}')
print(f'The required list is: {k_sum_two_pointer(list1, list2, k)}')

Output

The first list is: [1, 2, 3, 4, 5]
The second list is: [12, 7, 8, 9, 10]
The required list is: [(1, 12), (3, 10), (4, 9), (5, 8)]
  • Time Complexity: O(n log n) (due to sorting)

  • Space Complexity: O(1)

Using Hashing Method

The hashing method is commonly used in computer science and programming to store, retrieve, and manipulate data efficiently. It involves mapping data elements to unique identifiers called hash values or codes using a hash function. For getting k summation from a list, we can adopt the following algorithm:

  • We can maintain a hash table to insert all the numbers from any list.

  • Next, we can iterate over the other list, and under each iteration, we can find the k−element where the element is the element of the second list.

  • Now, we can use the hash table to find if the value (k−element) exists in the first list. If it exists, then the summation of the numbers would be equal to k, and hence we get our answer!

Example

In the following code, we have created the function k_sum_hashing, which uses the lists and the value k as the parameters. We initialized a dictionary called hash_table and a list called result. Next, we iterated over the first list and used hashing to map the boolean True to the existing elements. Now we iterated over the second list, and under each iteration, we found the value of (k−num2) where num2 are the elements of the second list. Using the hash table, we checked if the value exists in the first list, and if it is so, we appended the numbers to the initialized list.

def k_sum_hashing(list1, list2, k):
    hash_table = {}
    result = []
    for num1 in list1:
        hash_table[num1] = True
    for num2 in list2:
        complement = k - num2
        if complement in hash_table:
            result.append((complement, num2))
    return result

list1 = [1, 2, 3, 4, 5]
list2 = [12, 7, 8, 9, 10]
k = 13
print(f'The first list is: {list1}')
print(f'The second list is: {list2}')
print(f'The required list is: {k_sum_hashing(list1, list2, k)}')

Output

The first list is: [1, 2, 3, 4, 5]
The second list is: [12, 7, 8, 9, 10]
The required list is: [(1, 12), (5, 8), (4, 9), (3, 10)]
  • Time Complexity: O(n)

  • Space Complexity: O(n)

Using List Comprehension

List comprehension is a popular method in Python to create list elements. The advantage of using list comprehension is that we can easily combine multiple conditional statements, loops, etc., in a single line. However, we cannot write too many complex conditions in the list comprehension technique.

Example

In the following code, we used the list comprehension to create pairs whose sum adds to k. We created the function k_sum_list_comprehension, which takes the lists and the value k as the parameters. Under this function, we used list comprehension to check if the sum of the pairs of elements from the list adds up to k. If true, we appended the pairs to the list and returned it.

def k_sum_list_comprehension(list1, list2, k):
    return [(num1, num2) for num1 in list1 for num2 in list2 if num1 + num2 == k]

list1 = [1, 2, 3, 4, 5]
list2 = [8,5,7,4]
k = 9
print(f'The first list is: {list1}')
print(f'The second list is: {list2}')
print(f'The required list is: {k_sum_list_comprehension(list1, list2, k)}')

Output

The first list is: [1, 2, 3, 4, 5]
The second list is: [8, 5, 7, 4]
The required list is: [(1, 8), (2, 7), (4, 5), (5, 4)]
  • Time Complexity: O(n^2)

  • Space Complexity: O(1)

Using Iterrools Library

The itertools library in Python provides a powerful way to iterate over the iterable objects. It offers a wide range of tools to handle common programming tasks involving iterators, such as generating combinations, permutations, and Cartesian products. This is a part of the standard library of Python. We can utilize the itertools library to generate the combinations of the elements of the lists and use a custom logic to check if the combinations give the summation equal to k.

Example

In the following code, first, we imported the itertools library of Python. Under the function k_suum_product, we used the ‘product’ method of itertools to generate the combinations of elements from the lists. Next, we used list comprehension to check if the summation of the elements of each combination gives k. We have appended the pairs to the' pairs' list if it is True.

import itertools
def k_sum_product(list1, list2, k):
    pairs = list(itertools.product(list1, list2))
    return [(num1, num2) for (num1, num2) in pairs if num1 + num2 == k]
list1 = [1, 2, 3, 4, 5]
list2 = [8,5,7,4]
k = 9
print(f'The first list is: {list1}')
print(f'The second list is: {list2}')
print(f'The required list is: {k_sum_product(list1, list2, k)}')

Output

The first list is: [1, 2, 3, 4, 5]
The second list is: [8, 5, 7, 4]
The required list is: [(1, 8), (2, 7), (4, 5), (5, 4)]
  • Time Complexity: O(n^2)

  • Space Complexity: O(n^2)

Conclusion

In this article, we understood how to deal with k summation from two lists in Python. We can build our custom code and use the libraries available in Python. Python, by default, does not have any library to perform this function but provides us methods to perform many standard operations, which we can utilize to solve the problem. At the same time, brute force, using the Lamda function, etc., are easier to understand. They need to be better−optimized logic. Hence it is better to use hashing, two pointers,s, etc., to solve the problem.

Updated on: 18-Jul-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements