- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check we can find three unique elements ose sum is same as k or not Python
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
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
- Related Articles
- Program to check we can find four elements whose sum is same as k or not in Python
- Program to find three unique elements from list whose sum is closest to k 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
- 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 unique elements in Python
- Python program to check whether we can pile up cubes or not
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to check occurrences of every value is unique or not in Python
- Program to check whether we can make group of two partitions with equal sum or not in Python?
- Program to check sum of two numbers is up to k from sorted List or not 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

Advertisements