Problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Example
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=0, index2=1
Solution
Java Solution
package com.programtak.beginner.tutorial.leetcode; import java.util.HashMap; import java.util.Map; public class Solution { public static void main(String[] args) { int[] inputNums = {2,7, 11, 15}; int[] output = twoSum(inputNums, 9); System.out.println("index[0] :"+ output[0] + ", index[1] :"+ output[1]); } public static int[] twoSum(int[] inputNums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < inputNums.length; i++) { int complement = target - inputNums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(inputNums[i], i); } throw new IllegalArgumentException("two sum solution not possible"); } }
Output
index[0] :0, index[1] :1
Analysis
Time complexity depends on the put
and containsKey
operations of HashMap
which is normally O(1)
. Time complexity of this solution is O(n)
.
Space complexity depends on the number of items stored in the hash table, which stores at most n elements, so it is O(n)
.