Back to Browse

22 Two Sum II | LeetCode | Java Solution in Hindi

14 views
May 1, 2024
11:40

The problem requires finding two numbers in a sorted array that add up to a specific target. The approach involves utilizing the fact that the array is sorted and using two pointers to scan the array. Intuition: Since the array is sorted, the smallest and largest elements are on the ends. If the sum of the smallest and largest elements is greater than the target, we move the pointer of the larger element inward to decrease the sum. If the sum is less than the target, we move the pointer of the smaller element inward to increase the sum. We continue this process until we find the target sum or until the two pointers meet. Approach: Initialize two pointers, left at the beginning of the array and right at the end of the array. While left is less than right, perform the following steps: Calculate the sum of the elements at positions left and right. If the sum equals the target, return the indices {left + 1, right + 1} since the problem requires 1-indexed indices. If the sum is greater than the target, decrement right to decrease the sum. If the sum is less than the target, increment left to increase the sum. If no such pair is found, return [-1, -1] or an empty array to indicate that no solution exists. This approach utilizes the sorted nature of the array to efficiently find the pair of numbers that add up to the target. Since the array is sorted, we can navigate through it using two pointers, reducing the time complexity to O(n) where n is the size of the array.

Download

0 formats

No download links available.

22 Two Sum II | LeetCode | Java Solution in Hindi | NatokHD