From 26fe2fe232040fc91bc1872950fdd953a83ebbc8 Mon Sep 17 00:00:00 2001 From: dkoval Date: Tue, 14 Jan 2025 21:27:11 +0100 Subject: [PATCH] Another solution to "Find the Prefix Common Array of Two Arrays" problem --- .../FindPrefixCommonArrayOfTwoArrays.java | 25 +++++++++++++++++++ .../FindPrefixCommonArrayOfTwoArraysTest.kt | 11 ++++++++ 2 files changed, 36 insertions(+) diff --git a/src/main/java/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArrays.java b/src/main/java/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArrays.java index f2da989f..849c50ff 100644 --- a/src/main/java/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArrays.java +++ b/src/main/java/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArrays.java @@ -58,4 +58,29 @@ public int[] findThePrefixCommonArray(int[] A, int[] B) { return ans; } } + + // O(N) time | O(N) space + class FindPrefixCommonArrayOfTwoArraysRev2 implements FindPrefixCommonArrayOfTwoArrays { + + @Override + public int[] findThePrefixCommonArray(int[] A, int[] B) { + final var n = A.length; + + final var ans = new int[n]; + // 1 <= A[i], B[i] <= n + final var counts = new int[n + 1]; + for (var i = 0; i < n; i++) { + if (++counts[A[i]] == 2) { + ans[i]++; + } + + if (++counts[B[i]] == 2) { + ans[i]++; + } + + ans[i] += (i > 0) ? ans[i - 1] : 0; + } + return ans; + } + } } diff --git a/src/test/kotlin/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArraysTest.kt b/src/test/kotlin/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArraysTest.kt index 1499280b..7ebecd6c 100644 --- a/src/test/kotlin/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArraysTest.kt +++ b/src/test/kotlin/com/github/dkoval/leetcode/challenge/FindPrefixCommonArrayOfTwoArraysTest.kt @@ -1,6 +1,7 @@ package com.github.dkoval.leetcode.challenge import com.github.dkoval.leetcode.challenge.FindPrefixCommonArrayOfTwoArrays.FindPrefixCommonArrayOfTwoArraysRev1 +import com.github.dkoval.leetcode.challenge.FindPrefixCommonArrayOfTwoArrays.FindPrefixCommonArrayOfTwoArraysRev2 import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Nested import org.junit.jupiter.api.extension.ExtensionContext @@ -37,6 +38,16 @@ internal class FindPrefixCommonArrayOfTwoArraysTest { FindPrefixCommonArrayOfTwoArraysRev1().test(A, B, expected) } } + + @Nested + inner class FindPrefixCommonArrayOfTwoArraysRev2Test { + + @ParameterizedTest + @ArgumentsSource(InputArgumentsProvider::class) + fun `should return the prefix common array of A and B`(A: IntArray, B: IntArray, expected: IntArray) { + FindPrefixCommonArrayOfTwoArraysRev2().test(A, B, expected) + } + } } private fun FindPrefixCommonArrayOfTwoArrays.test(A: IntArray, B: IntArray, expected: IntArray) {