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

PythonServer Side ProgrammingProgramming

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] k = 25, then the output will be True, as we have [4, 6, 10, 5] whose sum is 25.

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

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[11, 4, 6, 10, 5, 1], 25

Output

True
raja
Published on 21-Oct-2020 11:30:24
Advertisements