easy Pair with Target Sum
Problem Statement
Given an array of numbers sorted in ascending order and a target sum, find a pair in the array whose sum is equal to the given target.
Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target. If no such pair exists return [-1, -1].
Example 1:
Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6
Example 2:
Input: [2, 5, 9, 11], target=11
Output: [0, 2]
Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11
Constraints:
- 2 <= arr.length <= 104
- -109 <= arr[i] <= 109
- -109 <= target <= 109
- Only
onevalid answer exists.
Try it yourself
Try solving this question here:
✅ Solution Pair with Target Sum
Problem Statement
Given an array of numbers sorted in ascending order and a target sum, find a pair in the array whose sum is equal to the given target. If no such pair exists return [-1, -1].
Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target.
Example 1:
Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6
Example 2:
Input: [2, 5, 9, 11], target=11
Output: [0, 2]
Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11
Constraints:
- 2 <= arr.length <= 104
- -109 <= arr[i] <= 109
- -109 <= target <= 109
Solution
Since the given array is sorted, a brute-force solution could be to iterate through the array, taking one number at a time and searching for the second number through Binary Search. The time complexity of this algorithm will be
To solve this problem, we can use a two-pointer approach. This approach is efficient because it takes advantage of the sorted nature of the array. By starting with one pointer at the beginning and the other at the end, we can adjust their positions based on the sum of the elements they point to. This allows us to find the pair that adds up to the target without needing to check all possible pairs, which saves time.
By moving the pointers inward, we can systematically find the pair in a single pass through the array. This ensures that the solution is both time-efficient and easy to implement.
Step-by-Step Algorithm
- Initialize two pointers: Start with one pointer (
left) at the beginning (index 0) and the other pointer (right) at the end (last index) of the array. - Loop until pointers meet: Continue the loop until
leftis less thanright.- Calculate current sum: Add the elements at the
leftandrightpointers. - Check if the sum matches the target:
- If
currentSumequals the target sum, return the indices[left, right]. - If
currentSumis less than the target sum, increment theleftpointer to increase the sum. - If
currentSumis more than the target sum, decrement therightpointer to decrease the sum.
- If
- Calculate current sum: Add the elements at the
- Return default values: If no pair is found, return
[-1, -1].
Algorithm Walkthrough
Let's walk through the example with input [1, 2, 3, 4, 6] and target 6.
- Initialize pointers:
left = 0,right = 4 - First iteration:
currentSum = 1 + 6 = 7(greater than target)- Decrement
rightto3
- Second iteration:
currentSum = 1 + 4 = 5(less than target)- Increment
leftto1
- Third iteration:
currentSum = 2 + 4 = 6(equals target)- Return indices
[1, 3]
Here is the visual representation of this algorithm for Example-1:

Code
Here is what our algorithm will look like:
class Solution {
public int[] search(int[] arr, int targetSum) {
int left = 0, right = arr.length - 1;
while (left < right) {
int currentSum = arr[left] + arr[right];
if (currentSum == targetSum) return new int[] { left, right }; // found the pair
if (targetSum > currentSum) left++; // we need a pair with a bigger sum
else right--; // we need a pair with a smaller sum
}
return new int[] { -1, -1 };
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] result = sol.search(new int[] { 1, 2, 3, 4, 6 }, 6);
System.out.println(
"Pair with target sum: [" + result[0] + ", " + result[1] + "]"
);
result = sol.search(new int[] { 2, 5, 9, 11 }, 11);
System.out.println(
"Pair with target sum: [" + result[0] + ", " + result[1] + "]"
);
}
}
Time Complexity
-
Initialization: Constant time,
, as it involves assigning values to leftandright. -
While Loop:
- The
whileloop runs as long asleftis less thanright. - In the worst case, this loop iterates over all elements of the array once. This happens when no pair is found, or the pair is found at the extreme ends of the array.
- Each iteration involves a constant amount of work: calculating
currentSum, comparing it withtargetSum, and then incrementingleftor decrementingright.
Therefore, the loop runs in
time, where is the number of elements in the array. - The
-
Overall: The dominant factor in this algorithm is the while loop, making the overall time complexity
.
Space Complexity
- The algorithm uses a fixed amount of extra space: variables
left,right, andcurrentSum. - It does not depend on the size of the input array, as no additional data structures are used that grow with the input size.
- Thus, the space complexity is
, constant space.
In summary, the algorithm has a time complexity of
An Alternate approach
Instead of using a two-pointer or a binary search approach, we can utilize a HashTable to search for the required pair. We can iterate through the array one number at a time. Let’s say during our iteration we are at number ‘X’, so we need to find ‘Y’ such that “
Search for ‘Y’ (which is equivalent to “Target−X”) in the HashTable. If it is there, we have found the required pair. Otherwise, insert “X” in the HashTable, so that we can search it for the later numbers.
Step-by-step Algorithm
-
Initialize a HashMap:
- Create a HashMap to store numbers as keys and their indices as values.
-
Iterate through the array:
- Loop through each element in the array using a for loop.
-
Check for the complement:
- For each element, check if the HashMap contains the complement (i.e.,
targetSum - current element). - If it does, return the indices of the complement and the current element.
- For each element, check if the HashMap contains the complement (i.e.,
-
Store the element and its index:
- If the complement is not found, store the current element and its index in the HashMap.
-
Return result:
- If no pair is found by the end of the loop, return
[-1, -1].
- If no pair is found by the end of the loop, return
Algorithm Walkthrough
Example Input: [1, 2, 3, 4, 6], Target: 6
-
Initialize:
nums = {}
-
First iteration (i = 0):
- Current element:
1 - Complement needed:
6 - 1 = 5 5is not innums- Store
1with index0:nums = {1: 0}
- Current element:
-
Second iteration (i = 1):
- Current element:
2 - Complement needed:
6 - 2 = 4 4is not innums- Store
2with index1:nums = {1: 0, 2: 1}
- Current element:
-
Third iteration (i = 2):
- Current element:
3 - Complement needed:
6 - 3 = 3 3is not innums- Store
3with index2:nums = {1: 0, 2: 1, 3: 2}
- Current element:
-
Fourth iteration (i = 3):
- Current element:
4 - Complement needed:
6 - 4 = 2 2is innumswith index1- Return indices
[1, 3]
- Current element:
Code
import java.util.HashMap;
class Solution {
public static int[] search(int[] arr, int targetSum) {
HashMap<Integer, Integer> nums = new HashMap<>(); // to store numbers and indices
for (int i = 0; i < arr.length; i++) {
if (nums.containsKey(targetSum - arr[i])) return new int[] {
nums.get(targetSum - arr[i]),
i,
};
else nums.put(arr[i], i); // put the number and its index in the map
}
return new int[] { -1, -1 }; // pair not found
}
public static void main(String[] args) {
int[] result = Solution.search(new int[] { 1, 2, 3, 4, 6 }, 6);
System.out.println(
"Pair with target sum: [" + result[0] + ", " + result[1] + "]"
);
result = Solution.search(new int[] { 2, 5, 9, 11 }, 11);
System.out.println(
"Pair with target sum: [" + result[0] + ", " + result[1] + "]"
);
}
}
Time Complexity
-
HashMap Initialization: Constant time,
. -
For Loop:
- The
forloop iterates over each element of the array once. - In each iteration, the algorithm checks if the element is already present in the
HashMap(ordictionaryin Python) and either returns a result or inserts an element into theHashMap. - This element checking or insertion operations of a
HashMapgenerally operate intime due to efficient hashing. However, in the worst case (e.g., when many hash collisions occur), these operations can degrade to . Under the assumption of a good hash function with minimal collisions, these operations can be considered .
Therefore, the loop runs in
time in the average case, where (n) is the number of elements in the array. - The
-
Overall: The dominating factor in this algorithm is the for loop. Under the assumption of efficient hashing, the overall average time complexity is
.
Space Complexity
- The algorithm uses a
HashMapto store elements from the array. In the worst case, this map can store all elements of the array if no pair is found that adds up to the target sum - Thus, the space complexity is proportional to the number of elements in the array, which is
.
In summary, the algorithm has an average time complexity of
🤖 Don't fully get this? Learn it with Claude
Stuck on Pair with Target Sum? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Pair with Target Sum** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Pair with Target Sum** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Pair with Target Sum**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Pair with Target Sum**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.