- Related Questions & Answers
- Program to check we can find three unique elements ose sum is same as k or not Python
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to find three unique elements from list whose sum is closest to k Python
- Program to find sum of rectangle whose sum at most k in Python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Program to check number of triplets from an array whose sum is less than target or not Python
- Program to find an element in list whose value is same as its frequency in Python
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check we can cross river by stones or not in Python
- Program to count number of paths whose sum is k in python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Check if a sorted array can be divided in pairs whose sum is k in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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

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

True

Advertisements