This is extremely simple problem where-in we traverse the array starting from 0’th index ( and incrementing by one index at a time ) and search for the reminder of the targetSum in rest of the array.
Code can be found @ Two Sum – LeetCode.
This is an O(n^2) algorithm.
We can solve this problem in O(n) using HashMap / Dictionary in the following manner.
1. First populate the Hashmap / Dictionary with indexes for each element.
2. Traverse the array starting from beginning and find the reminder of the targetSum.
3. Search for index of the reminder using HashMap / Dictionary in O(1).
4. Considering that there’s only one solution to the problem index can be found through dictionary in O(1).
This is an O(n) Algorithm. Code can be found @ Two Sum – LeetCode
Feel free to raise any questions / comments in the discussion section.
– Vamshi.
