- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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

- Related Questions & Answers
- Program to check we can find three unique elements ose sum is same as k or not Python
- Program to check n can be shown as sum of k or not in Python
- Program to check n can be represented as sum of k primes or not in Python
- C++ program to find range whose sum is same as n
- 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 check whether we can convert string in K moves or not using Python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to find sum of rectangle whose sum at most k in Python
- Program to check we can reach leftmost or rightmost position or not in Python
- Python program to find list of triplets for which i+j+k is not same as n
- Python program to check whether we can pile up cubes or not
- Program to find minimum number of subsequence whose concatenation is same as target 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

Advertisements