1. Two Sum
Problem Statement
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.
Solutions
We can use a hash map to store the indices of the elements as we iterate through the array. For each element, we check if the complement (i.e., target - nums[i]
) exists in the hash map. If it does, we return the indices of the current element and its complement.
- Time Complexity: O(n)
- Space Complexity: O(n)
This approach is not applicable for this problem since the array is not sorted. However, if the array were sorted, we could use two pointers to find the two numbers that add up to the target.
- Time Complexity: O(n log n) for sorting, O(n) for the two-pointer traversal, resulting in O(n log n) overall.
- Space Complexity: O(n)
We can use a brute force approach by checking every pair of elements in the array to see if they add up to the target. This approach has a time complexity of O(n^2)
.
- Time Complexity: O(n^2)
- Space Complexity: O(1)