diff --git a/src/page-24/2540. Minimum Common Value/getCommon.test.ts b/src/page-24/2540. Minimum Common Value/getCommon.test.ts new file mode 100644 index 0000000..abe4374 --- /dev/null +++ b/src/page-24/2540. Minimum Common Value/getCommon.test.ts @@ -0,0 +1,17 @@ +import { getCommon } from './getCommon'; + +describe('2540. Minimum Common Value', () => { + test('getCommon', () => { + { + const nums1 = [1, 2, 3]; + const nums2 = [2, 4]; + expect(getCommon(nums1, nums2)).toBe(2); + } + + { + const nums1 = [1, 2, 3, 6]; + const nums2 = [2, 3, 4, 5]; + expect(getCommon(nums1, nums2)).toBe(2); + } + }); +}); diff --git a/src/page-24/2540. Minimum Common Value/getCommon.ts b/src/page-24/2540. Minimum Common Value/getCommon.ts new file mode 100644 index 0000000..041d649 --- /dev/null +++ b/src/page-24/2540. Minimum Common Value/getCommon.ts @@ -0,0 +1,23 @@ +type getCommon = (nums1: number[], nums2: number[]) => number; + +/** + * Accepted + */ +export const getCommon: getCommon = (nums1, nums2) => { + let pointer1 = 0; + let pointer2 = 0; + + while (pointer1 < nums1.length && pointer2 < nums2.length) { + if (nums1[pointer1] === nums2[pointer2]) { + return nums1[pointer1]; + } + + if (nums1[pointer1] < nums2[pointer2]) { + pointer1 += 1; + } else { + pointer2 += 1; + } + } + + return -1; +};