From 4a540950a27e22deb0d936795f3a634a5c1c2e0b Mon Sep 17 00:00:00 2001 From: Behzad Ali Mohammad Zad Date: Wed, 29 May 2024 23:05:02 +0330 Subject: [PATCH] feat: add findMajorityElement challange --- README.md | 1 + .../find-majority-element.test.ts | 16 ++++++++++++++++ .../find-majority-element.ts | 9 +++++++++ 3 files changed, 26 insertions(+) create mode 100644 src/challange/array/find-majority-element/find-majority-element.test.ts create mode 100644 src/challange/array/find-majority-element/find-majority-element.ts diff --git a/README.md b/README.md index 4ae188a..0f81ff4 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/challange/array/find-majority-element/find-majority-element.test.ts b/src/challange/array/find-majority-element/find-majority-element.test.ts new file mode 100644 index 0000000..7df1e20 --- /dev/null +++ b/src/challange/array/find-majority-element/find-majority-element.test.ts @@ -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); + }); +}); diff --git a/src/challange/array/find-majority-element/find-majority-element.ts b/src/challange/array/find-majority-element/find-majority-element.ts new file mode 100644 index 0000000..673093e --- /dev/null +++ b/src/challange/array/find-majority-element/find-majority-element.ts @@ -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)]; +}