Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jianminchen/b1bc4836a0b7d1564910a9f27011e15f to your computer and use it in GitHub Desktop.
Save jianminchen/b1bc4836a0b7d1564910a9f27011e15f to your computer and use it in GitHub Desktop.
Find shortest subarray with target array
/*
830pm
brute force
target [1,2,3]
arr[1,1,1,2,2,2,3,1,2,3]
i j
arr [3,2,3]
arr[1,1,1,2,2,2,3]
i j
X find shortest subarray that has all target numbers in same order
find shortest subarray length
*/
/*
JUlia's analysis:
array is not sorted
target - not duplicate, unique, ascending -> any order
Find shortest subarray which has all target numbers in the same order.
Brute force:
how many subarray - start position firstIndex/ endIndex, containing 1, 2, 3,
first one, second one - 2, third one is 3
O(n^2) -> go through subarray once -> iterate target -> first number -> ..
O(n)
-> O(n^3)
shortest one -> find shortest length /
Improve this algorithm:
*/
public static int FindShortestSubArrayContainingAllKeys(int[] numbers, int[] target)
{
if(numbers == null || target == null || numbers.Length < target.Length)
return -1;
var nLength = numbers.Length;
var tLength = target.Length;
var minLength = Int.MaxValue;
for(int start = 0; start < nLength - tLength + 1; start++) // 2
{
if(numbers[start] != target[0])
continue;
// subarray start -> end
// target [1,2,3]
//arr[1,1,1,2,2,2,3,1,2,3]
// i j
//arr[1,1,1,2,2,2,3]
// i j
int tIndex = 0;
int tStart = 0;
int index = start;
while(index >= start && index < nLength)
{
var current = numbers[index];
if(current == target[tIndex])
{
tIndex++;
}
if(tIndex == 1)
tStart = index;
index++;
if(tIndex == tLength)
{
// record length - compare to minimum length
var currentLength = index - tStart;
minLength = currentLength < minLength? currentLength : minLength;
}
}
}
return minLength == Int.MaxValue? -1 : minLength;
}
}
Time complexity: (29 minutes)
should be O(n^2)
Brent hint:
for(int i=0;i<arr.length; i++)
if(arr[i]==target[0])
for(int j=i;j<arr.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment