Two Sum (Sorted Array) in Java: Explanation & Practice
Find two numbers in a sorted array that add up to target
Problem summary
Given a sorted array and a target sum, find two numbers that add up to the target. Return their indices. Use the Two Pointer technique for O(n) solution.
Starter code
public class Main {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
// Two pointer approach:
// Start with left=0, right=n-1
// If sum < target, move left++
// If sum > target, move right--
// Print: Indices: 0, 1
}
}Expected output and test cases
- nums=[2,7,11,15], target=9
Indices: 0, 1
- nums=[1,2,3,4], target=4
Indices: 0, 2
- nums=[1,3,5,7], target=10
Indices: 1, 3
Hints
- Use two pointers: left at start, right at end
- If sum < target, we need a bigger number → move left pointer right
- If sum > target, we need a smaller number → move right pointer left
- Works because array is sorted!
Related Data Structures & Algorithms exercises
- Practice Remove Duplicates from Sorted Array in Java
- Practice Container With Most Water in Java
- Practice Three Sum in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler