Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add findMajorityElement challange #45

Merged
merged 1 commit into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ This repository aims to provide a comprehensive collection of algorithms, data s
- [Find missing numbers](src/challange/array/find-missing-numbers/find-missing-numbers.ts)
- [Find max subarray](src/challange/array/find-max-subarray/find-max-subarray.ts)
- [Max profit](src/challange/array/max-profit/max-profit.ts)
- [Find majority element](src/challange/array/find-majority-element/find-majority-element.ts)

Please note that the repository is still a work in progress, and new algorithms and patterns will be added over time.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { findMajorityElement } from "./find-majority-element";

describe("findMajorityElement", () => {
it("returns the majority element when it exists", () => {
expect(findMajorityElement([3, 2, 3])).toBe(3);
expect(findMajorityElement([2, 2, 1, 1, 1, 2, 2])).toBe(2);
});

it("handles array with a single element", () => {
expect(findMajorityElement([1])).toBe(1);
});

it("handles array with all elements being the same", () => {
expect(findMajorityElement([1, 1, 1, 1])).toBe(1);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Given an array of integers, find the majority element in the array.
* @param arr - the given array
* @returns the majority element if it exists, otherwise undefined;
*/
export function findMajorityElement(arr: number[]): number {
arr.sort();
return arr[Math.floor(arr.length / 2)];
}
Loading