Saved Bookmarks
| 1. |
Two sum of an array: In this question you will be given an array arr and a target. You have to return the indices of the two numbers such that they add up to target. |
|
Answer» In this question, you will be given an array arr and a target. You have to return the indices of the two NUMBERS such that they add up to the target. Approach: So the easiest and most efficient solution is using a HashMap. We have to iterate through all the elements of the array and if (target-num) is present in the array then return {lower index, higher index} else PUSH the value at arr[i] and the index i in the hashmap. public class InterviewBit { public int[] twoSum(int[] arr, int target) { HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for(int i = 0; i <arr.length; i++){ Integer diff = (Integer)(target - arr[i]); if(hash.containsKey(diff)){ int TORETURN[] = {hash.get(diff)+1, i+1}; return toReturn; } hash.put(arr[i], i); } return NULL; }}The time Complexity for this approach will be O(n). |
|