This question is one of the prep questions provided by Meta(previously facebook) for candidates to get prepared for the interview. The question statement is as follows:
You are given an array arr of N integers. For each index i, you are required to determine the number of contiguous subarrays that fulfill the following conditions:
- The value at index i must be the maximum element in the contiguous subarrays, and
- These contiguous subarrays must either start from or end on index i.
Input
Array arr is a non-empty list of unique integers that range between 1 to 1,000,000,000
Size N is between 1 and 1,000,000
Output
An array where each index i contains an integer denoting the maximum number of contiguous subarrays of arr[i]
Example:
arr = [3, 4, 1, 6, 2]
output = [1, 3, 1, 5, 1]
Explanation:
- For index 0 - [3] is the only contiguous subarray that starts (or ends) with 3, and the maximum value in this subarray is 3.
- For index 1 - [4], [3, 4], [4, 1]
- For index 2 - [1]
- For index 3 - [6], [6, 2], [1, 6], [4, 1, 6], [3, 4, 1, 6]
- For index 4 - [2]
So, the answer for the above input is [1, 3, 1, 5, 1]
The simple solution for this question is to traverse the array, and for each element, expand left to find all valid subarrays and expand right to find all valid subarrays. The runtime complexity of this approach is O(n^2), which is not ideal.
After some observation, we would find that we can look for valid subarrays in two separate traversals of the array. We first traverse from left to right to find valid subarrays with each element as the ending element in the subarrays. Then, we traverse from right to left to find valid subarrays with each element as the starting element in the subarrays. If we combine the two results, we get the final answer. Of course, to reduce the runtime, we also need some extra datastructures to help us record some intermediate results. Here, I used a stack to store indices of elements smaller than the current element. Note that if the input array is [1,2,3,4], to count the number of subarray formed with 4 as the ending element, the stack only needs to store the index of 3. Let's look at the code for a better understanding:
def count_subarrays(arr):
# Write your code here
n = len(arr)
stack = []
left = [1] * n
for i in range(n):
while stack and arr[stack[-1]] < arr[i]:
left[i] += left[stack.pop()]
stack.append(i)
stack = []
right = [1] * n
for i in range(n-1, -1, -1):
while stack and arr[stack[-1]] < arr[i]:
right[i] += right[stack.pop()]
stack.append(i)
# the final count of subarray should be left + right - 1 because we overcounted each element twice
result = [left[i]+right[i]-1 for i in range(n)]
return result
