Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the hash map for storing numbers and their indices.
DSA Javascript
const twoSum = (nums, target) => {
const [1] = new Map();
for (let i = 0; i < nums.length; i++) {
// code continues...
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Using an array instead of a Map.
Not initializing the Map before the loop.
✗ Incorrect
We use a variable named 'hashMap' to store numbers and their indices for quick lookup.
2fill in blank
mediumComplete the code to check if the complement exists in the hash map.
DSA Javascript
const twoSum = (nums, target) => {
const hashMap = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (hashMap.[1](complement)) {
return [hashMap.get(complement), i];
}
hashMap.set(nums[i], i);
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' instead of 'has' to check existence.
Using 'find' which is not a Map method.
✗ Incorrect
The 'has' method checks if the Map contains a specific key.
3fill in blank
hardFix the error in the return statement to correctly return the indices.
DSA Javascript
const twoSum = (nums, target) => {
const hashMap = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (hashMap.has(complement)) {
return [hashMap.get(complement), [1]];
}
hashMap.set(nums[i], i);
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Returning the complement value instead of its index.
Returning the target instead of an index.
✗ Incorrect
We return the current index 'i' along with the stored index of the complement.
4fill in blank
hardFill both blanks to complete the loop and add elements to the hash map.
DSA Javascript
const twoSum = (nums, target) => {
const hashMap = new Map();
for (let [1] = 0; [2] < nums.length; [1]++) {
const complement = target - nums[[1]];
if (hashMap.has(complement)) {
return [hashMap.get(complement), [1]];
}
hashMap.set(nums[[1]], [1]);
}
};Attempts:
3 left
💡 Hint
Common Mistakes
Using different variables for initialization and condition.
Using variables not declared in the loop.
✗ Incorrect
The loop variable 'i' is used consistently for initialization and condition.
5fill in blank
hardFill all three blanks to complete the function with a return for no solution.
DSA Javascript
const twoSum = (nums, target) => {
const hashMap = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (hashMap.has(complement)) {
return [hashMap.get(complement), i];
}
hashMap.set(nums[i], i);
}
return [1];
};Attempts:
3 left
💡 Hint
Common Mistakes
Returning null or undefined which may cause errors.
Returning -1 which is not an array.
✗ Incorrect
Returning an empty array '[]' indicates no two numbers sum to the target.
