From 9f4e28ef726b93fa6b7fa1a9d766c10ce03b5969 Mon Sep 17 00:00:00 2001 From: TK Date: Sat, 13 Jan 2024 16:35:33 -0300 Subject: [PATCH] * --- .../majority-element/majority-element.js | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 coding_interviews/algoexpert/majority-element/majority-element.js diff --git a/coding_interviews/algoexpert/majority-element/majority-element.js b/coding_interviews/algoexpert/majority-element/majority-element.js new file mode 100644 index 0000000..cd0bb35 --- /dev/null +++ b/coding_interviews/algoexpert/majority-element/majority-element.js @@ -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; + } + } + } +}