Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the candidate for majority element.
DSA C++
int findMajorityElement(vector<int>& nums) {
int candidate = [1];
int count = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing candidate with nums[0] without setting count to 1.
Using an uninitialized candidate variable.
✗ Incorrect
We start with count zero and candidate zero (or any value). The candidate will be updated in the loop when count is zero.
2fill in blank
mediumComplete the code to update the count based on the current number.
DSA C++
for (int num : nums) { if (count == 0) { candidate = num; } count += (num [1] candidate) ? 1 : -1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' causing wrong count updates.
Using comparison operators like '>' or '<' which are incorrect here.
✗ Incorrect
We increase count if num equals candidate, else decrease count.
3fill in blank
hardFix the error in the code to correctly verify the majority element after finding the candidate.
DSA C++
int count = 0; for (int num : nums) { if (num == [1]) { count++; } } if (count > nums.size() / 2) { return candidate; } else { return -1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing num with count or zero instead of candidate.
Not verifying the candidate count at all.
✗ Incorrect
We count how many times the candidate appears to confirm it is the majority element.
4fill in blank
hardFill both blanks to complete the function that returns the majority element or -1 if none exists.
DSA C++
int findMajorityElement(vector<int>& nums) {
int candidate = [1];
int count = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
count = 0;
for (int num : nums) {
if (num == [2]) {
count++;
}
}
return (count > nums.size() / 2) ? candidate : -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using candidate before initialization.
Comparing count with wrong variable.
✗ Incorrect
Initialize candidate to 0 and verify count against candidate after the first loop.
5fill in blank
hardFill all three blanks to create a dictionary comprehension-like structure in C++ using a map to count frequencies.
DSA C++
map<int, int> freq; for (int num : nums) { freq[[1]] = freq[[2]] + [3]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using candidate instead of num as key.
Adding wrong values instead of 1.
✗ Incorrect
We increment the frequency count for each num by 1.
