Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Question
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
Solution
Sure, here is a Python solution for your problem using a dictionary (hashmap) to store the numbers and their indices.
def twoSum(nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
Here is a step by step explanation of the code:
-
Check if the length of the input list is less than or equal to 1. If it is, return False because there are not enough numbers to add up to the target.
-
Create an empty dictionary
buff_dict
. -
Loop through the list
nums
with the indexi
. -
Check if
nums[i]
is inbuff_dict
. If it is, return a list withbuff_dict[nums[i]]
andi
. These are the indices of the two numbers that add up to the target. -
If
nums[i]
is not inbuff_dict
, add a new entry to the dictionary with the key astarget - nums[i]
and the value asi
. This is because if we encounter a number that istarget - nums[i]
later in the list, we know thatnums[i]
andtarget - nums[i]
add up to the target. -
Continue this process until we find a pair of numbers that add up to the target or we have checked all numbers in the list.
Similar Questions
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Write a program to read and store n+ve numbers in array and search a number k provided by the user using a. Linear Searchb. Binary Search
Given a list of integers, count and return the number of times each value appears as an array of integers.
Given an array, check if there exist 2 elements of the array such that their sum is equal to the sum of the remaining elements of the array.
Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.