Skip to content

Commit

Permalink
*
Browse files Browse the repository at this point in the history
  • Loading branch information
imteekay committed Jan 13, 2024
1 parent 2ccee08 commit 9f4e28e
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions coding_interviews/algoexpert/majority-element/majority-element.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Runtime: O(N^2)
// Space: O(N)

function majorityElement(array) {
let half = Math.floor(array.length / 2);

if (array.length <= 1) return array[0];

for (let i = 0; i < array.length; i++) {
let count = 1;
let number = array[i];

for (let k = i + 1; k < array.length; k++) {
if (array[k] === number) {
count++;
}

if (count > half) {
return number;
}
}
}
}

0 comments on commit 9f4e28e

Please sign in to comment.