FastPrepShortest Subarray Covering an Integer Range

Shortest Subarray Covering an Integer Range

Marshall Wace logoMarshall Wace● MediumNEW GRADOA

Problem statement

Given an integer array A and integers L and R, find the shortest consecutive subarray containing every integer from L through R, inclusive.

Elements outside that range may appear in the chosen subarray. Repeated values do not replace a missing required integer.

Return the length of the shortest qualifying subarray, or -1 if none exists.

Function

solution(A: int[], L: int, R: int) → int

Examples

Example 1

A = [7,1,4,2,3]L = 1R = 3return = 4

The subarray [1,4,2,3] contains 1, 2 and 3. The outside-range value 4 remains between required elements, so its length is 4.

Example 2

A = [1,1,2]L = 1R = 3return = -1

No subarray contains the required value 3.

Example 3

A = [9,4,4,8]L = 4R = 4return = 1

The required range contains only 4. Either occurrence forms a valid length-one subarray.

Constraints

  • 1 <= A.length <= 200000.
  • -10^9 <= A[i] <= 10^9.
  • -10^9 <= L <= R <= 10^9.

More Marshall Wace problems

See Marshall Wace hiring insights
Saved
public int solution(int[] A, int L, int R) {
    // Write your solution here.
}
A[7,1,4,2,3]
L1
R3
expected4
Checking account…