Learner Level

Implement the twoSumUsingMap method that returns two indices that form the target sum using a hash map.

The input contains an integer array nums, its length size, and an integer target. Your task is to return the indexes of two numbers whose sum is equal to target.

Each input is expected to have one valid pair. The same element cannot be used twice.

For example, in [2,7,11,15] with target 9, values 2 and 7 form the target sum, so the answer is [0,1].

Example 1

Input
nums (int[]) = [2,7,11,15]
size (int) = 4
target (int) = 9
Returns (int[]) [0,1]

Example 2

Input
nums (int[]) = [3,2,4]
size (int) = 3
target (int) = 6
Returns (int[]) [1,2]

Example 3

Input
nums (int[]) = [3,3]
size (int) = 2
target (int) = 6
Returns (int[]) [0,1]

Use a hash map to remember values that have already been visited along with their indexes.

For each current number, calculate the needed complement as target - currentNumber. If the complement already exists in the map, the pair has been found.

If not found, store the current number and its index in the map and continue scanning.

Pseudocode:

function twoSumUsingMap(nums, size, target):
    create empty map valueToIndex
    for i from 0 to size - 1:
        need = target - nums[i]
        if need exists in valueToIndex:
            return [valueToIndex[need], i]
        valueToIndex[nums[i]] = i
    return [-1, -1]
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.