Skip to content
prdlk
Esc
↑↓navigate↵open⌘Jpreview
On this page

1. Two Sum

You are given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target

CompanyAsked withinFrequency
Amazon30 days100
Google30 days100
Meta30 days100
Microsoft30 days100
tcs30 days80
Ola Cabs30 days77
Bloomberg30 days70
Infosys30 days69
Altimetrik3 months100
Capgemini3 months100
Microstrategy3 months100
MongoDB3 months100
Cognizant3 months89
Apple3 months80
Barclays6 months100
Cisco6 months100
Deloitte6 months100
Expedia6 months100
NetApp6 months100
Samsung6 months100
Sony6 months100
Oracle6 months91
Qualcomm6 months81
IBM6 months77
eBay6 months75
Walmart Labs6 months71
Flipkart6 months57
Goldman Sachs6 months45

Example 1:

  • Input: nums = [2,7,11,15], target = 9
  • Output: [0,1]
  • Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

  • Input: nums = [3,2,4], target = 6
  • Output: [1,2]

Example 3:

  • Input: nums = [3,3], target = 6
  • Output: [0,1]

Constraints:

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.

Approach

Solution

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in seen:
                return [seen[complement], i]
            seen[num] = i
        return []

Last updated on

Was this page helpful?