Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the HashMap for storing numbers and their indices.
DSA Java
Map<Integer, Integer> map = new HashMap[1];Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets [] instead of parentheses
Using curly braces {} which are for blocks or initializers
Using angle brackets <> which are for generics only
✗ Incorrect
In Java, to create a new HashMap object, you use parentheses after the constructor name.
2fill in blank
mediumComplete the code to check if the map contains the complement of the current number.
DSA Java
if (map.[1](target - nums[i])) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using containsValue which checks values, not keys
Using get which retrieves a value but does not check existence
Using put which inserts a key-value pair
✗ Incorrect
We use containsKey to check if a key (the complement) exists in the map.
3fill in blank
hardFix the error in the return statement to correctly return the indices as an array.
DSA Java
return new int[] {map.get(target - nums[i]), [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the target value instead of the index
Returning the number nums[i] instead of its index
Returning the map object which is not an index
✗ Incorrect
We return the current index i along with the index stored in the map for the complement.
4fill in blank
hardFill both blanks to correctly add the current number and its index to the map.
DSA Java
map.[1](nums[i], [2]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using get instead of put to add elements
Using containsKey which only checks existence
Using wrong value instead of index i
✗ Incorrect
We use put to add the number as key and its index i as value to the map.
5fill in blank
hardFill all three blanks to complete the for-loop header iterating over the array indices.
DSA Java
for (int [1] = 0; [2] < [3]; [1]++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using j instead of i inconsistently
Using nums instead of nums.length in the condition
Incorrect increment variable
✗ Incorrect
The loop variable i starts at 0, runs while i < nums.length, and increments i each time.
