Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the first occurrence of the target element in the array.
DSA C
int firstOccurrence(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of the target in the comparison.
Comparing arr[i] to arr[i] which is always true.
✗ Incorrect
We compare each element arr[i] with the target to find the first occurrence.
2fill in blank
mediumComplete the code to find the last occurrence of the target element in the array.
DSA C
int lastOccurrence(int arr[], int n, int target) {
for (int i = n - 1; i >= 0; i--) {
if (arr[i] == [1]) {
return i;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of the target in the comparison.
Comparing arr[i] to arr[i] which is always true.
✗ Incorrect
We compare each element arr[i] with the target 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 the target element.
DSA C
int firstOccurrence(int arr[], int n, int target) {
int i = 0;
while (i < n) {
if (arr[i] == [1]) {
return i;
}
i++;
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '==' in the if condition.
Comparing with the wrong variable.
✗ Incorrect
The error is using assignment '=' instead of comparison '=='. Replace with '==' and compare arr[i] with target.
4fill in blank
hardFill both blanks to create a function that returns the first and last occurrence indices of the target element.
DSA C
void firstAndLastOccurrence(int arr[], int n, int target, int *first, int *last) {
*first = -1;
*last = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == [1]) {
if (*first == -1) {
*first = i;
}
*last = [2];
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Updating *last with *first instead of i.
Comparing arr[i] with the wrong variable.
✗ Incorrect
We compare arr[i] with target and update *last with the current index i.
5fill in blank
hardFill all three blanks to create a function that returns a struct with first and last occurrence of the target element.
DSA C
typedef struct {
int first;
int last;
} Occurrence;
Occurrence findOccurrences(int arr[], int n, int target) {
Occurrence result = [1];
result.first = -1;
result.last = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == [2]) {
if (result.first == -1) {
result.first = i;
}
result.last = [3];
}
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Not initializing the struct properly.
Updating result.last with the wrong value.
Comparing arr[i] with the wrong variable.
✗ Incorrect
Initialize result with empty braces {}, compare arr[i] with target, and update result.last with i.
