Skip to content

Commit

Permalink
Another solution to "Find the Prefix Common Array of Two Arrays" problem
Browse files Browse the repository at this point in the history
  • Loading branch information
dkoval committed Jan 14, 2025
1 parent da581c2 commit 26fe2fe
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 26fe2fe

Please sign in to comment.