1. Two Sum
function twoSum(nums: number[], target: number): number[] {
// Created a hash map to store the value, index pairs
let hash = new Map()
// Iterating over the length of nums
for(let i = 0; i < nums.length ; i++){
// Checking if the value already present in the hashmap
if(hash.has(nums[i])){
// If the value is already present in the hashmap then we will return the
// current index and the index which was set to the hashmap of the respective
// current value
return [i, hash.get(nums[i])]
}
// Calculated the value of x and then set the key, value pair in the form of value
// index
const x = target - nums[i]
hash.set(x, i)
}
return
}
Time Complexity: The time complexity of the twoSum function is O(n), where n is the number of elements in the nums array. This complexity arises from the single pass through the array to iterate over its elements. Within each iteration, the function performs constant-time operations such as hash map lookups and arithmetic calculations. Therefore, the overall time complexity is linear with respect to the size of the input array.
Space Complexity: The space complexity of the twoSum function is O(n), where n is the number of elements in the nums array. This complexity is determined by the usage of a hash map (hash) to store value-index pairs. In the worst-case scenario, where no pair of elements sum up to the target, the hash map will store all elements of the array along with their corresponding indices. Additionally, the function uses a constant amount of extra space for variables like i, x, and for the returned array containing the indices.
Overall, the twoSum function provides an efficient solution to the two-sum problem with linear time complexity and linear space complexity, making it suitable for handling large input arrays.