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 C#
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 arr instead of target in the comparison.
Comparing with i 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 C#
int LastOccurrence(int[] arr, int target) {
for (int i = arr.Length - 1; i >= 0; i--) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using arr instead of target in the comparison.
Comparing with i instead of target.
✗ Incorrect
We compare each element arr[i] with the target value starting from the end to find the last occurrence.
3fill in blank
hardFix the error in the code to correctly find the first occurrence of target.
DSA C#
int FindFirst(int[] arr, int target) {
int index = -1;
for (int i = 0; i < arr.Length; i++) {
if (arr[i] [1] target) {
index = i;
break;
}
}
return index;
}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 assigns a value.
4fill in blank
hardFill both blanks to create a dictionary of element counts for the array.
DSA C#
Dictionary<int, int> counts = new Dictionary<int, int>(); foreach (int num in arr) { if (counts.ContainsKey([1])) { counts[[2]]++; } else { counts[num] = 1; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the array name instead of the current element variable.
Using an index variable that does not exist in the loop.
✗ Incorrect
We check and update the count for the current number 'num' in the dictionary.
5fill in blank
hardFill all three blanks to create a dictionary of elements with their first occurrence index.
DSA C#
Dictionary<int, int> firstIndices = new Dictionary<int, int>(); for (int i = 0; i < arr.Length; i++) { if (!firstIndices.ContainsKey([1])) { firstIndices[[2]] = [3]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the dictionary name instead of the element as key.
Assigning the element instead of the index as value.
✗ Incorrect
We check if the dictionary has the element arr[i], then store its index i as the first occurrence.
