1. Two Sum
Asked at 113Amazon100Bloomberg100Google100Microsoft100Meta93Apple86Accenture100Capgemini100Wipro100tcs100Infosys100HCL100Cognizant95Qualcomm91Altimetrik89Samsung86Nvidia85Oracle85HSBC81Sony79Expedia73MongoDB71Microstrategy69TikTok67Citadel64Adobe100Citigroup100Comcast100Delhivery100Devsinc100EPAM Systems100EY100Garmin100Intel100Mastercard100NetApp100Pwc100SAP100Splunk100Synopsys100Tech Mahindra100Western Digital100Yahoo100ciena100Deloitte96Zoho96Visa95Yelp94Morgan Stanley93Dropbox92LTI92Airbus SE87Walmart Labs87Tinkoff86eBay86American Express85IBM85persistent systems84VK84Virtusa84FreshWorks81UKG79AMD79Spotify79Criteo78Tiger Analytics78Huawei76Toast76Flipkart75Tekion74Hubspot73DevRev72ThoughtWorks71Ozon70Accolite70FPT70Warnermedia70KLA69Yandex69Optum68Jane Street68PayPay68Snowflake67Airbnb66Dell66Grab66Lowe's65Turing64Akamai64HashedIn62Tesla62Barclays61Autodesk59ByteDance59Intuit58Cisco56ServiceNow55Uber55Goldman Sachs54PhonePe53Wix52PayPal51LinkedIn51Roblox51Epic Systems51Anduril49BlackRock47DoorDash45Capital One43DE Shaw38Databricks37Salesforce35Atlassian34
Problem
Given an integer array nums and an integer target, return the indices of the two elements that add up to target. Exactly one such pair exists, an element can't be paired with itself, and the indices may be returned in any order.
Example: nums = [2,7,11,15], target = 9 → [0,1]
Constraints: 2 ≤ n ≤ 10⁴. Follow-up: do better than O(n²).
Scan once. For each x, the partner we need is target - x. If we've already seen it, we're done; otherwise remember x → index.
nums = [2, 7, 11, 15], target = 9
i=0 x=2 need 7 seen {} -> store {2:0}
i=1 x=7 need 2 seen {2:0} -> hit! answer [0, 1]
Complexity: O(n) time, O(n) space.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []
assert sorted(Solution().twoSum([2, 7, 11, 15], 9)) == sorted([0, 1])
assert sorted(Solution().twoSum([3, 2, 4], 6)) == sorted([1, 2])
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[]{j, i};
seen.put(nums[i], i);
}
return new int[0];
}
}
func twoSum(nums []int, target int) []int {
seen := map[int]int{} // value -> index
for i, x := range nums {
if j, ok := seen[target-x]; ok {
return []int{j, i}
}
seen[x] = i
}
return nil
}