Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create twoSum.py #72

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/twoSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def twoSum(nums: list[int], target: int) -> list[int]:
"""
Given an array of integers nums and an integer target,
return indices of the two numbers that add up to target.

Args:
nums: List of integers
target: Target sum

Returns:
List containing indices of two numbers that sum to target

Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]
"""
# Create hash map to store complement values
seen = {}

# Iterate through array once, O(n) time complexity
for i, num in enumerate(nums):
complement = target - num

# If we've seen the complement before, we found our pair
if complement in seen:
return [seen[complement], i]

# Store current number and its index
seen[num] = i

# No solution found
return []