Two Sum
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.
Solution
Use a key-value store to record the index of each element in nums
as we iterate through the array. For each element, check if the store contains the difference between the current element and the target. If it does, we return the current index and the index of the difference. If it doesn’t, we add the current element to the key-value store.
Implementation
Pseudocode
- Initialize a key-value store to record the index of each element in
nums
. - Iterate through
nums
and for each element, check if the key-value store contains the difference between the current element and the target. - If it does, return the current index and the index of the difference.
Complexity Analysis
- The time complexity of this algorithm is O(n) because we iterate through the array once.
- The space complexity of this algorithm is O(n) because we store the index of each element in a key-value store.