Given two arrays of numbers and where each number is or , the fastest algorithm to find the largest span such that or report that there is not such span,
View worked solution
Answer: C
The problem asks us to find the largest span such that:
This can be rewritten as:
Let . Since , the value of can only be , , or .
Let be the prefix sum of array up to index :
The condition is equivalent to:
To find the largest span where , we want to maximize . This means for each unique prefix sum value, we want to find its first occurrence and its last occurrence.
Algorithm Steps:
- Compute the prefix sums . Since , the prefix sum must lie in the range .
- Initialize an auxiliary array
first_occurrenceof size with to store the first index at which each prefix sum value is seen. (We can map the range to by adding an offset of ). - Traverse the prefix sums from to :
- If
first_occurrence[S_p]is , set it to . - Otherwise, a span with sum exists from index to . The length of this span is . Update the maximum span length if this is larger than the current maximum.
- If
Complexity Analysis:
- Time Complexity: We perform a single pass over the array of size . Each lookup and update in the auxiliary array takes time. Thus, the total time complexity is .
- Space Complexity: The auxiliary array of size requires extra space.
Therefore, the fastest algorithm takes time and space.
Free practice · Your answers on this page are not saved.
