[Array] Majority Element - Easy

The Majority Element problem in an array is about finding an element that shows up more than half the time in an array of size n. We call this element the majority element. We can solve this problem using different methods. Some methods are simple brute force ones, and others are better like the Boyer-Moore Voting Algorithm. When we understand what the majority element is, we can pick the best way to find it based on what we need for our application.

In this article, we will look closely at the Majority Element problem. We will go over different ways to solve it well. First, we will give an overview of the solution. Then we will check the brute force method in Java, Python, and C++. After that, we will look at a better way using HashMaps in the same languages. Finally, we will talk about the Boyer-Moore Voting Algorithm. We will also answer some common questions to help with any confusion. Here is what we will talk about:

  • [Array] Majority Element Solution Overview
  • Understanding the Majority Element Problem
  • Brute Force Approach for Majority Element in Java
  • Brute Force Approach for Majority Element in Python
  • Brute Force Approach for Majority Element in C++
  • Optimal Approach Using HashMap in Java
  • Optimal Approach Using HashMap in Python
  • Optimal Approach Using HashMap in C++
  • Boyer-Moore Voting Algorithm in Java
  • Boyer-Moore Voting Algorithm in Python
  • Boyer-Moore Voting Algorithm in C++
  • Frequently Asked Questions

If we want to learn about related topics, we can check our articles on Array Two Sum, Best Time to Buy and Sell Stock, Contains Duplicate, and Maximum Subarray for more insights.

Understanding the Majority Element Problem

The Majority Element problem is about finding an element in an array that shows up more than n/2 times. Here n is the size of the array. If we find such an element, we call it the “majority element.” We often see this problem in many algorithm challenges. We can solve it in different ways.

Key Properties:

  • If a majority element is there, it is the only one.
  • We can use brute force, hash maps, or faster methods like the Boyer-Moore Voting Algorithm.

Example:

Let’s look at an array:

[3, 2, 3]

The majority element is 3 because it comes up twice. That is more than n/2 which is 1.5.

Another example is:

[2, 2, 1, 1, 1, 2, 2]

The majority element here is 2 because it appears four times. That is more than n/2 which is 3.5.

The Majority Element problem helps us understand how to work with arrays. It also helps us with more complex problems. For example, we can use it for problems like Array - Two Sum and Array - Contains Duplicate.

Brute Force Approach for Majority Element in Java

We can find the majority element in an array using a brute force method. This means we check each element and count how many times it appears. The majority element is the one that shows up more than n/2 times in the array. Here, n is the total number of elements in the array.

Implementation

Here is a simple way to use the brute force method in Java:

public class MajorityElement {
    public static int majorityElement(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int count = 0;
            for (int j = 0; j < n; j++) {
                if (nums[j] == nums[i]) {
                    count++;
                }
            }
            if (count > n / 2) {
                return nums[i];
            }
        }
        return -1; // Return -1 if no majority element exists
    }

    public static void main(String[] args) {
        int[] nums = {2, 2, 1, 1, 1, 2, 2};
        System.out.println("Majority Element: " + majorityElement(nums)); // Output: 2
    }
}

Complexity Analysis

  • Time Complexity: O(n^2) - We have loops inside loops which makes it slow.
  • Space Complexity: O(1) - We do not use extra space except for some variables.

This brute force method is easy to understand but not good for large arrays. For faster results, we can use better methods like the HashMap method or the Boyer-Moore Voting Algorithm. If you want to learn more about efficient array problems, you can check Array - Contains Duplicate.

Brute Force Approach for Majority Element in Python

We can find the majority element in an array using a simple brute force method. This method checks each element and counts how many times it appears. The majority element is the one that appears more than n/2 times in an array of size n.

Implementation

We can implement the brute force method in Python like this:

def majority_element(nums):
    n = len(nums)
    for i in range(n):
        count = 0
        for j in range(n):
            if nums[j] == nums[i]:
                count += 1
        if count > n // 2:
            return nums[i]
    return None

Explanation

  • The outer loop goes through each element in the array.
  • The inner loop counts how many times the current element appears.
  • If the count is more than n/2, we return that element as the majority element.

Time Complexity

  • The time complexity for this method is (O(n^2)). This is because of the nested loops. It becomes slow for big datasets.

Example Usage

nums = [3, 2, 3]
result = majority_element(nums)
print(result)  # Output: 3

This brute force approach is easy to understand. But we can make it better with smarter methods, like using a HashMap or the Boyer-Moore Voting Algorithm. For more information on related array problems, we can look at Contains Duplicate and Maximum Subarray.

Brute Force Approach for Majority Element in C++

We use the brute force method to find the majority element in an array. This means we count how many times each element shows up. Then we check if any element appears more than n/2 times. Here n is the size of the array. This method takes a lot of time. It has a time complexity of O(n^2) because we use nested loops to count.

C++ Implementation

Here is a simple way to do the brute force method for finding the majority element in C++:

