Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check If a Number Is Majority Element in a Sorted Array in Python
A majority element in an array is an element that appears more than N/2 times in an array of length N. When dealing with a sorted array, we can use binary search to efficiently find the first and last occurrence of the target element and check if its frequency exceeds the majority threshold.
Algorithm Overview
To solve this problem, we need to:
- Find the leftmost (first) occurrence of the target using binary search
- Find the rightmost (last) occurrence of the target using binary search
- Calculate the frequency by subtracting indices
- Check if frequency > N/2
Finding First and Last Occurrence
We'll implement two helper functions using binary search variants ?
class Solution:
def find_first(self, nums, target):
"""Find the first occurrence of target"""
low = 0
high = len(nums) - 1
result = -1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
result = mid
high = mid - 1 # Continue searching left
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return result
def find_last(self, nums, target):
"""Find the last occurrence of target"""
low = 0
high = len(nums) - 1
result = -1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
result = mid
low = mid + 1 # Continue searching right
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return result
Complete Solution
Now let's implement the main function that uses these helpers ?
class Solution:
def find_first(self, nums, target):
low = 0
high = len(nums) - 1
result = -1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
result = mid
high = mid - 1
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return result
def find_last(self, nums, target):
low = 0
high = len(nums) - 1
result = -1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
result = mid
low = mid + 1
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return result
def isMajorityElement(self, nums, target):
first = self.find_first(nums, target)
if first == -1:
return False
last = self.find_last(nums, target)
frequency = last - first + 1
return frequency > len(nums) // 2
# Test the solution
solution = Solution()
nums = [2, 4, 5, 5, 5, 5, 5, 6, 6]
target = 5
result = solution.isMajorityElement(nums, target)
print(f"Is {target} a majority element? {result}")
Is 5 a majority element? True
Testing Different Cases
Let's test with multiple examples to verify our solution ?
solution = Solution()
# Test case 1: Majority element exists
nums1 = [2, 4, 5, 5, 5, 5, 5, 6, 6]
print(f"Array: {nums1}")
print(f"Target 5 is majority: {solution.isMajorityElement(nums1, 5)}")
# Test case 2: Non-majority element
nums2 = [1, 2, 3, 3, 3, 4, 5]
print(f"Array: {nums2}")
print(f"Target 3 is majority: {solution.isMajorityElement(nums2, 3)}")
# Test case 3: Element not present
nums3 = [1, 1, 2, 2, 3, 3]
print(f"Array: {nums3}")
print(f"Target 4 is majority: {solution.isMajorityElement(nums3, 4)}")
Array: [2, 4, 5, 5, 5, 5, 5, 6, 6] Target 5 is majority: True Array: [1, 2, 3, 3, 3, 4, 5] Target 3 is majority: False Array: [1, 1, 2, 2, 3, 3] Target 4 is majority: False
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(log n) | Two binary searches |
| Space | O(1) | Only using constant extra space |
Conclusion
Using binary search to find first and last occurrences allows us to check majority element status in O(log n) time. This approach is efficient for sorted arrays and handles all edge cases including missing elements.
