diff --git a/src/leetcode/merge-sorted-array/main.spec.ts b/src/leetcode/merge-sorted-array/main.spec.ts new file mode 100644 index 0000000..dbe01a9 --- /dev/null +++ b/src/leetcode/merge-sorted-array/main.spec.ts @@ -0,0 +1,31 @@ +/** + * @copyright NHCarrigan + * @license Naomi's Public License + * @author Naomi Carrigan + */ + +import { describe, it, expect } from "vitest"; +import { merge } from "./main.js"; + +describe("merge", () => { + it("should merge the two arrays", () => { + const nums1 = [ 1, 2, 3, 0, 0, 0 ]; + const nums2 = [ 2, 5, 6 ]; + merge(nums1, nums2); + expect(nums1).toStrictEqual([ 1, 2, 2, 3, 5, 6 ]); + }); + + it("should merge the two arrays when the first array is empty", () => { + const nums1 = [ 0 ]; + const nums2 = [ 1 ]; + merge(nums1, nums2); + expect(nums1).toStrictEqual([ 1 ]); + }); + + it("should merge the two arrays when the second array is empty", () => { + const nums1 = [ 1, 2, 3, 0, 0, 0 ]; + const nums2 = [ 2, 5, 6 ]; + merge(nums1, nums2); + expect(nums1).toStrictEqual([ 1, 2, 2, 3, 5, 6 ]); + }); +}); diff --git a/src/leetcode/merge-sorted-array/main.ts b/src/leetcode/merge-sorted-array/main.ts new file mode 100644 index 0000000..ce20767 --- /dev/null +++ b/src/leetcode/merge-sorted-array/main.ts @@ -0,0 +1,25 @@ +/** + * @copyright NHCarrigan + * @license Naomi's Public License + * @author Naomi Carrigan + */ + +/** + * Mutates the first array to merge the second array into it. + * Returns nothing because LeetCode fucking wants you to mutate a param which is a terrible terrible idea. + * @param nums1 - The first array to merge into. + * @param nums2 - The second array to merge into the first. + * @see https://leetcode.com/problems/merge-sorted-array + */ +const merge = (nums1: Array, nums2: Array): void => { + while (nums2.length > 0) { + nums1.pop(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- We assert it is not undefined immediately above this. But because we cannot use a variable, TypeScript doesn't narrow the type. + nums1.unshift(nums2.pop()!); + } + nums1.sort((a, b) => { + return a - b; + }); +}; + +export { merge };