Check If a Number Is Majority Element in a Sorted Array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called, nums and that is sorted in non-decreasing order, and a number target. We have to find if the target is a majority element. In an array a majority element is an element that appears more than N/2 times in an array of length N. So if the array is like − [2,4,5,5,5,5,5,6,6] and target is 5, then output is true.

To solve this, we will follow these steps −

  • There will be two helping modules, lower() and upper(). These are as follows.
  • The lower() takes two arguments array arr and target, that is −
  • low := 0, high := length of arr
  • while low < high −
    • mid := low + (high - low)/2
    • if arr[mid] = target, then high = mid, otherwise low = mid + 1
  • return high when arr[high] = target, otherwise -1
  • The upper() takes two arguments array arr and target, that is −
  • low = 0, high = length of arr
  • while low < high −
    • mid = low + (high - low)/2
    • if arr[mid] = target, then low = mid, otherwise high = mid - 1
  • return low when arr[low] = target, otherwise -1
  • The main function will be like −
  • u := upper(arr, target)
  • l := lower(arr, target)
  • return true, when u – l + 1 > (length of nums) / 2 if u is not -1, otherwise false

Example(Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def upper(self,n,target):
      low = 0
      high = len(n)-1
      while low<high:
         mid = low + (high - low + 1)//2
         if n[mid] == target:
            low = mid
         else:
            high = mid-1
      return low if n[low] == target else -1
   def lower(self,n,target):
      low = 0
      high = len(n)-1
      while low < high:
         mid = low + (high - low)//2
         if n[mid]== target:
            high = mid
         else :
            low = mid +1
      return high if n[high] == target else -1
   def isMajorityElement(self, nums, target):
      u = self.upper(nums,target)
      l = self.lower(nums,target)
      return u-l+1 >len(nums)/2 if u != -1 else False
ob1 = Solution()
print(ob1.isMajorityElement([2,4,5,5,5,5,5,6,6], 5))

Input

[2,4,5,5,5,5,5,6,6]
5

Output

true
raja
Published on 27-Feb-2020 07:21:02
Advertisements