πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- sort the input array
- return the element at n/2 position which is guaranteed to be the majority element

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

Sorting Solution:
	- sort the input array
	- return the element at n/2 position which is guaranteed to be the majority element

Hashmap Solution:
	- create a hashmap where the key is the number and the value is the frequency
	- if the frequency of a given number exceeds n/2, return that number

Boyer-Moore Voting Algorithm:
	- Traverse the array while maintaining a `count` and a `candidate`.
	- If `count` is 0, set the current element as the `candidate`.
	- If the current element matches the `candidate`, increment the `count`. Otherwise, decrement it.

βŒ› Complexity Analysis

Sorting:
	Time Complexity: O(n log n) due to the use of comparison based sorting
	Space Complexity: O(1)

Hashmap:
	Time Complexity: O(n)
	Space Complexity: O(n) due to the auxilary space used to store frequencies in a map

Boyer-Moore:
	Time Complexity: O(n)
	Space Complexity: O(1)

πŸ’» Implementation of Solution (Sorting)

class Solution {
 
public:
Β  Β  int majorityElement(vector<int>& nums) {
Β  Β  Β  Β  int n = nums.size();
Β  Β  Β  Β  sort(nums.begin(), nums.end());
Β  Β  Β  Β  return nums[n/2];
Β  Β  }
};

πŸ’» Implementation of Solution (Hashmap)

int majorityElement(vector<int>& nums) {
    unordered_map<int, int> count;
    int n = nums.size();
    for (int num : nums) {
        count[num]++;
        if (count[num] > n / 2) {
            return num;
        }
    }
    return -1; // Should not reach here if majority element is guaranteed
}

πŸ’» Implementation of Solution (Boyer-Moore)

int majorityElement(vector<int>& nums) {
    int candidate = nums[0], count = 0;
    for (int num : nums) {
        if (count == 0) {
            candidate = num;
        }
        count += (num == candidate) ? 1 : -1;
    }
    return candidate; // No need to verify if a majority is guaranteed
}