This was asked to my friend in Chargebee Internship OA yesterday. I have my test scheduled for tomorrow, can you someone help me.
You are given 2 arrays A[a1, a2, ......, aN] and B[b1, b2, ....., bM] of length N and M respectively. Array A corresponds to Alice's array and array B corresponds to Bob's array. Alice wants to check the number of Alice's subarray which matches Bob's array. Alice's definition of a match is as follows.
- She takes her array, and for every subarray of length M-1, she checks if it is equal to any permutation of Bob's
array. If any permutation of Bob's array is equal to Alice's subarray of length M1, a match is found corresponding
to that subarray.
Bob's array is restored.
She does steps 1-2 till she has selected-deleted-restored every element from Bob's array once.
Task
Determine all the distinct starting indexes of Alice's subarray in ascending order, which matched Bob's array. If no subarray matched with Bob's array, -1 should be printed.
Notes
Example
Assumptions
N=5
A = [1, 2, 2, 1, 1]
B = [1, 2, 1]
Approach
Function description
Complete the function solve provided in the editor. This function takes the following 4 parameters:
The function's return type is an array, which should contain the starting indices of Alice's subarray, which matched with Bob's array in ascending order. If no subarray matched with Bob's array, it should contain -1.
Input format
Note:
This is the input format that you must use to provide custom input (available above the Compile and Test button).
Output Format
For each test case, print a line containing space-separated starting indices of Alice's subarray, which matched Bob's array in ascending order, and if no match is found, -1 should be printed.
Constraints
I don't remember the constraints, will update when I get them.
It would be a great help if u provide the range of every element of a[i] and b[i] and the constraints (n,m)
Assuming test cases are not that tight :
Let's Understand the problem more clearly :
Solution :
Let's break down the problem a bit.
We'll first create a count array for all subarrays of size M-1. We'll have a total of M-1 count arrays in order.
Count array is nothing but an array storing the count of each element in that subarray. Let the array be 'count', then count[i] is the count of element i.
We'll create similar count arrays for the second array after removing each element one by one. Then see in which position this count array is in the previously created count array list. That's the index to be added.
Just a followup comment, above approach which is O(N x M) solution, can be extended directly to O(N+M) solution by using rolling-hash. But that is overkill and not the best solution.
Fortunately, a very simple O(N+M) solution exists.
Hint: Exploit the fact that you are only deleting exactly 1 element from Bob's Array!