Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. 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.

  2. Create an empty dictionary buff_dict.

  3. Loop through the list nums with the index i.

  4. Check if nums[i] is in buff_dict. If it is, return a list with buff_dict[nums[i]] and i. These are the indices of the two numbers that add up to the target.

  5. If nums[i] is not in buff_dict, add a new entry to the dictionary with the key as target - nums[i] and the value as i. This is because if we encounter a number that is target - nums[i] later in the list, we know that nums[i] and target - nums[i] add up to the target.

  6. 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.

This problem has been solved

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.

1/1

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.