easyTwo PointersPattern: Two Pointers

Pairwise Sum Equality Solution

Problem Statement

Given an array of integers and a target sum, determine if there exist two elements in the array that add up to the target sum.

Examples

Example 1:
Input:[1, 2, 3, 4, 5], 7
Output:True
Explanation: The elements at indices 2 and 4 add up to the target sum of 7 (3 + 4 = 7).
Example 2:
Input:[10, 20, 30], 5
Output:False
Explanation: No two elements in the array add up to the target sum of 5.

Constraints

  • Array size is at most 10^4
  • Target sum is a positive integer
  • Array elements are distinct integers
  • All elements in the array are non-negative
Time: O(n log n) Space: O(1)
The optimal approach is to sort the array and then use two pointers, one starting from the beginning and one from the end of the array, to find a pair of elements that add up to the target sum in linear time.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.