January 18, 2025 |26.7K Views

Pair Sum in a Sorted and Rotated Array

Explore Courseexplore course icon
Description
Discussion

To find if a pair of elements in a sorted and rotated array sums up to a given target, a hashing-based approach can be used for O(n) time and space complexity. By iterating through the array, a set is used to store elements, and for each element, its complement with respect to the target is checked. If the complement exists in the set, the pair is found. Otherwise, the element is added to the set. This approach provides simplicity but requires additional space for the hash set.

A more efficient approach is the two-pointer technique, which operates in O(n) time and O(1) space. First, the pivot (largest element) and the smallest element in the rotated array are identified. Pointers are initialized at the smallest and largest elements. The sum of the elements at these pointers is compared with the target, and the pointers are adjusted accordingly using modulo operations to handle the circular nature of the array. If the pair is found, the function returns true; otherwise, it returns false after the iteration completes.

For more details, please go through - Pair Sum in a Sorted and Rotated Array