Check if a sorted array can be divided in pairs whose sum is k in Python

PythonServer Side ProgrammingProgramming

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
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

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
raja
Published on 29-Dec-2020 17:33:30
Advertisements