VOOZH about

URL: https://www.geeksforgeeks.org/dsa/mex-sum-count/

⇱ MEX Sum Count - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

MEX Sum Count

Last Updated : 29 Jan, 2024

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: 3

Input: 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:

  • Create two two-dimensional vectors, countM and countX, to keep track of the number of "M" and "X" characters before and after each position in the string S.
  • Iterate over the string S and for each character, if it’s β€˜M’, increment the corresponding count in the countM array.
  • Similarly, iterate over the string S in reverse and for each character, if it’s β€˜X’, increment the corresponding count in the countX array.
  • Initialize the answer to 0. Then, iterate over the string S and for each character, if it’s β€˜E’, iterate over all possible values of sequence A (0, 1, 2) and for each pair of values, add to the answer the product of the corresponding counts in countM and countX and the MEX of the pair of values and the current value in sequence A.
  • Finally, print the calculated answer.

Below is the implementation of the above approach:


Output
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’

Comment