Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created January 23, 2026 14:17
Show Gist options
  • Select an option

  • Save Ephraimiyanda/ac88d9a8efeb0f4c993bd9c88cc831ef to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/ac88d9a8efeb0f4c993bd9c88cc831ef to your computer and use it in GitHub Desktop.
Majority Element

Approach

  1. Create a unique array without repeating numbers to avoid.
  2. Loop thruogh the unique array and filter the orignal array using numbers in unique array.
  3. if the the number of a particular number that was filtered is greater than n/2 it returns the unique number.

Complexity

  • Time complexity: O(N^2)

  • Space complexity: O(N)

Code

function majorityElement(nums: number[]): number {
    let n = nums.length
    let uniqueArr= [...new Set(nums)]
    for (let i = 0; i < uniqueArr.length; i++) {
        let size = nums.filter((num) => num === uniqueArr[i]).length
        if (size > n / 2) {
            return uniqueArr[i]
        }
    }
};
scrnli_OjmTTmF8gY5H08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment