
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Check if an array can be divided into pairs whose sum is divisible by k in Python
- Count pairs in a sorted array whose product is less than k in C++
- Check if array can be sorted with one swap in Python
- Count pairs in a sorted array whose sum is less than x in C++
- Check if array sum can be made K by three operations on it in Python
- Count pairs in array whose sum is divisible by K in C++
- Program to check whether list can be partitioned into pairs where sum is multiple of k in python
- Check if an array of 1s and 2s can be divided into 2 parts with equal sum in Python
- Check if the array can be sorted using swaps between given indices only in Python
- Check if array can be divided into two sub-arrays such that their absolute difference is Ks in Python
- Check if an array is sorted and rotated in Python
- Find if array can be divided into two subarrays of equal sum in C++
- Check If a Number Is Majority Element in a Sorted Array in Python
- Check if a queue can be sorted into another queue using a stack in Python
- Check if reversing a sub array make the array sorted in Python

Advertisements