Problem Description
A classic LeetCode question called "Two Sum". The problem is simple: given an array of integers and a target integer, return the indices of two numbers in the array that add up to the target. Sounds easy, right? Let's dive in!
Solution
First, let's take a look at the solution in Python:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, n in enumerate(nums):
diff = target - n
if diff in seen:
return [i, seen[diff]]
else:
seen[n] = i
Here's what's happening: we're creating an empty dictionary called seen
to keep track of the integers we've already seen in the array. We then iterate through each integer in the array using the enumerate
function, which gives us both the index and the value of each integer.
Next, we calculate the difference between the target and the current integer, and check if that difference is already in seen
. If it is, we've found our two numbers and we can return their indices. If not, we add the current integer to seen
along with its index.
Complexity Analysis
The time complexity of this solution is O(n), since we're only iterating through the array once. The space complexity is also O(n), since we're creating a dictionary to store the integers we've seen.
Conclusion
And there you have it - a fun and easy solution to the "Two Sum" problem in Python! Don't be intimidated by LeetCode questions - with a little bit of practice and determination, you can tackle any coding challenge. Happy coding! 😎