imashutosh51

Majority Element II

Feb 3rd, 2026
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. '''
  2. There can be 2 elements in any with more than n//3 occurance because n//3 + n//3+ n//3 > n is impossible.
  3. Phase 1-> Find potential candidate-> if current element ==candidate 1, increase it's count and similarly check for other element and if no elements in any of them then, place them. using the phase 1 you got the potential elment
  4.  
  5. so using the above logic even if arr is like [1,2,3,4,5] still you will get 2 elements so to check them are their frequency is actually more than n//3,you check it manually and return them as the output.
  6.  
  7. ***Always increment first then populate the None condition because if you will populate first the None,then suppose you got array like [1,1,2] then at the i=2, cand1=1 and cand2=1 because count1 is non-zero and count2 is zero***
  8. '''
  9. class Solution:
  10.     def majorityElement(self, nums: List[int]) -> List[int]:
  11.         if not nums:
  12.             return []
  13.  
  14.         # Phase 1: Find candidates
  15.         cand1, cand2 = None, None
  16.         count1, count2 = 0, 0
  17.  
  18.         for num in nums:
  19.             if num == cand1:
  20.                 count1 += 1
  21.             elif num == cand2:
  22.                 count2 += 1
  23.             elif count1 == 0:
  24.                 cand1, count1 = num, 1
  25.             elif count2 == 0:
  26.                 cand2, count2 = num, 1
  27.             else:
  28.                 count1 -= 1
  29.                 count2 -= 1
  30.  
  31.         # Phase 2: Verify counts
  32.         result = []
  33.         n = len(nums)
  34.  
  35.         if nums.count(cand1) > n // 3:
  36.             result.append(cand1)
  37.         if cand2 != cand1 and nums.count(cand2) > n // 3:
  38.             result.append(cand2)
  39.  
  40.         return result
  41.  
Advertisement
Add Comment
Please, Sign In to add comment