Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the candidate for majority element.
DSA C#
int candidate = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing candidate to 0 or -1 which may not be in the array.
Using nums.Length which is an integer count, not an element.
✗ Incorrect
The candidate is initialized 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 (nums[i] == candidate) count [1] 1;
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' which decreases the count incorrectly.
Using '*=' or '/=' which are not appropriate here.
✗ Incorrect
When the current element matches the candidate, we increase the count by 1.
3fill in blank
hardFix the error in the code that resets the candidate and count when count reaches zero.
DSA C#
if (count == 0) { candidate = nums[[1]]; count = 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using i+1 which can cause index out of range.
Using 0 which resets candidate incorrectly.
✗ Incorrect
When count is zero, the candidate is reset to the current element nums[i].
4fill in blank
hardFill both blanks to complete the loop that implements Moore's Voting Algorithm.
DSA C#
for (int [1] = 1; [2] < nums.Length; [1]++) { if (nums[i] == candidate) count++; else count--; if (count == 0) { candidate = nums[i]; count = 1; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in initialization and condition.
Starting loop at 0 instead of 1.
✗ Incorrect
The loop variable is 'i' used consistently for initialization, condition, and increment.
5fill in blank
hardFill all three blanks to verify the candidate is the majority element after voting.
DSA C#
int countCheck = 0; foreach (int num in nums) { if (num == [1]) countCheck[2] 1; } return countCheck > [3] / 2 ? candidate : -1;
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable instead of candidate.
Using '-' instead of '+=' for countCheck.
Comparing with count instead of nums.Length.
✗ Incorrect
We count how many times candidate appears, then check if it is more than half the array length.