#include <iostream>
#include <vector>
using namespace std;

int majorityElement(vector<int>& nums) {
    int n = nums.size();
    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            if (nums[i] == nums[j]) {
                count++;
            }
        }
        if (count > n / 2) {
            return nums[i];
        }
    }
    return -1; // Return -1 if no majority element found
}

int main() {
    vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
    int result = majorityElement(nums);
    if (result != -1) {
        cout << "Majority Element: " << result << endl;
    } else {
        cout << "No Majority Element found" << endl;
    }
    return 0;
}

Explanation

We have an outer loop that goes through each element in the array. Inside, there is an inner loop that counts how many times the current element shows up. If the count is more than n/2, we return that element as the majority element. If we don’t find any majority element, we return -1.

This brute force method is easy to understand but not very fast for big datasets. If we want a better solution, we can use a HashMap or the Boyer-Moore Voting Algorithm.

Optimal Approach Using HashMap in Java

We can find the majority element in an array using a HashMap. This method is fast. It has a time complexity of O(n) and a space complexity of O(n). We count how many times each element appears in the array. Then we figure out which element shows up more than n/2 times.

Implementation

import java.util.HashMap;

public class MajorityElement {
    public static int findMajorityElement(int[] nums) {
        HashMap<Integer, Integer> countMap = new HashMap<>();
        int majorityCount = nums.length / 2;

        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
            if (countMap.get(num) > majorityCount) {
                return num;
            }
        }

        throw new IllegalArgumentException("No majority element found");
    }

    public static void main(String[] args) {
        int[] nums = {3, 2, 3};
        System.out.println("Majority Element: " + findMajorityElement(nums)); // Output: 3
    }
}

Explanation

  • HashMap Usage: We use the HashMap to keep each element as a key. The value is how many times it appears.
  • Count Check: While we go through the array, we check if the count of the current element is more than half of the size of the array (n/2). If it is, we return that element right away.
  • Exception Handling: If we do not find a majority element, we throw an exception.

This method works well for arrays where a majority element is sure to be there. For more problems about arrays, we can look at articles like Array Two Sum and Array Contains Duplicate.

Optimal Approach Using HashMap in Python

In Python, we can find the majority element quickly by using a HashMap, which is also called a dictionary. This dictionary helps us count how many times each element appears. The majority element is the one that shows up more than n/2 times in the array. Here, n is the total number of elements in the array.

Implementation

Here is how we can do this in Python:

def majorityElement(nums):
    count = {}
    majority_count = len(nums) // 2

    for num in nums:
        if num in count:
            count[num] += 1
        else:
            count[num] = 1

        if count[num] > majority_count:
            return num

    return None  # If there is no majority element

Example

Let’s look at an example array:

nums = [3, 2, 3]
print(majorityElement(nums))  # Output: 3

Complexity Analysis

  • Time Complexity: O(n), where n is the number of elements in the input array.
  • Space Complexity: O(n) in the worst case, when all elements are different.

This method works well for finding the majority element. It uses a simple scan and quick access to the dictionary. If we want to learn more about similar problems with arrays, we should check Array Two Sum and Array Contains Duplicate.

Optimal Approach Using HashMap in C++

We can find the Majority Element in an array by using a HashMap. This means we count how many times each element shows up. Then we check which element appears more than n/2 times. Here, n is the size of the array. This way is fast. It has a time complexity of O(n) and a space complexity of O(n).

C++ Implementation

#include <iostream>
#include <vector>
#include <unordered_map>

int majorityElement(std::vector<int>& nums) {
    std::unordered_map<int, int> countMap;
    int n = nums.size();
    
    for (int num : nums) {
        countMap[num]++;
        if (countMap[num] > n / 2) {
            return num;
        }
    }
    return -1; // This line is not reachable if input has a majority element.
}

int main() {
    std::vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
    std::cout << "Majority Element: " << majorityElement(nums) << std::endl;
    return 0;
}

Explanation

  • Data Structure: We use an unordered_map to keep count of each element.
  • Algorithm:
    • We go through each element in the array.
    • We add one to the count for each element in the HashMap.
    • If the count is more than n/2, we return that element as the majority element.

This method works well and is simple. It uses the features of a HashMap to find the Majority Element quickly. For more algorithms, you can check Array Best Time to Buy and Sell Stock - Easy.

Boyer-Moore Voting Algorithm in Java

The Boyer-Moore Voting Algorithm is a smart way to find the majority element in an array. It runs in O(n) time and uses O(1) space. The algorithm keeps track of a candidate for the majority element and a count to see how often it appears.

Implementation

public class MajorityElement {
    public static int findMajorityElement(int[] nums) {
        int candidate = nums[0], count = 1;

        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                candidate = nums[i];
            }
            count += (nums[i] == candidate) ? 1 : -1;
        }

        return candidate;
    }

    public static void main(String[] args) {
        int[] nums = {3, 2, 3};
        System.out.println("The majority element is: " + findMajorityElement(nums));
    }
}

