LeetCode 167: Two Sum II - Input Array Is Sorted Solution

Master LeetCode problem 167 (Two Sum II - Input Array Is Sorted), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

167. Two Sum II - Input Array Is Sorted

Problem Explanation

Explanation

To solve this problem, we can use a two-pointer approach. Since the input array is sorted, we can start with two pointers - one at the beginning of the array and one at the end. We check the sum of the elements pointed to by these pointers. If the sum is equal to the target, we return the indices. If the sum is less than the target, we move the left pointer to the right to increase the sum. If the sum is greater than the target, we move the right pointer to the left to decrease the sum. We continue this process until we find the target sum.

  • Time complexity: O(n) where n is the number of elements in the array.
  • Space complexity: O(1) since we are using constant extra space.

Solution Code

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length - 1;
        
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        
        return new int[]{-1, -1}; // No solution found
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 167 (Two Sum II - Input Array Is Sorted)?

This page provides optimized solutions for LeetCode problem 167 (Two Sum II - Input Array Is Sorted) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 167 (Two Sum II - Input Array Is Sorted)?

The time complexity for LeetCode 167 (Two Sum II - Input Array Is Sorted) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 167 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 167 in Java, C++, or Python.

Back to LeetCode Solutions