Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the first occurrence index of target in the array.
DSA Java
public static int firstOccurrence(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of target for comparison.
Comparing arr[i] with arr instead of target.
✗ Incorrect
We compare each element arr[i] with the target value to find the first occurrence.
2fill in blank
mediumComplete the code to find the last occurrence index of target in the array.
DSA Java
public static int lastOccurrence(int[] arr, int target) {
int result = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == [1]) {
result = i;
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of target for comparison.
Not updating the result variable inside the loop.
✗ Incorrect
We update result whenever arr[i] equals target to track the last occurrence index.
3fill in blank
hardFix the error in the code to correctly find the first occurrence of target.
DSA Java
public static int firstOccurrence(int[] arr, int target) {
int i = 0;
while (i < arr.length) {
if (arr[i] [1] target) {
return i;
}
i++;
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '==' in the if condition.
Using '!=' which checks for inequality.
✗ Incorrect
The if condition must use '==' to compare values, not '=' which is assignment.
4fill in blank
hardFill the blank to create a method that returns the first and last occurrence indices of target in the array.
DSA Java
public static int[] firstAndLastOccurrence(int[] arr, int target) {
int first = -1;
int last = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] [1] target) {
if (first == -1) {
first = i;
}
last = i;
}
}
return new int[] {first, last};
}Attempts:
3 left
💡 Hint
Common Mistakes
Using inequality operator '!=' instead of equality.
Using comparison operators '<' or '>' which are incorrect here.
✗ Incorrect
We check if arr[i] equals target to update first and last occurrence indices.
5fill in blank
hardFill all three blanks to create a method that returns a map with keys "first" and "last" for the first and last occurrence indices of target.
DSA Java
import java.util.Map; import java.util.HashMap; public static Map<String, Integer> findOccurrences(int[] arr, int target) { Map<String, Integer> result = new HashMap<>(); int first = -1; int last = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] [1] target) { if (first [2] -1) { first = i; } last = i; } } result.put("[3]", first); result.put("last", last); return result; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '!=' to check first index.
Using wrong key string instead of "first" in the map.
✗ Incorrect
We check equality with '==', check if first is equal to -1 with '!=', and use "first" as the key string.