Explanation

  • Initialization: We start with the first element as the candidate and set count to 1.
  • Iteration: For each next element:
    • If count is zero, we set the current element as the candidate.
    • We add or subtract from the count based on if the current element matches the candidate.
  • Result: After we go through the array, the candidate will be the majority element.

This method is fast and does not need extra data structures. It is good for large datasets. If you want to learn more about array problems, you can check out Array Two Sum.

Boyer-Moore Voting Algorithm in Python

The Boyer-Moore Voting Algorithm is a simple and fast way to find the majority element in an array. The majority element is the one that shows up more than ⌊n/2⌋ times. Here, n is the size of the array. This algorithm runs in O(n) time and uses O(1) space.

Implementation

Here is how we can implement the Boyer-Moore Voting Algorithm in Python:

def majorityElement(nums):
    candidate = None
    count = 0
    
    for num in nums:
        if count == 0:
            candidate = num
        count += (1 if num == candidate else -1)
    
    return candidate

# Example usage
nums = [3, 2, 3]
print(majorityElement(nums))  # Output: 3

Explanation

  • Candidate Selection: We go through the array and keep a count. When the count is zero, we pick the current number as our new candidate.
  • Count Adjustment: We add to the count if the current number is the candidate. If not, we take away from the count.
  • Result: The candidate we have at the end is the majority element.

This algorithm is good and popular because it is fast and easy to understand. It is a great choice for the majority element problem. If you want to learn more about working with arrays, you can check out the article on Array Two Sum.

Boyer-Moore Voting Algorithm in C++

The Boyer-Moore Voting Algorithm is a simple and fast way to find the majority element in an array. The majority element is the one that shows up more than n/2 times in an array of size n. This algorithm runs in O(n) time and uses O(1) space.

Implementation in C++

Here is a C++ code for the Boyer-Moore Voting Algorithm:

#include <iostream>
#include <vector>
using namespace std;

int majorityElement(vector<int>& nums) {
    int candidate = nums[0], count = 1;
    
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] == candidate) {
            count++;
        } else {
            count--;
            if (count == 0) {
                candidate = nums[i];
                count = 1;
            }
        }
    }
    
    // Optional step: check if the candidate is the majority element
    count = 0;
    for (int num : nums) {
        if (num == candidate) count++;
    }
    
    return count > nums.size() / 2 ? candidate : -1; // Return -1 if no majority element
}

int main() {
    vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
    cout << "Majority Element: " << majorityElement(nums) << endl;
    return 0;
}

Key Points:

  • Candidate Selection: The algorithm keeps a candidate for the majority element. It also uses a count to see how many times it appears.
  • Count Adjustment: If the current element is the same as the candidate, we add to the count. If it’s not, we subtract from the count. If the count goes to zero, we change the candidate to the current element.
  • Verification: After we find a candidate, we can check if it is really the majority element.
  • Use Cases: This algorithm works great for big datasets. It is useful when we need to save time and space.

For more information on similar array problems, check out Array Two Sum and Array Contains Duplicate.

Frequently Asked Questions

1. What is the Majority Element in an Array?

The Majority Element in an array is the element that shows up more than half the time. For example, in the array [2, 2, 1, 1, 2], the majority element is 2. This is because it shows up three times, which is more than half of the total elements. We need to know how to find the majority element. This is important for solving many problems with arrays.

2. How can I find the Majority Element using the Brute Force approach?

To find the Majority Element with the Brute Force approach, we can go through each element in the array. We count how many times each one appears. If any element’s count is more than half the length of the array, then it is the majority element. This method is easy to understand. But it has a time complexity of O(n^2), so it is not very good for big datasets. For a better way, we can look into the Optimal Approach Using HashMap.

3. What is the Boyer-Moore Voting Algorithm for finding the Majority Element?

The Boyer-Moore Voting Algorithm is a smart way to find the Majority Element in an array. It has O(n) time complexity and O(1) space complexity. It keeps track of a count and a candidate element. The algorithm goes through the array. It adds or subtracts from the count based on the current element. In the end, it finds the majority element. This method works well with large arrays.

4. How does the HashMap approach help in finding the Majority Element?

Using a HashMap helps us see how often each element appears in the array. We can go through the array and update the HashMap. This way, we can quickly find if any element’s count is more than half the length of the array. This Optimal Approach Using HashMap has O(n) time complexity and O(n) space complexity. This makes it good for medium-sized datasets. For more info, check out the article on array best time to buy and sell stock.

Some common array problems about the Majority Element are finding duplicates, maximum subarrays, and special sums. For example, checking if an array has duplicates can connect to the majority element problem. Both need us to count how often elements appear. Looking into these topics, like the array contains duplicate problem, can help us understand more about working with arrays and algorithms.

By answering these frequently asked questions, we can learn more about the Majority Element problem and different ways to solve it well.