Skip to content

Commit

Permalink
Majority element exercise (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
soonick authored Aug 18, 2024
1 parent 0f37e49 commit dd2101e
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
19 changes: 19 additions & 0 deletions data-structures-and-algorithms/majority-element/answer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Majority Element

Find the majority element in a given array. The majority element in an array of size n is an element that appears more than n/2 times.

Examples:

```
Input : arr = [3, 9, 2, 9, 2, 9, 9]
Output : 9
Explanation: n = 7. 9 appear more 4 times which is more than 7/2 times
Input : arr = [3]
Output : 3
Explanation: Appears more than n/2 times
Input : arr = [3, 3, 4, 2, 4, 4, 2, 4]
Output : null
Explanation: There is no element whose frequency is greater than n/2
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const assert = require('assert');

function majorityElement(input) {
const found = {};
input.forEach(n => {
if (found[n]) {
found[n]++;
} else {
found[n] = 1;
}
});

const minSize = input.length / 2;
for (k in found) {
if (found[k] > minSize) {
return k;
}
};

return null;
}

assert.equal(majorityElement([3, 9, 2, 9, 2, 9, 9]), 9);
assert.equal(majorityElement([3]), 3);
assert.equal(majorityElement([3, 3, 4, 2, 4, 4, 2, 4]), null);

console.log("All assertions passed!");
19 changes: 19 additions & 0 deletions data-structures-and-algorithms/majority-element/execise/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Majority Element

Find the majority element in a given array. The majority element in an array of size n is an element that appears more than n/2 times.

Examples:

```
Input : arr = [3, 9, 2, 9, 2, 9, 9]
Output : 9
Explanation: n = 7. 9 appear more 4 times which is more than 7/2 times
Input : arr = [3]
Output : 3
Explanation: Appears more than n/2 times
Input : arr = [3, 3, 4, 2, 4, 4, 2, 4]
Output : null
Explanation: There is no element whose frequency is greater than n/2
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const assert = require('assert');

function majorityElement(input) {
}

assert.equal(majorityElement([3, 9, 2, 9, 2, 9, 9]), 9);
assert.equal(majorityElement([3]), 3);
assert.equal(majorityElement([3, 3, 4, 2, 4, 4, 2, 4]), null);

console.log("All assertions passed!");

0 comments on commit dd2101e

Please sign in to comment.