Skip to main content
All Questions

Given an array, find the two sum.

Easy

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]

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.