Advertisement

Two Sum - LeetCode 1 Solution

Two Sum - Complete Solution Guide

Two Sum is LeetCode problem 1, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target . You may assume that each input would have exactly one solution , and you may not use the same element twice. You can return the answer in any order. 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

Detailed Explanation

The Two Sum problem asks you to find two numbers within a given array that add up to a specified target value. The input consists of an array of integers (`nums`) and the target integer (`target`). The output should be the indices (positions) of the two numbers in the array that sum to the target. You are guaranteed that there will be exactly one solution, and you cannot use the same element twice. The indices can be returned in any order.

Solution Approach

The provided solutions use a hash map (or unordered_map in C++) to solve the problem efficiently. The algorithm iterates through the input array. For each number, it calculates the complement needed to reach the target. It then checks if the complement exists as a key in the hash map. If it does, it means the complement (and hence the pair) has already been encountered, and the indices are returned. If not, the current number and its index are added to the hash map for future checks. This approach avoids redundant checks and significantly improves the performance.

Step-by-Step Algorithm

  1. Step 1: Initialize an empty hash map (dictionary in Python).
  2. Step 2: Iterate through the input array `nums` using a loop.
  3. Step 3: For each number `num` in `nums`, calculate the `complement` as `target - num`.
  4. Step 4: Check if the `complement` exists as a key in the hash map.
  5. Step 5: If the `complement` exists, return the index of the `complement` (stored in the hash map) and the current index `i`.
  6. Step 6: If the `complement` does not exist, add the current number `num` and its index `i` to the hash map.
  7. Step 7: If the loop completes without finding a pair, return an empty array (or handle accordingly based on language).

Key Insights

  • Insight 1: Using a hash map (dictionary in Python) allows for efficient lookups of the complement (target - num).
  • Insight 2: The hash map stores each number and its index, enabling quick identification of the pair that sums to the target.
  • Insight 3: A brute-force approach (nested loops) would have O(n^2) time complexity, while the hash map approach achieves O(n) time complexity.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Array, Hash Table.

Companies

Asked at: AMD, Accenture, Accolite, Adobe, Agoda, Airbnb, Airbus SE, Akamai, Altimetrik, Amadeus, Amazon, American Express, Apple, Atlassian, Avito, BNY Mellon, Barclays, BlackStone, Bloomberg, Bolt, Braze, ByteDance, Cadence, Capgemini, Careem, Chewy, Cisco, Cognizant, Comcast, Criteo, Deloitte, Deutsche Bank, Devsinc, Docusign, DoorDash, Dropbox, EPAM Systems, EY, EarnIn, Epic Systems, Expedia, FPT, Fidelity, Flipkart, FreshWorks, Garmin, Goldman Sachs, Google, Grab, HCL, Honeywell, Huawei, Hubspot, IBM, Infosys, Intel, Intuit, J.P. Morgan, KLA, Karat, LinkedIn, Luxoft, Mastercard, Meta, Microsoft, MindTree, Morgan Stanley, Myntra, Nagarro, Nielsen, Nutanix, Nvidia, Oracle, Ozon, Palo Alto Networks, PayPal, Paytm, Publicis Sapient, Pwc, Qualcomm, Roblox, SAP, Samsung, ServiceNow, Shopee, Siemens, Slice, Snowflake, SoFi, Spotify, Tech Mahindra, Tekion, TikTok, Tinkoff, UKG, Uber, VMware, Visa, Walmart Labs, Western Digital, Wipro, Wise, Wissen Technology, Wix, Yahoo, Yandex, Yelp, ZScaler, Zoho, athenahealth, eBay, jio, persistent systems, tcs.