1. Two Sum
Problem
Intuition
Time Complexity
Space Complexity
Solution
class Solution {
public int[] twoSum(int[] nums, int target) {
// n -> nums.length, number of elements in array
// Time Complexity: O(n), to traverse the nums array
// Space Complexity: O(n), to store the complements in hashmap
// Create a HashMap to store the elements and their indices
Map<Integer, Integer> map = new HashMap<>();
// Iterate through the array
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i]; // Calculate the complement required to reach the target
// Check if the complement is present in the map
if (map.containsKey(complement)) {
// Return the indices of the current element and its complement
return new int[]{i, map.get(complement)};
}
// If the complement is not found, add the current element to the map with its index
map.put(nums[i], i);
}
// If no solution is found, return null
return null;
}
}
Last updated
Was this helpful?