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

Suppose we have a sorted array of numbers and another number k. We need to check whether the given array can be divided into pairs such that the sum of every pair equals k.

So, if the input is like arr = [1, 2, 3, 4, 5, 6] and k = 7, then the output will be True as we can form pairs like (1, 6), (2, 5) and (3, 4).

Algorithm

To solve this, we will follow these steps −

  • Get the size of the array
  • If the array size is odd, return False (cannot form pairs)
  • Use two pointers: low at start and high at end
  • While low < high:
    • If arr[low] + arr[high] != k, return False
    • Move low forward and high backward
  • Return True if all pairs sum to k

Example

def solve(arr, k):
    n = len(arr)
    
    # If odd number of elements, cannot form pairs
    if n % 2 == 1:
        return False
    
    # Two pointers approach
    low = 0
    high = n - 1
    
    while low < high:
        if arr[low] + arr[high] != k:
            return False
        low += 1
        high -= 1
    
    return True

# Test the function
arr = [1, 2, 3, 4, 5, 6]
k = 7
print(solve(arr, k))
True

How It Works

The algorithm works because the array is sorted. For any valid pairing with sum k, the smallest element must pair with the largest element, the second smallest with the second largest, and so on. This two-pointer approach efficiently checks all possible pairs in O(n) time.

Additional Example

# Example where pairing is not possible
arr2 = [1, 3, 5, 7]
k2 = 8
print(f"Array: {arr2}, k: {k2}")
print(f"Can form pairs: {solve(arr2, k2)}")

print()

# Another valid example
arr3 = [2, 4, 6, 8]
k3 = 10
print(f"Array: {arr3}, k: {k3}")
print(f"Can form pairs: {solve(arr3, k3)}")
Array: [1, 3, 5, 7], k: 8
Can form pairs: True

Array: [2, 4, 6, 8], k: 10
Can form pairs: True

Conclusion

This two-pointer technique efficiently checks if a sorted array can be divided into pairs with sum k. The key insight is that in a sorted array, valid pairs must be formed between elements at opposite ends.

Updated on: 2026-03-25T14:08:08+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements