InterviewHubPRO
Section Overview
Q6

Question 6 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

6%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

Two Sum.

In Simple Words: Iterate through numbers and check if target - current already exists in a Hash Map. If yes, return their indices; otherwise store current -> index.

  • Time: $O(N)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def twoSum(nums: list[int], target: int) -> list[int]:
    prev_map = {}  # val -> index
    for i, n in enumerate(nums):
        diff = target - n
        if diff in prev_map:
            return [prev_map[diff], i]
        prev_map[n] = i
    return []