Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the candidate variable.
DSA C
int findMajorityElement(int arr[], int n) {
int count = 0;
int candidate = [1];
for (int i = 0; i < n; i++) {
if (count == 0) {
candidate = arr[i];
count = 1;
} else if (arr[i] == candidate) {
count++;
} else {
count--;
}
}
return candidate;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing candidate to 0 or -1 which may not be in the array.
Not initializing candidate before the loop.
✗ Incorrect
The candidate is initially set to the first element of the array to start the voting process.
2fill in blank
mediumComplete the code to update the count when the current element matches the candidate.
DSA C
if (arr[i] == candidate) { [1]; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Decreasing count instead of increasing it.
Resetting count to 0 or 1 incorrectly.
✗ Incorrect
When the current element matches the candidate, increase the count by one.
3fill in blank
hardFix the error in the condition to reset the candidate and count.
DSA C
if (count == [1]) { candidate = arr[i]; count = 1; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Resetting candidate when count is 1 instead of 0.
Using negative values in the condition.
✗ Incorrect
The candidate and count reset when count reaches zero, not one.
4fill in blank
hardFill both blanks to complete the verification loop that confirms the majority element.
DSA C
int verifyCount = 0; for (int i = 0; i < n; i++) { if (arr[i] [1] candidate) { verifyCount [2]; } } if (verifyCount > n / 2) { return candidate; } else { return -1; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' in the condition.
Decrementing verifyCount instead of incrementing.
✗ Incorrect
We check if each element equals the candidate and increment verifyCount if true.
5fill in blank
hardFill all three blanks to complete the main function that tests the majority element function.
DSA C
#include <stdio.h> int findMajorityElement(int arr[], int n); int main() { int arr[] = {2, 2, 1, 1, 1, 2, 2}; int n = [1]; int result = findMajorityElement(arr, [2]); if (result != [3]) { printf("Majority element is %d\n", result); } else { printf("No majority element found\n"); } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing wrong array length.
Using 0 instead of -1 for no majority element.
✗ Incorrect
The array length is 7, passed twice, and -1 indicates no majority element.
