Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the candidate for majority element.
DSA Python
candidate = [1] count = 0
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting candidate to an element before starting the loop.
Using a number like 0 or 1 which may not be in the array.
✗ Incorrect
We start with no candidate, so candidate is set to None.
2fill in blank
mediumComplete the code to update the candidate when count is zero.
DSA Python
if count == 0: candidate = [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning candidate to the index instead of the element.
Assigning candidate to None or count.
✗ Incorrect
When count is zero, we pick the current element as the new candidate.
3fill in blank
hardFix the error in updating count based on the current element.
DSA Python
if arr[i] == candidate: count [1] 1 else: count -= 1
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Decreasing count when elements match.
Assigning count instead of incrementing.
✗ Incorrect
When the current element matches the candidate, we increase count by 1.
4fill in blank
hardFill both blanks to complete the verification step for majority element.
DSA Python
count = 0 for num in arr: if num [1] candidate: count [2] 1
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using != instead of == in the condition.
Decreasing count instead of increasing.
✗ Incorrect
We count how many times the candidate appears by checking equality and incrementing count.
5fill in blank
hardFill all three blanks to return the majority element or -1 if none exists.
DSA Python
if count [1] len(arr) // 2: return [2] else: return [3]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > for majority check.
Returning count instead of candidate.
Returning 0 instead of -1 when no majority.
✗ Incorrect
If candidate count is more than half the array length, return candidate; otherwise, return -1.