#K33517. Find Pair with Target Sum in a Sorted Array
Find Pair with Target Sum in a Sorted Array
Find Pair with Target Sum in a Sorted Array
You are given a sorted array of unique integers and a target sum. Your task is to find a pair of numbers \(a\) and \(b\) in the array such that \(a + b = target\). If such a pair exists, output the pair in the order they appear when scanning from left to right; otherwise, output None
.
The array is sorted in increasing order, which allows a two-pointer approach to be used effectively. The algorithm can be described as follows:
1. Initialize two pointers: one at the beginning (left) and one at the end (right) of the array.
2. While the left pointer is less than the right pointer, check the sum \(S = arr[left] + arr[right]\).
- If \(S = target\), output the pair \(arr[left]\) and \(arr[right]\) and terminate.
- If \(S < target\), move the left pointer to the right (i.e., increment \(left\)).
- If \(S > target\), move the right pointer to the left (i.e., decrement \(right\)).
3. If no pair is found, output None
.
Note: All formulas are in \(\LaTeX\) format, for instance: \(a+b=target\).
inputFormat
The input is read from standard input (stdin) with the following format:
- The first line contains a single integer \(n\) representing the number of elements in the array.
- The second line contains \(n\) space-separated integers representing the sorted array.
- The third line contains an integer representing the target sum.
outputFormat
Output to standard output (stdout) should be a single line containing the two integers separated by a space if a valid pair exists. If no such pair exists, output None
.
5
1 2 3 4 6
5
1 4
</p>