DEV Community

Dharani
Dharani

Posted on

Find The Majority Element

Introduction

Finding the majority element is a common problem in data structures. It helps in understanding arrays, counting techniques, and efficient algorithms.


Problem Statement

Given an array of size n, find the element that appears more than ⌊n/2⌋ times.

You can assume that the majority element always exists.


Approach 1: Brute Force

  1. Count frequency of each element
  2. Return the element with count > n/2

Python Code (Brute Force)


python
def majority_element(arr):
    n = len(arr)
    for i in arr:
        if arr.count(i) > n // 2:
            return i


## Input
   [2,2,1,1,2]

## output
   [2]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)