
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 If a Sorted Array Can Be Divided in Pairs Whose Sum is K in Python
Suppose we have an array of numbers and have another number k, we have to check whether given array can be divided into pairs such that the sum of every pair is k or not.
So, if the input is like arr = [1, 2, 3, 4, 5, 6], k = 7, then the output will be True as we can take pairs like (2, 5), (1, 6) and (3, 4).
To solve this, we will follow these steps −
- n := size of arr
- if n is odd, then
- return False
- low := 0, high := n - 1
- while low < high, do
- if arr[low] + arr[high] is not same as k, then
- return False
- low := low + 1
- high := high - 1
- if arr[low] + arr[high] is not same as k, then
- return True
Let us see the following implementation to get better understanding −
Example
def solve(arr, k): n = len(arr) if n % 2 == 1: return False low = 0 high = n - 1 while low < high: if arr[low] + arr[high] != k: return False low = low + 1 high = high - 1 return True arr = [1, 2, 3, 4, 5, 6] k = 7 print(solve(arr, k))
Input
[1, 2, 3, 4, 5, 6], 7
Output
True
Advertisements