![]() |
VOOZH | about |
Given a length-N sequence A=(A1,A2 ,β¦,AN ) consisting of 0, 1, and 2, and a string S of size N consisting of M, E, and X. Find the sum of MEX(Ai, Aj, Ak) over all tuples of integers (i,j,k) such that 1β€i.
Example:
Input: sequenceLength = 4, sequenceA = {1, 1, 0, 2}, stringS = "MEEX"
Output: 3Input: sequenceLength = 3, sequenceA = {0, 0, 0}, stringS = "XXX"
Output: 0
Approach:
The idea is to uses the concept of MEX (Minimum Excludant), which is the smallest non-negative integer that does not exist in the given set. Exhaustively try all j such that Sj = E and calculates the number of i's with i<j, Si = M, and Ai = a, and the number of k's with k>j, Sk = X, and Ai = b. Then multiplies these counts by mex(a,Aj,b) and adds the result to the answer. This is done for all i, j, and k, and the final answer is printed.
Steps:
Below is the implementation of the above approach:
3
Time complexity: O(N), where N is the length of the sequence A and the string S. This is because the solution performs a single pass over the sequence A and the string S to calculate the countM and countX arrays, and then another pass to calculate the answer.
Auxiliary space: O(N), where N is the length of the sequence A and the string S. This is because the solution uses two two-dimensional vectors, countM and countX, to store the counts of βMβ and βXβ