FastPrepLongest Common Contiguous Subarray

Longest Common Contiguous Subarray

Coinbase logoCoinbase● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given arr1 and arr2, return a longest common contiguous subarray. Its values must occur consecutively and in the same order in both arrays; skipping an element is not allowed.

For this exercise, assume the inputs contain integers and return the selected values, rather than only the length. If several longest occurrences exist, choose the smallest starting index in arr1, then the smallest starting index in arr2.

For this exercise, assume an empty array is returned when no nonempty common subarray exists, including when either input is empty. Preserve signed values and repeated elements.

Function

longestCommonSubarray(arr1: int[], arr2: int[]) → int[]

Examples

Example 1

arr1 = [1,2,3,2,1]arr2 = [3,2,1,4,7]return = [3,2,1]

This authored fixture returns the three-element contiguous run, rather than a subsequence or only its length.

Example 2

arr1 = [4,5,9,1,2]arr2 = [1,2,8,4,5]return = [4,5]

This authored tie chooses [4,5], whose occurrence starts earlier in the first array.

Example 3

arr1 = [-1,0,-1,2]arr2 = [8,-1,0,-1,3]return = [-1,0,-1]

This authored fixture preserves negative values, zero and repeated values in the returned run.

Constraints

  • For this exercise, assume 0 <= arr1.length, arr2.length <= 500.
  • For this exercise, assume every element is an integer from -1000 through 1000.

More Coinbase problems

See Coinbase hiring insights
public int[] longestCommonSubarray(int[] arr1, int[] arr2) {
    // Write your code here.
    return new int[0];
}
arr1[1,2,3,2,1]
arr2[3,2,1,4,7]
expected[3,2,1]
Checking account…