Introduction
The Pair Sum in Sorted Array problem involves checking whether there exists a pair of elements whose sum equals a given target value.
Given a sorted array arr[] and an integer target, the task is to determine whether any pair exists such that:
arr[i] + arr[j] = targetThis problem helps in understanding:
- Two Pointer Technique
- sorted array optimization
- pair searching
- efficient traversal logic
Example
Input: arr[] = [1,2,4,6,10]target = 8
Output: true Explanation: 2 + 6 = 8 Therefore, valid pair exists.
Input: arr[] = [1,3,5,7]
target = 12
Output: true Explanation: 5 + 7 = 12
Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9
-10^9 <= target <= 10^9
Array is sorted
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate all possible pairs
- Calculate their sum
- Check whether the sum equals target
This approach is easy to understand but checking all pairs increases time complexity.
Steps
- Traverse the array using index i.
- For every index:
- traverse remaining elements using j
- Calculate pair sum.
- If sum equals target:
- return true
- Otherwise:
- continue traversal
Dry Run
Input Array: [1,2,4,6,10]target = 8Check 1 + 2:
Sum = 3 Not equal to target Check 1 + 4: Sum = 5 Check 2 + 6: Sum = 8 Target found Return true
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
Every possible pair is checked.
Space Complexity: O(1) Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Two Pointer Technique)
Explanation
Since the array is already sorted, we can use the Two Pointer Technique.
The idea is:
- Place:
- left pointer at beginning
- right pointer at end
- Calculate current sum.
- If:
- sum == target:
- pair found
- sum < target:
- move left pointer
- sum > target:
- move right pointer
- sum == target:
This avoids unnecessary pair generation.
Steps
- Initialize:
- left = 0
- right = n - 1
- While left < right:
- calculate current sum
- If sum equals target:
- return true
- If sum smaller than target:
- move left pointer
- If sum greater than target:
- move right pointer
- If traversal ends:
- return false
Dry Run
Input Array: [1,2,4,6,10]target = 8
Initially: left = 0 → 1
right = 4 → 10
Current Sum: 1 + 10 = 11 11 > 8 Move right pointer right = 3 → 6
Current Sum: 1 + 6 = 7
7 < 8 Move left pointer left = 1 → 2
Current Sum: 2 + 6 = 8 Target found Return true
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each pointer moves at most once.
Space Complexity: O(1) Explanation:
No extra data structures are used.