- Create a unique array without repeating numbers to avoid.
- Loop thruogh the unique array and filter the orignal array using numbers in unique array.
- if the the number of a particular number that was filtered is greater than n/2 it returns the unique number.
-
Time complexity: O(N^2)
-
Space complexity: O(N)
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]
}
}
};