Skip to content

Commit 3be067a

Browse files
committed
Added Moore'es Voting Algorithm
1 parent 5048028 commit 3be067a

File tree

1 file changed

+250
-0
lines changed

1 file changed

+250
-0
lines changed
Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,250 @@
1+
---
2+
id: moores-voting-algorithm
3+
title: Moore's Voting Algorithm
4+
sidebar_label: Moore's Voting Algorithm
5+
tags: [python, java, c++, javascript, programming, algorithms, subarray, array, tutorial, in-depth , Hash Table,Divide and Conquer,Sorting ,Counting]
6+
description: In this tutorial, we will learn about Moore's Voting Algorithm and its implementation in Python, Java, C++, and JavaScript with detailed explanations and examples.
7+
---
8+
9+
# Moore's Voting Algorithm
10+
The Boyer-Moore voting algorithm is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than `N/ 2` occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in $O(N)$ time complexity and $O(1)$ space complexity.
11+
12+
## Problem Statement
13+
Given an array nums of size n, return the majority element.
14+
The majority element is the element that appears more than `n / 2` times. You may assume that the majority element always exists in the array.
15+
16+
### Intuition
17+
- We will run a loop that will select the elements of the array one by one.
18+
- Now, for each element, we will run another loop and count its occurrence in the given array.
19+
- If any element occurs more than the floor of $(N/2)$, we will simply return it.
20+
21+
## Brute Force Approach
22+
```c++
23+
int majorityElement(vector<int> v) {
24+
//size of the given array:
25+
int n = v.size();
26+
27+
for (int i = 0; i < n; i++) {
28+
//selected element is v[i]
29+
int cnt = 0;
30+
for (int j = 0; j < n; j++) {
31+
// counting the frequency of v[i]
32+
if (v[j] == v[i]) {
33+
cnt++;
34+
}
35+
}
36+
37+
// check if frquency is greater than n/2:
38+
if (cnt > (n / 2))
39+
return v[i];
40+
}
41+
42+
return -1;
43+
}
44+
```
45+
#### Time Complexity : $O(n^2)$
46+
#### Spcae Complexity : $O(1)$
47+
## Better Approach - Hashmap
48+
#### Intuition
49+
- Use a hashmap and store as (key, value) pairs. (Can also use frequency array based on the size of nums)
50+
- Here the key will be the element of the array and the value will be the number of times it occurs.
51+
- Traverse the array and update the value of the key. Simultaneously check if the value is greater than the floor of N/2.
52+
- If yes, return the key
53+
- Else iterate forward.
54+
55+
56+
```c++
57+
int majorityElement(vector<int> v) {
58+
59+
//size of the given array:
60+
int n = v.size();
61+
62+
//declaring a map:
63+
map<int, int> mpp;
64+
65+
//storing the elements with its occurnce:
66+
for (int i = 0; i < n; i++) {
67+
mpp[v[i]]++;
68+
}
69+
70+
//searching for the majority element:
71+
for (auto it : mpp) {
72+
if (it.second > (n / 2)) {
73+
return it.first;
74+
}
75+
}
76+
77+
return -1;
78+
}
79+
```
80+
#### Time Complexity : $O(nlogn)$
81+
#### Spcae Complexity : $O(n)$
82+
83+
## Optimized Approach - Moore's Voting Algorithm
84+
#### Intuition
85+
If the array contains a majority element, its occurrence must be greater than the floor(N/2). Now, we can say that the count of minority elements and majority elements is equal up to a certain point in the array. So when we traverse through the array we try to keep track of the count of elements and the element itself for which we are tracking the count.
86+
87+
After traversing the whole array, we will check the element stored in the variable. If the question states that the array must contain a majority element, the stored element will be that one but if the question does not state so, then we need to check if the stored element is the majority element or not. If not, then the array does not contain any majority element.
88+
89+
#### Steps
90+
- Initialize 2 variables:
91+
Count – for tracking the count of element
92+
Element – for which element we are counting
93+
- Traverse through the given array.
94+
If Count is 0 then store the current element of the array as Element.
95+
If the current element and Element are the same increase the Count by 1.
96+
If they are different decrease the Count by 1.
97+
- The integer present in Element should be the result we are expecting
98+
99+
## Implementing Moore's Voting Algorithm
100+
101+
### Python Implementation
102+
103+
```python
104+
def majorityElement(arr):
105+
# Size of the given array
106+
n = len(arr)
107+
cnt = 0 # Count
108+
el = None # Element
109+
110+
# Applying the algorithm
111+
for i in range(n):
112+
if cnt == 0:
113+
cnt = 1
114+
el = arr[i]
115+
elif el == arr[i]:
116+
cnt += 1
117+
else:
118+
cnt -= 1
119+
120+
# Checking if the stored element is the majority element
121+
cnt1 = 0
122+
for i in range(n):
123+
if arr[i] == el:
124+
cnt1 += 1
125+
126+
if cnt1 > (n / 2):
127+
return el
128+
return -1
129+
```
130+
131+
### Java Implementation
132+
133+
```java
134+
import java.util.*;
135+
136+
public class tUf {
137+
public static int majorityElement(int []v) {
138+
//size of the given array:
139+
int n = v.length;
140+
int cnt = 0; // count
141+
int el = 0; // Element
142+
143+
//applying the algorithm:
144+
for (int i = 0; i < n; i++) {
145+
if (cnt == 0) {
146+
cnt = 1;
147+
el = v[i];
148+
} else if (el == v[i]) cnt++;
149+
else cnt--;
150+
}
151+
152+
//checking if the stored element
153+
// is the majority element:
154+
int cnt1 = 0;
155+
for (int i = 0; i < n; i++) {
156+
if (v[i] == el) cnt1++;
157+
}
158+
159+
if (cnt1 > (n / 2)) return el;
160+
return -1;
161+
}
162+
163+
public static void main(String args[]) {
164+
int[] arr = {2, 2, 1, 1, 1, 2, 2};
165+
int ans = majorityElement(arr);
166+
System.out.println("The majority element is: " + ans);
167+
168+
}
169+
170+
}
171+
```
172+
173+
### C++ Implementation
174+
175+
```cpp
176+
int majorityElement(vector<int> v) {
177+
178+
//size of the given array:
179+
int n = v.size();
180+
int cnt = 0; // count
181+
int el; // Element
182+
183+
//applying the algorithm:
184+
for (int i = 0; i < n; i++) {
185+
if (cnt == 0) {
186+
cnt = 1;
187+
el = v[i];
188+
}
189+
else if (el == v[i]) cnt++;
190+
else cnt--;
191+
}
192+
193+
//checking if the stored element
194+
// is the majority element:
195+
int cnt1 = 0;
196+
for (int i = 0; i < n; i++) {
197+
if (v[i] == el) cnt1++;
198+
}
199+
200+
if (cnt1 > (n / 2)) return el;
201+
return -1;
202+
}
203+
```
204+
205+
### JavaScript Implementation
206+
207+
```javascript
208+
function majorityElement(arr) {
209+
// Size of the given array
210+
let n = arr.length;
211+
let cnt = 0; // Count
212+
let el; // Element
213+
214+
// Applying the algorithm
215+
for (let i = 0; i < n; i++) {
216+
if (cnt === 0) {
217+
cnt = 1;
218+
el = arr[i];
219+
} else if (el === arr[i]) {
220+
cnt++;
221+
} else {
222+
cnt--;
223+
}
224+
}
225+
226+
// Checking if the stored element is the majority element
227+
let cnt1 = 0;
228+
for (let i = 0; i < n; i++) {
229+
if (arr[i] === el) {
230+
cnt1++;
231+
}
232+
}
233+
234+
if (cnt1 > Math.floor(n / 2)) {
235+
return el;
236+
}
237+
return -1;
238+
}
239+
240+
```
241+
242+
## Complexity Analysis
243+
#### Time Complexity : $O(n)$
244+
#### Space Complexity : $O(1)$
245+
246+
## Conclusion
247+
- Moore's Voting Algorithm concludes by returning the majority element, if it exists, otherwise, -1.
248+
249+
250+

0 commit comments

Comments
 (0)