![]() |
VOOZH | about |
You are given an array arr[] of N integers, and your task is to find two different indices whose sum is X.
Examples:
Input: N = 4, X = 8, arr[] = {2, 7, 5, 1}
Output: 2 4
Explanation: The sum of arr[2] and arr[4] (1-based indexing) is 7 + 1 = 8Input: N = 5, X = 6, arr[] = {1, 2, 3, 4, 5}
Output: 1 5
Explanation: The sum of arr[1] and arr[5] (1-based indexing) is 1 + 5 = 6
Approach: To solve the problem, follow the below idea:
The problem can be solved using a map to store the element as the key and its index as the value. For every arr[i], check if there is any element already present in the map having value = X - arr[i]. If yes, then print the index of (X - arr[i]) along with the current index else insert the value and index to the map.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2 4
Time Complexity: O(N * logN), where N is the size of arr[].
Auxiliary Space: O(N)
Before applying the two-pointer approach, sort the array. Initialize two pointers, typically named 'left' and 'right'. 'left' points to the beginning (index 0) of the sorted array, and 'right' points to the end (index n-1) of the array, where 'n' is the length of the array. Iterate through the array using these two pointers. The iteration continues as long as 'left' pointer is less than 'right' pointer. This ensures that every pair of elements is considered exactly once. At each iteration, the sum of elements pointed to by 'left' and 'right' pointers is calculated. Now compare, If the sum equals the target value , then the pair of indices corresponding to 'left' and 'right' pointers is a valid solution, return it. If the sum is less than target value, it means that the current sum is small, increase left pointer. If the sum is greater than target value, decrease pointer. This process continues left pointer crosses right pointer.
Indices of the two numbers are : 1 and 6
Time Complexity: O(n)
Space Complexity: O(1)