
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Check for Three Unique Elements with Sum Equal to K in 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
Advertisements