Given an array of integers, return the indices of the two numbers that add up to a…
- User
Given an array of integers, return the indices of the two numbers that add up to a specific target. Please solve using the most optimal algorithm possible.
Assistant
Optimal Solution (Two-Pass Hash Table):
Time Complexity: O(n)
Space Complexity: O(n)def two_sum(nums, target): num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i return []Explanation:
- Hash Map (
num_map): Stores numbers as keys and their indices as values.
- Hash Map (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.