feat: add merge sorted array solution
Node.js CI / Lint and Test (push) Successful in 22s

This commit is contained in:
2025-12-03 11:50:57 -08:00
parent f89d010f61
commit 0eceaee426
2 changed files with 56 additions and 0 deletions
@@ -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 ]);
});
});
+25
View File
@@ -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<number>, nums2: Array<number>): 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 };