Given an array arr[] of size n, find the element that appears more than ⌊n/2⌋ times. If no such element exists, return -1.
Examples:
Input: arr[] = [1, 1, 2, 1, 3, 5, 1]
Output: 1
Explanation: Element 1 appears 4 times. Since ⌊7/2⌋ = 3, and 4 > 3, it is the majority element.
Input: arr[] = [7]
Output: 7
Explanation: Element 7 appears once. Since ⌊1/2⌋ = 0, and 1 > 0, it is the majority element.
Input: arr[] = [2, 13]
Output: -1
Explanation: No element appears more than ⌊2/2⌋ = 1 time, so there is no majority element.
[Naive Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space
The idea is to use nested loops to count frequencies. The outer loop selects each element as a candidate, and the inner loop counts how many times it appears. If any element appears more than n / 2 times, it is the majority element.
C++
#include <iostream>
#include <vector>
using namespace std;
int majorityElement(vector<int>& arr) {
int n = arr.size();
// Loop to consider each element as a
// candidate for majority
for (int i = 0; i < n; i++) {
int count = 0;
// Inner loop to count the frequency of arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
// Check if count of arr[i] is more
// than half the size of the array
if (count > n / 2) {
return arr[i];
}
}
// If no majority element found, return -1
return -1;
}
int main() {
vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
cout << majorityElement(arr) << endl;
return 0;
}
C
#include <stdio.h>
int majorityElement(int arr[], int n) {
// Loop to consider each element as
// a candidate for majority
for (int i = 0; i < n; i++) {
int count = 0;
// Inner loop to count the frequency of arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
// Check if count of arr[i] is more
// than half the size of the array
if (count > n / 2) {
return arr[i];
}
}
// If no majority element found, return -1
return -1;
}
int main() {
int arr[] = {1, 1, 2, 1, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", majorityElement(arr, n));
return 0;
}
Java
class GfG {
static int majorityElement(int[] arr) {
int n = arr.length;
// Loop to consider each element as
// a candidate for majority
for (int i = 0; i < n; i++) {
int count = 0;
// Inner loop to count the frequency of arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
// Check if count of arr[i] is more
// than half the size of the array
if (count > n / 2) {
return arr[i];
}
}
// If no majority element found, return -1
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
System.out.println(majorityElement(arr));
}
}
Python
def majorityElement(arr):
n = len(arr)
# Loop to consider each element as
# a candidate for majority
for i in range(n):
count = 0
# Inner loop to count the frequency of arr[i]
for j in range(n):
if arr[i] == arr[j]:
count += 1
# Check if count of arr[i] is more
# than half the size of the array
if count > n // 2:
return arr[i]
# If no majority element found, return -1
return -1
if __name__ == "__main__":
arr = [1, 1, 2, 1, 3, 5, 1]
print(majorityElement(arr))
C#
using System;
class GfG {
static int majorityElement(int[] arr) {
int n = arr.Length;
// Loop to consider each element
// as a candidate for majority
for (int i = 0; i < n; i++) {
int count = 0;
// Inner loop to count the frequency of arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
// Check if count of arr[i] is more
// than half the size of the array
if (count > n / 2) {
return arr[i];
}
}
// If no majority element found, return -1
return -1;
}
static void Main(string[] args) {
int[] arr = { 1, 1, 2, 1, 3, 5, 1 };
Console.WriteLine(majorityElement(arr));
}
}
Javascript
function majorityElement(arr) {
let n = arr.length;
// Loop to consider each element as
// a candidate for majority
for (let i = 0; i < n; i++) {
let count = 0;
// Inner loop to count the frequency of arr[i]
for (let j = 0; j < n; j++) {
if (arr[i] === arr[j]) {
count++;
}
}
// Check if count of arr[i] is more than
// half the size of the array
if (count > n / 2) {
return arr[i];
}
}
// If no majority element found, return -1
return -1;
}
// Driver Code
let arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));
[Better Approach - 1] Using Sorting - O(nlog(n)) Time and O(1) Space
The idea is to sort the array so that similar elements are next to each other. Once sorted, go through the array and keep track of how many times each element appears. When you encounter a new element, check if the count of the previous element was more than half the total number of elements in the array. If it was, that element is the majority and should be returned. If no element meets this requirement, no majority element exists.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int majorityElement(vector<int>& arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
// Potential majority element
int candidate = arr[n/2];
// Count how many times candidate appears
int count = 0;
for (int num : arr) {
if (num == candidate) {
count++;
}
}
if (count > n/2) {
return candidate;
}
// No majority element
return -1;
}
int main() {
vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
cout << majorityElement(arr);
return 0;
}
Java
import java.util.Arrays;
class GfG {
static int majorityElement(int[] arr) {
int n = arr.length;
Arrays.sort(arr);
// Potential majority element
int candidate = arr[n/2];
// Count how many times candidate appears
int count = 0;
for (int num : arr) {
if (num == candidate) {
count++;
}
}
if (count > n/2) {
return candidate;
}
// No majority element
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
System.out.println(majorityElement(arr));
}
}
Python
def majorityElement(arr):
n = len(arr)
arr.sort()
# Potential majority element
candidate = arr[n // 2]
# Count how many times candidate appears
count = 0
for num in arr:
if num == candidate:
count += 1
if count > n // 2:
return candidate
else:
return -1
if __name__ == "__main__":
arr = [1, 1, 2, 1, 3, 5, 1]
print(majorityElement(arr))
C#
using System;
class GfG {
static int majorityElement(int[] arr) {
int n = arr.Length;
Array.Sort(arr);
// Potential majority element
int candidate = arr[n / 2];
// Count how many times candidate appears
int count = 0;
foreach (int num in arr) {
if (num == candidate) {
count++;
}
}
if (count > n / 2) {
return candidate;
} else {
return -1;
}
}
static void Main() {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
Console.WriteLine(majorityElement(arr));
}
}
Javascript
function majorityElement(arr) {
let n = arr.length;
arr.sort((a, b) => a - b);
// Potential majority element
let candidate = arr[Math.floor(n / 2)];
// Count how many times candidate appears
let count = 0;
for (let num of arr) {
if (num === candidate) {
count++;
}
}
if (count > Math.floor(n / 2)) {
return candidate;
} else {
return -1;
}
}
// Driver Code
let arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));
[Better Approach - 2] Using Hashing - O(n) Time and O(n) Space
The idea is to use a hash map to track frequencies and identify the majority element in a single pass.
Step By Step Implementations:
- Initialize an empty hash map.
- Traverse the array and update the count of each element.
- After each update, check if the count exceeds n / 2.
- If found, return that element immediately.
- If no such element exists after the loop, return -1.
C++
#include <iostream>
#include<unordered_map>
#include<vector>
using namespace std;
int majorityElement(vector<int> &arr) {
int n = arr.size();
unordered_map<int, int> countMap;
// Traverse the array and count occurrences using the hash map
for (int num : arr) {
countMap[num]++;
// Check if current element count exceeds n / 2
if (countMap[num] > n / 2) {
return num;
}
}
// If no majority element is found, return -1
return -1;
}
int main() {
vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
cout << majorityElement(arr) << endl;
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
class GfG {
static int majorityElement(int[] arr) {
int n = arr.length;
Map<Integer, Integer> countMap = new HashMap<>();
// Traverse the array and count occurrences using the hash map
for (int num : arr) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
// Check if current element count exceeds n / 2
if (countMap.get(num) > n / 2) {
return num;
}
}
// If no majority element is found, return -1
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
System.out.println(majorityElement(arr));
}
}
Python
from collections import defaultdict
def majorityElement(arr):
n = len(arr)
countMap = defaultdict(int)
# Traverse the list and count occurrences using the hash map
for num in arr:
countMap[num] += 1
# Check if current element count exceeds n / 2
if countMap[num] > n / 2:
return num
# If no majority element is found, return -1
return -1
if __name__ == "__main__":
arr = [1, 1, 2, 1, 3, 5, 1]
print(majorityElement(arr))
C#
using System;
using System.Collections.Generic;
class GfG {
static int majorityElement(int[] arr) {
int n = arr.Length;
Dictionary<int, int> countMap = new Dictionary<int, int>();
// Traverse the array and count occurrences using the hash map
foreach (int num in arr) {
if (countMap.ContainsKey(num))
countMap[num]++;
else
countMap[num] = 1;
// Check if current element count exceeds n / 2
if (countMap[num] > n / 2) {
return num;
}
}
// If no majority element is found, return -1
return -1;
}
public static void Main() {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
Console.WriteLine(majorityElement(arr));
}
}
Javascript
function majorityElement(arr) {
const n = arr.length;
const countMap = new Map();
// Traverse the array and count occurrences using the hash map
for (const num of arr) {
countMap.set(num, (countMap.get(num) || 0) + 1);
// Check if current element count exceeds n / 2
if (countMap.get(num) > n / 2) {
return num;
}
}
// If no majority element is found, return -1
return -1;
}
// Driver Code
const arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));
[Expected Approach] Using Moore's Voting Algorithm - O(n) Time and O(1) Space
The idea is to use the Boyer-Moore Voting Algorithm to efficiently find a potential majority element by canceling out different elements. If a majority element exists, it will remain as the candidate. Then verify it.
This is a two-step process:
- The first step gives the element that may be the majority element in the array. If there is a majority element in an array, then this step will definitely return majority element, otherwise, it will return candidate for majority element.
- Check if the element obtained from the above step is the majority element. This step is necessary as there might be no majority element.
Step By Step Approach:
- Initialize a candidate variable and a count variable.
- Traverse the array once:
-> If count is zero, set the candidate to the current element and set count to one.
-> If the current element equals the candidate, increment count.
-> If the current element differs from the candidate, decrement count. - Traverse the array again to count the occurrences of the candidate.
- If the candidate's count is greater than n / 2, return the candidate as the majority element.
C++
#include <iostream>
#include <vector>
using namespace std;
int majorityElement(vector<int>& arr) {
int n = arr.size();
int candidate = -1;
int count = 0;
// Find a candidate
for (int num : arr) {
if (count == 0) {
candidate = num;
count = 1;
}
else if (num == candidate) {
count++;
}
else {
count--;
}
}
// Validate the candidate
count = 0;
for (int num : arr) {
if (num == candidate) {
count++;
}
}
// If count is greater than n / 2, return the
// candidate; otherwise, return -1
if (count > n / 2) {
return candidate;
} else {
return -1;
}
}
int main() {
vector<int> arr = {1, 1, 2, 1, 3, 5, 1};
cout << majorityElement(arr) << endl;
return 0;
}
C
#include <stdio.h>
int majorityElement(int arr[], int n) {
int candidate = -1;
int count = 0;
// Find a candidate
for (int i = 0; i < n; i++) {
if (count == 0) {
candidate = arr[i];
count = 1;
}
else if (arr[i] == candidate) {
count++;
}
else {
count--;
}
}
// Validate the candidate
count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == candidate) {
count++;
}
}
// If count is greater than n / 2, return
// the candidate; otherwise, return -1
if (count > n / 2) {
return candidate;
} else {
return -1;
}
}
int main() {
int arr[] = {1, 1, 2, 1, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", majorityElement(arr, n));
return 0;
}
Java
class GfG {
static int majorityElement(int[] arr) {
int n = arr.length;
int candidate = -1;
int count = 0;
// Find a candidate
for (int num : arr) {
if (count == 0) {
candidate = num;
count = 1;
}
else if (num == candidate) {
count++;
}
else {
count--;
}
}
// Validate the candidate
count = 0;
for (int num : arr) {
if (num == candidate) {
count++;
}
}
// If count is greater than n / 2, return
// the candidate; otherwise, return -1
if (count > n / 2) {
return candidate;
} else {
return -1;
}
}
public static void main(String[] args) {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
System.out.println(majorityElement(arr));
}
}
Python
def majorityElement(arr):
n = len(arr)
candidate = -1
count = 0
# Find a candidate
for num in arr:
if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1
# Validate the candidate
count = 0
for num in arr:
if num == candidate:
count += 1
# If count is greater than n / 2, return
# the candidate; otherwise, return -1
if count > n // 2:
return candidate
else:
return -1
if __name__ == "__main__":
arr = [1, 1, 2, 1, 3, 5, 1]
print(majorityElement(arr))
C#
using System;
class GfG {
static int majorityElement(int[] arr) {
int n = arr.Length;
int candidate = -1;
int count = 0;
// Find a candidate
foreach (int num in arr) {
if (count == 0) {
candidate = num;
count = 1;
} else if (num == candidate) {
count++;
} else {
count--;
}
}
// Validate the candidate
count = 0;
foreach (int num in arr) {
if (num == candidate) {
count++;
}
}
// If count is greater than n / 2, return
// the candidate; otherwise, return -1
if (count > n / 2) {
return candidate;
} else {
return -1;
}
}
static void Main() {
int[] arr = {1, 1, 2, 1, 3, 5, 1};
Console.WriteLine(majorityElement(arr));
}
}
Javascript
function majorityElement(arr) {
const n = arr.length;
let candidate = -1;
let count = 0;
// Find a candidate
for (const num of arr) {
if (count === 0) {
candidate = num;
count = 1;
}
else if (num === candidate) {
count++;
}
else {
count--;
}
}
// Validate the candidate
count = 0;
for (const num of arr) {
if (num === candidate) {
count++;
}
}
// If count is greater than n / 2, return
// the candidate; otherwise, return -1
if (count > n / 2) {
return candidate;
} else {
return -1;
}
}
// Driver Code
const arr = [1, 1, 2, 1, 3, 5, 1];
console.log(majorityElement(arr));
Solving the Majority Element Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem