Majority Element II
LeetCode 229 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Count and keep values with count > n // 3.
আমি Majority Element II (LeetCode 229) এভাবে সমাধান করেছি — Moore Voting প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.
Approach
- 1
Count frequencies.
- 2
Keep each value whose count exceeds n // 3.
আমি কীভাবে সমাধান করেছি
Counter filterPythonO(n) time · O(n) space
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
mpp = Counter(nums)
res = []
for key,val in mpp.items():
if val>(n//3):
res.append(key)
return resMajority Element II — সাধারণ প্রশ্ন
Majority Element II-এর পেছনে intuition কী?
Any value appearing more than n/3 times qualifies; there can be at most two. Counting every value with a Counter and filtering by the threshold is straightforward.
Majority Element II (LeetCode 229) কীভাবে সমাধান করবেন?
1. Count frequencies. 2. Keep each value whose count exceeds n // 3.
Majority Element II-এর time আর space complexity কত?
Time: O(n)। Space: O(n)। (Accepted approach: Counter filter।)
Majority Element II-এ সাধারণ ভুলগুলো কী?
Extended Boyer–Moore (two candidates) does it in O(1) space.