Program to check we can find three unique elements ose sum is same as k or not Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and another value k, we have to check whether we can find three unique elements in the list whose sum is k.

So, if the input is like nums = [11, 4, 6, 10, 5, 1] k = 20, then the output will be True, as we have numbers [4,6,10] whose sum is 20.

To solve this, we will follow these steps −

  • sort the list nums

  • l := 0, r := size of nums − 1

  • while l < r − 1, do

    • t := k − nums[l] − nums[r]

    • if nums[r − 1] < t, then

      • l := l + 1

      • come out from the loop

    • for m in range l + 1 to r, do

      • if nums[m] > t, then

        • r := r − 1

        • come out from the loop

      • if nums[m] is same as t, then

        • return True

  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, k):
      nums.sort()
      l, r = 0, len(nums) − 1
      while l < r − 1:
         t = k − nums[l] − nums[r]
         if nums[r − 1] < t:
            l += 1
            continue
         for m in range(l + 1, r):
            if nums[m] > t:
               r −= 1
               break
            if nums[m] == t:
               return True
      return False
ob1 = Solution()
nums = [11, 4, 6, 10, 5, 1]
k = 20
print(ob1.solve(nums, k))

Input

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

Output

True
raja
Published on 21-Oct-2020 11:38:01
Advertisements