Skip to main content

Two Sum

EasyPremium

Given an array of integers nums and an integer target, write a function twoSum that returns the indices of the two numbers such that they add up to the target. You may assume that each input will have exactly one solution, and you may not use the same element twice. If no such pair exists, return an empty array. If there are multiple pairs of indices that sum to the target, return the indices of the pair where the numbers appear first in the array.

Examples

Input: nums = [2, 7, 11, 15], target = 9 Output: [0, 1] Input: nums = [3, 2, 4], target = 6 Output: [1, 2]

The brute force approach has a time complexity of O(n^2). We can do better.

Consider using a hash map to store the elements of the array along with their indices as you iterate through the array.

Implement the solution efficiently in terms of both time and space. Aim for an O(n) time complexity.