We need to solve: given a string s length n (up to 200k) consisting of characters from {'a','b','c','?'}. For each possible replacement of each '?' with one of 'a','b','c', we get a string over 'a','b','c'. Count the total number of subsequences "abc" across all these 3^k strings (where k is number of '?'s). Output modulo 1e9+7.
We need to sum over all replacements. Let total sum = sum_{replacement} count_abc(t) where t is the resulting string.
We can think combinatorially. For each triple of positions i < j < l (indices 1..n) in the original string s, we want to know in how many replacements the letters at these positions become 'a','b','c' respectively, because that triple contributes one to the subsequence count if we pick those three positions (in order) as the subsequence. But careful: subsequence "abc" can be formed by any increasing indices i<j<l such that t[i]='a', t[j]='b', t[l]='c'. So total count in a given t is the number of such triples. So total sum over all t is sum_{i<j<l} ( number of replacements where at those positions we get 'a','b','c' respectively ). So we can sum over all triples (i,j,l) of positions (i<j<l) and multiply by the number of ways to replace the '?'s such that those three positions become fixed letters (and the rest of '?'s can be anything). However note that if any of those positions originally is a fixed letter (not '?') but does not match the required letter, then the number of replacements is zero; if it matches, it's okay. Also, there may be '?' at those positions which we must set to the specific letter.
Let's denote:
For any triple (i,j,l) with i<j<l, the number of replacements that yield t[i]='a', t[j]='b', t[l]='c' is: 3^{k - d} where d = number of '?' among positions i,j,l that are forced to a specific letter (since each '?' elsewhere (positions not among {i,j,l}) can be any of 3 letters, but also '?' at i,j,l that are forced to a particular letter count as forced; if some positions are fixed letters, they must match, otherwise contribution zero). Actually more precisely: let total number of '?' in s be k. For a given triple, we need to count how many assignments to all '?' yield the required letters at those positions. For each '?' position p:
- If p is not in {i,j,l}, it can be any of 3 letters (3 choices).
- If p is in {i,j,l}, then its required letter is predetermined; if the original s[p] is '?', then we must set it to that required letter (1 choice). If s[p] is a fixed letter, then we need that letter to equal the required letter; if not, then there are 0 assignments. So the number of assignments is: 0 if for any p in {i,j,l}, s[p] is a fixed letter not equal to required; else = 3^{(k - q)} where q = number of '?' among {i,j,l} (since those '?' are forced to a specific value, reducing free '?' count). Actually careful: total '?' count is k. Among them, those at positions i,j,l that are '?' must be fixed to one specific value, so they are not free. All other '?' (k - q) can be any of 3. So number of assignments = 3^{k - q} if constraints satisfied, else 0.
Thus total sum = sum_{i<j<l} [condition satisfied] * 3^{k - q(i,j,l)}.
We can compute this efficiently by counting over triples.
n up to 200k, so O(n^2) is impossible. We need O(n) or O(n log n) approach.
We need to sum over triples of positions. Typical approach: dynamic programming or combinatorics using contributions from each position.
We can think of each position j (as the middle of the triple, i.e., 'b') and combine counts of 'a' before and 'c' after, with handling of '?'.
Alternatively, we can compute total sum as expectation: For each replacement, count of "abc" subsequences. Sum over all assignments = total number of assignments (3^k) times expected count of "abc" under uniformly random assignments? Actually careful: The total sum is sum_{all assignments} count_abc(t). That is 3^k * E[count_abc(t)] if assignments are uniform. So we can compute expected number of subsequences "abc" when each '?' is independently uniformly assigned one of three letters (and fixed letters remain as given). But note that fixed letters are not random; they are deterministic. However we can still view the assignments as independent random choices for '?' only, with uniform distribution over 3 letters. Then the total sum = 3^k * E[count_abc], because each assignment has equal probability 1/3^k. So total sum = (3^k) * (expected number of "abc" subsequences). So we could compute expected value of count_abc under random filling of '?' uniformly and independently.
E[count_abc] = sum_{i<j<l} P( t[i]='a', t[j]='b', t[l]='c' ). Since assignments only affect '?' positions, we need to compute for each triple the probability that these three positions become 'a','b','c'. That probability is: product over p in {i,j,l} of P( t[p] = required letter ), where if s[p] is fixed letter, probability is 1 if matches else 0; if s[p] is '?', probability = 1/3 (since random assignment yields required letter with probability 1/3). Additionally, note that assignments are independent across '?', and fixed letters are deterministic, so indeed probability = (1/3)^{q} if constraints possible else 0, where q = number of '?' among the triple. So P = (1/3)^{q} if the fixed letters match, else 0. Then total sum = 3^k * sum_{i<j<l} (1/3)^{q} [condition] = sum_{i<j<l} 3^{k-q} [condition] which matches earlier.
Thus we can compute expected value using linearity and dynamic contributions.
We need to compute sum over triples: for each triple, if possible, weight = 3^{k - q} = 3^{k} * (1/3)^q. Since 3^{k} is common factor if we factor it out, but we can also compute directly without factoring.
Option 1: Compute sum_{triples} 3^{k-q} with condition.
Option 2: Compute expected count = sum_{triples} (1/3)^{q} with condition, then multiply by 3^k.
We can design DP that processes positions from left to right, maintaining counts of ways for prefixes and suffixes.
We need to consider contributions of '?' properly.
Approach:
We can treat each position independently in terms of contributions to a, b, c sequences.
For a given assignment, the number of "abc" subsequences can be computed as sum over j: (number of 'a' before position j) * (number of 'c' after position j) for positions where t[j] = 'b'. So we can write:
count_abc(t) = sum_{j=1..n} [ t[j] == 'b' ] * A_j * C_j, where A_j = number of indices i < j with t[i] = 'a', and C_j = number of indices l > j with t[l] = 'c'.
Now, total sum over all assignments = sum_{assignments} sum_{j} [t[j]='b'] * A_j * C_j = sum_{j} sum_{assignments} [t[j]='b'] * A_j * C_j.
We can try to compute for each position j, the expected (or total) contribution across assignments, and sum. So for each j, we need to compute total number of assignments times expected value of indicator * A_j * C_j. Since assignments are uniform, total contribution for position j = 3^k * E[ I_j * A_j * C_j ], where I_j = 1 if t[j]='b'.
Now, because the random assignments for different positions are independent (except that fixed letters are deterministic and not random; for '?' they are independent). However, we have dependency among I_j, A_j, C_j because they involve the same random variables. But we can compute E[ I_j * A_j * C_j ] by considering distributions for each position.
We can treat each '?' as independent random variable uniformly over {a,b,c}. The fixed letters are constants. Then for each position j, we can compute expectation of product. Because the random variables for different positions are independent, we can factor expectations? But A_j depends on positions i<j, C_j on positions l>j. Since all positions are independent, we can consider the joint distribution.
We can compute for each j: E[ I_j * A_j * C_j ] = E[ I_j * (sum_{i<j} X_i) * (sum_{l>j} Y_l) ] where X_i = 1 if t[i]='a' else 0, and Y_l = 1 if t[l]='c' else 0. Also I_j = 1 if t[j]='b' else 0.
Since expectations of products of sums can be expressed as sum over i and l: E[ I_j * X_i * Y_l ] for i<j<l, because cross terms with i not less than j or l not greater than j vanish? Actually careful: A_j = sum_{i<j} X_i, C_j = sum_{l>j} Y_l. So I_j * A_j * C_j = I_j * (∑{i<j} X_i) * (∑{l>j} Y_l) = ∑{i<j} ∑{l>j} I_j * X_i * Y_l.
So expectation = ∑_{i<j<l} E[ X_i * I_j * Y_l ]. This matches the triple sum approach.
Thus we are back to triple sum.
But maybe we can compute total sum via DP that accumulates contributions from left to right with state tracking counts of ways for partial assignments.
Alternative approach: Since n <= 200k, we can precompute prefix counts and suffix counts that incorporate '?'. But careful because '?' can be assigned in multiple ways; we need to sum over all assignments.
We can think of each position's letter as a random variable with distribution based on original: if fixed letter L, then it's deterministic; if '?', uniform over {a,b,c}. Then we need to compute sum over triples of product of expectations? But because we need expectation of product of three indicators for distinct positions, and the positions are independent, we have E[ I_a(i) * I_b(j) * I_c(l) ] = product of expectations (since they are independent? Are they independent? For positions that are all '?' they are independent because each '?' assignment is independent. However if some positions are fixed, they are deterministic, but still independent from the '?' ones. So indeed, for any distinct positions, the random variables (the resulting letters) are independent, because each position's value is either fixed (constant) or a random variable independent from others. So yes, they are independent: the randomness only comes from independent assignments to '?' at each position. Therefore, for any distinct positions i, j, l, the events that t[i]='a', t[j]='b', t[l]='c' are independent? They are independent because the assignments are independent across positions. However careful: If a position is fixed (non-random), then it's constant, so it's independent of anything else. So indeed the three events are independent. Therefore P( t[i]='a' and t[j]='b' and t[l]='c' ) = P(t[i]='a') * P(t[j]='b') * P(t[l]='c'). And those probabilities are either 1 or 0 if fixed, or 1/3 if '?'. So that matches (1/3)^q if constraints possible else 0. So indeed we can compute the total sum as:
Total = 3^k * ∑_{i<j<l} p_i_a * p_j_b * p_l_c, where p_x_a = P(t[x]='a') etc. Because independent.
Wait: Is that correct? Let's verify: We want total sum = sum over assignments count_abc = ∑{assignments} ∑{i<j<l} I_i_a I_j_b I_l_c = ∑{i<j<l} ∑{assignments} I_i_a I_j_b I_l_c. For each triple, the inner sum is number of assignments where all three conditions hold. That's exactly 3^k * (P(t[i]='a') * P(t[j]='b') * P(t[l]='c')) because assignments are independent across positions. Indeed, number of assignments = product over positions of number of choices; for each position p, if it's '?' then number of choices for that position to match a specific letter is 1 (since we force that letter) and total assignments for that position is 3; but if we think probability: For fixed positions, if they match, then probability is 1, which corresponds to number of choices = 1 out of 1 (so it's like a forced assignment). So yes, the number of assignments = 3^k * P(t[i]='a') * P(t[j]='b') * P(t[l]='c'), because P(t[i]='a') = (1 if fixed a else 0 if fixed not a else 1/3 if '?'). However careful: The factor 3^k is total number of assignments. But P(t[i]='a') etc are defined under the uniform random assignment. So indeed, for each triple, the expected indicator = P(t[i]='a') * P(t[j]='b') * P(t[l]='c'). Then sum over assignments = total assignments * expected indicator = 3^k * product of probabilities.
But check: For a triple where a fixed letter conflicts (e.g., s[i] = 'b'), then P(t[i]='a') = 0, so product is 0. Good. For '?' positions, probability = 1/3. So indeed total contributions = 3^k * (1/3)^{q} where q is number of '?' among the triple, provided fixed letters match. This matches earlier expression: 3^{k} * (1/3)^q = 3^{k-q}. However wait: earlier we had 3^{k - q}. Let's reconcile: In earlier expression, we said number of assignments where triple satisfied = 3^{k - q} if constraints satisfied. Because total assignments = 3^k, and probability of satisfaction = (1/3)^q, so indeed assignments = 3^k * (1/3)^q = 3^{k - q}. Yes, consistent. So we can compute total sum = 3^k * ∑_{i<j<l} p_i_a * p_j_b * p_l_c.
Thus the problem reduces to: given probabilities for each position being 'a', 'b', 'c' (which are either 0, 1, or 1/3), compute sum over all triples i<j<l of p_i_a * p_j_b * p_l_c, then multiply by 3^k mod M.
But careful: p_i_a, etc, are rational numbers (like 1 or 1/3). Multiplying by 3^k will yield integer contributions. Since we are computing modulo prime (1e9+7), we can work with modular inverses.
Alternatively, we can compute directly ∑_{i<j<l} 3^{k - q(i,j,l)} [condition], which may be easier by counting triples based on counts of '?' among them.
But using probabilities seems more straightforward: we can compute sum over triples of product of probabilities, then multiply by 3^k. However, note that the probabilities are fractions; we can represent them as integers modulo MOD by multiplying by appropriate powers of 3. Better: Let's define weight_a[i] = 1 if s[i] == 'a', 0 if s[i] == 'b' or 'c', and 1 if s[i] == '?'? Actually for '?' probability = 1/3. So p_i_a = (s[i] == 'a' ? 1 : (s[i] == '?' ? 1/3 : 0)). Similarly p_i_b = (s[i] == 'b' ? 1 : (s[i] == '?' ? 1/3 : 0)), p_i_c = (s[i] == 'c' ? 1 : (s[i] == '?' ? 1/3 : 0)). So we can write p_i_a = val_i_a / 3^{?}. Actually for '?' it's 1/3; we can represent each probability as an integer divided by 3^{f_i} but simpler: Let's multiply everything by 3^k factor eventually. Instead compute:
Total = ∑{i<j<l} 3^{k} * p_i_a * p_j_b * p_l_c = ∑{i<j<l} 3^{k} * (v_i_a / d_i) * (v_j_b / d_j) * (v_l_c / d_l) maybe but easier: define for each position a value in terms of counts of '?' contributions.
Observation: For each position i, if s[i] is 'a', then it contributes factor 3 (like 3^{1})? Not exactly. Let's derive:
We want to compute S = ∑_{i<j<l} 3^{k - q(i,j,l)} * [condition], where q = number of '?' among i,j,l. This is same as: for each triple, count = 3^{k} * (1/3)^{q} if condition, else 0.
Now define for each position i, we can assign a "weight" for being 'a' as: w_a[i] = 3^{k_i?} hmm.
We could factor out 3^{k} and then compute sum of (1/3)^{q}. But maybe we can directly compute S using DP with counting of number of ways with contributions.
Another approach: Consider generating function: Let we process string left to right, and keep track of number of ways to form prefixes with certain counts of 'a', 'ab', etc. That is typical for counting subsequences "abc" in a string with wildcards. For each character position, we update DP states: dp[0] = number of ways to form empty subsequence? Actually we can compute total number of "abc" subsequences across all strings by dynamic programming that counts expected number or total.
We can treat '?' as having three possibilities, and we want the sum of counts across all assignments. This can be done by DP that counts, for each prefix, the total number of ways to form partial subsequences ('a', 'ab', 'abc') summed over all assignments of processed '?' so far. This is a typical problem: Count total number of subsequences "abc" across all strings generated by replacing '?' with letters a,b,c.
We can define:
Let dp0 = total number of ways for prefix (i.e., number of assignments for processed part) maybe? Actually we need to accumulate both counts and number of assignments.
We can have:
Let ways = number of different assignments for processed positions (initially 1). But we also want to sum of counts.
Standard DP: Let cnt[0] = total number of ways (assignments) for prefix; but we need to count subsequences. Alternatively, we can compute expected count for each assignment.
But we can compute total sum directly:
We process characters one by one. Maintain three values:
total_a: total number of ways to choose an 'a' (i.e., sum over assignments for processed prefix of number of 'a's? Actually careful: We want eventually total sum over assignments of number of "abc" subsequences. This can be expressed as sum over assignments of (number of ways to pick i<j<l with a,b,c). Equivalent to number of triples (i,j,l) and assignments where they are a,b,c. Alternatively, while processing, we can maintain counts of partial subsequences:
Define:
-
state0: total number of ways (i.e., sum over all assignments of processed part)?? Actually we need aggregated counts: we can keep:
-
sum_a: total sum over all assignments of the number of 'a' subsequences (i.e., number of ways to select a single index that is 'a') in the processed prefix. But careful: Since we want to eventually count triples, we can maintain counts for 'a' and for 'ab' and for 'abc'.
We can define:
-
cnt: total number of assignments so far (for processed positions). Initially 1.
-
total_a: for the processed prefix, sum over all assignments of the count of 'a's (i.e., for each assignment, number of positions i with letter 'a', sum them). Equivalent to total number of pairs (assignment, index) where index is an 'a'.
-
total_ab: sum over assignments of number of subsequences "ab" (i.e., number of pairs i<j with t[i]='a' and t[j]='b').
-
total_abc: sum over assignments of number of subsequences "abc".
Then as we process the next character (position p) with type (a, b, c, ?), we update these values.
But need to handle that when we extend the string, we need to account for new subsequences that involve the new character.
For each new character, we consider its possible letters based on if it's fixed or '?'. For '?' we have three possibilities, each equally likely in the assignment set; but we are summing over all assignments, so we treat it as branching factor 3. So we can update as follows:
Let the current counts be: cnt (number of assignments for processed prefix), total_a, total_ab, total_abc.
When we add a new character at position p:
Case: if character is fixed, say 'a':
- New assignments: each previous assignment remains same, no branching. So cnt_new = cnt * 1 (since no extra choice). But we need to update totals:
- total_a_new: previous total_a plus for each assignment, if the new char is 'a', it adds 1 to the count of 'a's. So additional = cnt (since each assignment gets one extra 'a'). So total_a_new = total_a + cnt.
- total_ab_new: The new character being 'a' does not contribute to 'ab' as the second character; but it can be the first character of new 'ab' pairs? Actually pairs i<j, where j is new position. If new character is 'a', then it cannot be the second character (b) in an 'ab' pair. However, it can be the first character (a) in a pair with some future b? But for subsequences "ab", we count pairs i<j. When we process the new character as a potential j (second), we need to consider pairs where this new position is the b. Since it's 'a', not b, it doesn't serve as b. It can serve as a for later b's, but that's accounted later. So for current update, only existing total_ab remains unchanged because no new 'ab' pairs ending at this position (since it's not b). However, note: existing total_ab counts pairs with indices both in prefix. Adding a new character that is 'a' does not create new pairs with earlier positions as a? Actually consider a pair (i, new) where i < new. If new is 'a', then it would be 'a' at both i and new; but 'ab' requires first a, second b. So no. So total_ab_new = total_ab.
- total_abc: similarly, new char being 'a' does not directly create new 'abc' triples where it is c? Actually it can be part of abc as a? It could be the a in a triple with later b and c, but not ending at this position as c. Also it could be the middle b? No. So total_abc unchanged.
But wait: There is another effect: When we add new character, we also need to consider that earlier counts total_a, total_ab, total_abc are defined for the prefix only. After adding new character, they should represent counts for the extended prefix. So the updates above are correct for a fixed 'a'.
Case: fixed 'b':
- cnt_new = cnt.
- total_a_new: does not add to a count; so total_a_new = total_a.
- total_ab_new: new character is 'b', so it can form new 'ab' pairs with every 'a' that occurred earlier. For each assignment, the number of new 'ab' pairs = number of 'a's in that assignment (i.e., count of a in prefix). Summed over assignments, that's exactly total_a. So total_ab_new = total_ab + total_a.
- total_abc_new: new character being 'b' does not directly create 'abc' triples as the third char (c). However, it can be the middle of an 'abc' triple where a is before, b is this, and c will be later. So no new complete abc yet. So total_abc unchanged.
But also total_abc may be affected if we later add c, but not now.
Case: fixed 'c':
- cnt_new = cnt.
- total_a_new = total_a.
- total_ab_new = total_ab.
- total_abc_new: new character is 'c', so it can complete 'abc' triples with every 'ab' pair that ends before it. For each assignment, number of new 'abc' = number of 'ab' subsequences in that assignment (i.e., count of ab pairs). Summed over assignments, that's total_ab. So total_abc_new = total_abc + total_ab.
Case: '?':
Here, the new character can be 'a', 'b', or 'c' each with branching factor 3. For each previous assignment, we extend it into 3 assignments: one with 'a', one with 'b', one with 'c'. So cnt_new = cnt * 3.
Now we need to update total counts for the extended prefix, considering all three possibilities.
We can compute new totals as weighted sum over the three possibilities. Since each branch is equally counted (each assignment distinct), we can update:
total_a_new = for each previous assignment, after adding 'a' we add 1 to a count; after adding 'b' or 'c' we add 0. So contribution: total_a from previous assignments (each assignment's a count) remains same regardless of which letter we add? Wait, careful: The existing total_a counts the number of 'a' positions in the prefix (without the new char). When we extend with a new char, for each previous assignment, its total_a count (i.e., number of a's in that assignment) is carried over unchanged. Additionally, if the new char is 'a', it adds 1. So for each previous assignment, if we add 'a' branch, the new a count = old a count + 1; if we add 'b' or 'c', new a count = old a count. Since there is one branch for each, we sum over all branches. So total_a_new = (sum over previous assignments of (old a count) * 3) + (cnt * 1) because for each previous assignment, exactly one branch (the 'a' branch) adds an extra 1. More precisely:
total_a_new = 3 * total_a (since each previous assignment contributes its old a count to all three branches) + cnt (since for each previous assignment, there is one branch where new char is 'a', giving +1). So total_a_new = 3*total_a + cnt.
Similarly, total_ab_new: We need to compute sum over assignments of number of 'ab' pairs in the extended prefix.
For each previous assignment, let a = its number of 'a's, ab = its number of 'ab' pairs.
When we add new char:
- If new char = 'a': ab count remains same (since no new ab). So new ab = ab.
- If new char = 'b': new ab = ab + a (since each previous a forms a new ab pair with this b).
- If new char = 'c': new ab = ab (no new ab).
Over three branches per previous assignment, total ab sum becomes: for each previous assignment, sum_{branch} new_ab = (ab for a) + (ab + a for b) + (ab for c) = 3*ab + a.
Now summing over all previous assignments, we get total_ab_new = 3*total_ab + total_a (since sum over assignments of a = total_a). Also we need to consider that the cnt factor? Actually total_a is sum over assignments of a counts. So yes.
But also careful: The total number of assignments now is cnt_new = 3cnt. So total_ab_new = 3total_ab + total_a.
Now total_abc_new:
For each previous assignment, let abc = its abc count, ab = its ab count, and maybe also something else? When adding new char:
- If new char = 'a': abc unchanged.
- If new char = 'b': abc unchanged (but might later affect? no).
- If new char = 'c': new abc = abc + ab (since each ab pair completes an abc with this c).
So for each previous assignment, sum over branches new_abc = (abc) + (abc) + (abc + ab) = 3*abc + ab.
Summing over assignments: total_abc_new = 3*total_abc + total_ab.
Thus we have recurrence for '?'.
Now for fixed letters we already had updates, which can be seen as special cases of the above with branching factor 1 and only one possible letter. But careful: For fixed letter, we do not have the factor 3; cnt stays the same. The updates we derived for fixed letters should be consistent with these formulas if we consider branching factor 1 and only that specific letter. Let's check:
For fixed 'a':
- cnt_new = cnt.
- total_a_new = total_a + cnt (since only one branch with +1). That matches: if we had only 'a' branch, total_a_new = total_a + cnt. In '?' formula, total_a_new = total_a * (branch count) + cnt * (indicator of a). With branch count=1, we get total_a_new = total_a + cnt if a is chosen. Good.
- total_ab_new = total_ab (since a doesn't add ab). In '?' formula for only a branch: total_ab_new = total_ab + total_a * (indicator of b)? Actually for only a, no contribution from total_a. So total_ab_new = total_ab. Good.
- total_abc_new = total_abc.
For fixed 'b':
- total_a_new = total_a.
- total_ab_new = total_ab + total_a.
- total_abc_new = total_abc.
For fixed 'c':
- total_ab_new = total_ab.
- total_abc_new = total_abc + total_ab.
So we can process the string in O(n) using these updates, maintaining cnt, total_a, total_ab, total_abc modulo MOD.
At the end, total_abc will be the sum over all assignments of the number of subsequences "abc". That's exactly the desired answer. We don't need to multiply by anything else.
Check with examples:
Example 1:
n=6, s="ac?b?c"
Let's compute manually:
We'll simulate:
Initialize:
cnt = 1 (number of assignments for empty prefix)
total_a = 0
total_ab = 0
total_abc = 0
Process each char:
1: 'a'
fixed 'a':
cnt = 1
total_a = 0 + cnt = 1
total_ab = 0
total_abc = 0
2: 'c'
fixed 'c':
cnt = 1
total_a stays 1
total_ab stays 0
total_abc = 0 + total_ab = 0
3: '?'
'?':
cnt_new = cnt * 3 = 3
total_a_new = 3total_a + cnt = 31 + 1 = 4
total_ab_new = 3total_ab + total_a = 30 + 1 = 1
total_abc_new = 3total_abc + total_ab = 30 + 0 = 0
Now after char3:
cnt=3, total_a=4, total_ab=1, total_abc=0
4: 'b'
fixed 'b':
cnt stays 3
total_a stays 4
total_ab = total_ab + total_a = 1 + 4 = 5
total_abc unchanged = 0
5: '?'
'?':
cnt = cnt3 = 9
total_a = 3total_a + cnt_old? Wait careful: When updating for '?' we need to use old cnt before multiplication. So we must compute based on previous values. Let prev_cnt = 3, prev_total_a=4, prev_total_ab=5, prev_total_abc=0.
Then:
cnt_new = prev_cnt * 3 = 9
total_a_new = 3prev_total_a + prev_cnt = 34 + 3 = 12 + 3 = 15
total_ab_new = 3prev_total_ab + prev_total_a = 35 + 4 = 15 + 4 = 19
total_abc_new = 3prev_total_abc + prev_total_ab = 30 + 5 = 5
6: 'c'
fixed 'c':
prev values: cnt=9, total_a=15, total_ab=19, total_abc=5
Now fixed 'c':
cnt stays 9
total_a stays 15
total_ab stays 19
total_abc = total_abc + total_ab = 5 + 19 = 24
Result total_abc=24, matches example output.
Great.
Example 2: n=7, s="???????" all '?'
We need compute final total_abc. Should be 2835.
Let's simulate quickly to verify recurrence:
Initialize: cnt=1, a=0, ab=0, abc=0.
For each '?' step, we apply same recurrence.
Let’s define after processing i characters (all '?'), we have some values. We can compute closed form? We'll just simulate with code later, but let's try manually perhaps:
After 1 '?':
cnt = 3
a = 30 + 1 = 1
ab = 30 + 0 = 0
abc = 3*0 + 0 = 0
Check: strings: a,b,c. a count: 1 for a, 0 for b,c => total a sum =1, matches a=1. ab sum =0, abc=0.
After 2 '?':
prev: cnt=3, a=1, ab=0, abc=0.
new cnt = 33=9
a = 31 + 3 = 3+3=6
ab = 30 + 1 = 1
abc = 30 + 0 = 0
After 3 '?':
prev: cnt=9, a=6, ab=1, abc=0
new cnt = 93=27
a = 36 + 9 = 18+9=27
ab = 31 + 6 = 3+6=9
abc = 30 + 1 = 1
After 4 '?':
prev: cnt=27, a=27, ab=9, abc=1
new cnt = 273=81
a = 327 + 27 = 81+27=108? Wait: 327=81, plus prev_cnt=27 =>108
ab = 39 + 27 = 27+27=54
abc = 3*1 + 9 = 3+9=12
After 5 '?':
prev: cnt=81, a=108, ab=54, abc=12
new cnt = 813=243
a = 3108 + 81 = 324+81=405
ab = 354 + 108 = 162+108=270
abc = 312 + 54 = 36+54=90
After 6 '?':
prev: cnt=243, a=405, ab=270, abc=90
new cnt = 2433=729
a = 3405 + 243 = 1215+243=1458
ab = 3270 + 405 = 810+405=1215
abc = 390 + 270 = 270+270=540
After 7 '?':
prev: cnt=729, a=1458, ab=1215, abc=540
new cnt = 7293=2187
a = 31458 + 729 = 4374+729=5103? Actually 31458=4374, +729 = 5103
ab = 31215 + 1458 = 3645+1458=5103
abc = 3*540 + 1215 = 1620+1215=2835
Thus abc=2835, matches.
Example 3: "cccbbbaaa" output 0: Let's simulate: fixed letters only, but no possible abc because order is c,c,c,b,b,b,a,a,a. Since all a's are after b's and c's, there is no subsequence a,b,c in order (since a must come before b, but all a's are at end). So result should be 0. Our DP should yield 0.
Example 4: n=5, s="a???c" output 46. Let's simulate:
Initialize: cnt=1,a=0,ab=0,abc=0
1: 'a' -> cnt=1, a=1, ab=0, abc=0
2: '?' -> prev: cnt=1,a=1,ab=0,abc=0. '?' => cnt=3, a=31+1=4, ab=30+1=1, abc=30+0=0
3: '?' -> prev: cnt=3,a=4,ab=1,abc=0. '?' => cnt=9, a=34+3=12+3=15, ab=31+4=3+4=7, abc=30+1=1
4: '?' -> prev: cnt=9,a=15,ab=7,abc=1. '?' => cnt=27, a=315+9=45+9=54, ab=37+15=21+15=36, abc=3*1+7=3+7=10
5: 'c' fixed 'c' -> prev: cnt=27,a=54,ab=36,abc=10. fixed 'c': cnt stays 27, a=54, ab=36, abc = 10 + ab = 10 + 36 = 46. So abc=46. Matches.
Great! So the DP approach works perfectly.
Thus solution: iterate over string, maintain four variables: cnt (number of assignments so far), a (sum over assignments of number of 'a' subsequences), ab (sum of 'ab' subsequences), abc (sum of 'abc' subsequences). Update according to character.
Complexity O(n), memory O(1). Modulo M = 1e9+7.
Need to be careful with large numbers: all operations modulo M.
Edge cases: cnt can become huge; we take modulo.
But wait: Is there any subtlety? The DP is essentially counting total number of assignments and sums over assignments of counts. The recurrences we derived for '?' are correct because we treat each previous assignment multiplied by 3 branches equally. However, we must be careful: When we multiply total_a by 3, we are effectively counting each previous assignment's a count three times, which corresponds to the three branches. Then we add cnt for the extra 'a' from the branch where new char is 'a'. That seems fine.
But what about the case where the new character is '?', we used cnt (the previous number of assignments) to add to total_a. That's correct because for each previous assignment, exactly one of the three new assignments (the 'a' branch) contributes an extra 'a'. So total extra = 1 * (number of previous assignments) = cnt. Since we also multiply the old total_a by 3, we are counting each previous assignment's a count in all three branches. So total_a_new = 3*old_total_a + old_cnt.
Similarly for total_ab: old total_ab counted sum of ab counts per assignment. For each previous assignment, in branches: 'a' and 'c' keep same ab; 'b' adds old a to ab. So sum over branches: old_ab (for a) + (old_ab + old_a) (for b) + old_ab (for c) = 3old_ab + old_a. Summing over assignments gives 3old_total_ab + old_total_a. Good.
For total_abc: sum over branches: old_abc (a) + old_abc (b) + (old_abc + old_ab) (c) = 3old_abc + old_ab. So total_abc_new = 3old_total_abc + old_total_ab.
Now for fixed letters, we can just apply updates as if only one branch.
We need to ensure that after processing all characters, total_abc is the sum over all assignments of the number of "abc" subsequences. Indeed, our DP built it step by step.
Thus answer = total_abc % MOD.
Now we should verify with more cases. Let's test small n manually:
n=3, s = "???" -> total assignments = 27. For each assignment, we count number of "abc" subsequences (i.e., if the string is exactly "abc", count 1; otherwise maybe more? For length 3, only possible if the string is exactly "abc", then count=1. How many assignments yield "abc"? Exactly 1 (a at pos1, b pos2, c pos3). So total sum should be 1. But our DP would compute? Let's simulate:
Init: cnt=1,a=0,ab=0,abc=0
1:'?' -> cnt=3, a=1, ab=0, abc=0
2:'?' -> prev: cnt=3,a=1,ab=0,abc=0; new: cnt=9, a=31+3=6, ab=30+1=1, abc=30+0=0
3:'?' -> prev: cnt=9,a=6,ab=1,abc=0; new: cnt=27, a=36+9=18+9=27, ab=31+6=3+6=9, abc=30+1=1
So abc=1. Good.
If s = "a?c"? Let's compute manually. n=3: possibilities: assign '?' to a,b,c -> strings: aac, abc, acc. Count abc: only abc gives 1. So total sum =1. Our DP:
Init: cnt=1,a=0,ab=0,abc=0
1:'a' -> cnt=1,a=1,ab=0,abc=0
2:'?' -> prev: cnt=1,a=1,ab=0,abc=0; '?' -> cnt=3, a=31+1=4, ab=30+1=1, abc=3*0+0=0
3:'c' fixed 'c' -> prev: cnt=3,a=4,ab=1,abc=0; fixed c: abc = abc + ab = 0+1=1. So total_abc=1. Good.
If s = "ab?"? n=3: possibilities: assign '?' to a,b,c -> strings: aba, abb, abc. Count abc: only abc gives 1. So total=1. DP:
Init: cnt=1,a=0,ab=0,abc=0
1:'a' -> a=1
2:'b' -> ab = ab + a = 0+1=1, a unchanged (1)
3:'?' -> '?': prev cnt=1? Wait after step2: cnt=1,a=1,ab=1,abc=0. Now step3 '?': new cnt=3, a=31+1=4, ab=31+1=3+1=4, abc=3*0+1=1. So abc=1. Good.
Another test: s = "a?b?c" (n=5) maybe compute manually? Not needed.
Thus DP is correct.
Now we need to implement this.
Important: We must perform all operations modulo MOD = 1e9+7. But careful: When we compute 3 * total_a, that's fine modulo MOD. Adding cnt, etc.
But we must keep cnt also modulo MOD? cnt is the number of assignments for the processed prefix. Since total counts we compute are modulo MOD, we can keep cnt modulo MOD because we only use it in additions and multiplications. However, note that cnt can become huge (3^k). But modulo arithmetic is fine: we only need final answer modulo MOD, and the recurrence uses only linear combinations modulo MOD. So we can keep cnt modulo MOD. However, there is a nuance: In the recurrences for '?', we used cnt as the number of assignments to compute the addition to total_a: total_a_new = 3*total_a + cnt. If we reduce cnt modulo MOD, it's fine because the actual value modulo MOD is what matters for final total_abc modulo MOD. Since all operations are linear, using modulo throughout yields correct result modulo MOD.
But we need to be careful: In the fixed letter updates, we add cnt to total_a when char is 'a', etc. That also works modulo MOD.
So we can maintain everything modulo MOD.
Potential pitfalls: We must be careful about order: When processing a character, we need to use the previous values (cnt, a, ab, abc) to compute new values. We need to compute all updates simultaneously or in correct order to avoid using partially updated values. Since each update only uses old values, we can compute new values into temporary variables or update sequentially with care. But if we do:
cnt = cnt * (branch factor) // for fixed, branch factor = 1; for '?', branch factor = 3.
a = ... based on old a, old cnt
ab = ... based on old ab, old a
abc = ... based on old abc, old ab
So we need to store old values before updating. Or compute in order that ensures we don't use a variable that's already been updated when it should be old. Since a appears in formula for ab, and ab appears in formula for abc, we need old a and old ab. So it's safest to store old values.
Alternatively, we can compute new_a, new_ab, new_abc, new_cnt using old values, then assign.
Pseudo:
MOD = 10**9+7
cnt = 1
a = 0
ab = 0
abc = 0
for ch in s:
if ch == 'a':
# only a branch
a = (a + cnt) % MOD
# cnt unchanged
# ab unchanged
# abc unchanged
elif ch == 'b':
ab = (ab + a) % MOD
# others unchanged
elif ch == 'c':
abc = (abc + ab) % MOD
else: # '?'
# new_cnt = cnt * 3
# new_a = (3a + cnt) % MOD
# new_ab = (3ab + a) % MOD
# new_abc = (3abc + ab) % MOD
# then assign
new_cnt = (cnt * 3) % MOD
new_a = (3a + cnt) % MOD
new_ab = (3ab + a) % MOD
new_abc = (3abc + ab) % MOD
cnt, a, ab, abc = new_cnt, new_a, new_ab, new_abc
But careful: For fixed 'a', we also need to update cnt? No change. For fixed 'b' and 'c', cnt unchanged. So above is fine.
But there is a nuance: In fixed 'a' update, we do a = a + cnt. That's using current cnt (which is correct). And no other updates depend on a for this step? Actually after we update a, we should not use that updated a for anything else in same step, but that's fine because we only do that one update. In fixed 'b', we update ab = ab + a; but we need old a, which is the a before update. Since we haven't changed a yet in this iteration, that's fine. In fixed 'c', abc = abc + ab; using old ab.
Thus we can do sequentially without temp variables because each update uses only values that are from previous iteration (except for '?', where we need old values for multiple updates, but we can compute them before changing any; but we also need to update cnt, a, ab, abc simultaneously. So for '?' we can compute new values using old and then assign.
One more nuance: For fixed 'a' and 'b' and 'c', cnt remains same. So we should not multiply cnt by 1, it's fine.
Now confirm the formulas for fixed letters again with the perspective that they are special cases of '?' with only that branch and factor=1.
But we need to check for fixed 'b' and 'c' that we also might have a slight effect on a? No.
Thus implementation is straightforward.
Edge Cases: n up to 200k, O(n) is fine.
We need to parse input: first line n, second line s. s length may contain spaces? No, it's a string.
Now we produce answer modulo MOD.
But wait: Could there be any overflow in Python? Python ints are arbitrary precision, but we mod each step.
Now test on examples:
Example1 gave 24, example2 2835, example3 0, example4 46.
So solution works.
But let's double-check with example3 manually: s = "cccbbbaaa". Process:
cnt=1,a=0,ab=0,abc=0
c: fixed c -> abc += ab (0) -> abc=0
c: same -> abc unchanged (still 0)
c: same -> abc unchanged (0)
b: fixed b -> ab += a (a is 0) -> ab=0
b: same -> ab remains 0
b: same -> 0
a: fixed a -> a += cnt (1) -> a=1
a: fixed a -> a=2
a: fixed a -> a=3
At the end abc = 0. So works.
Now we should consider if any other nuance: The DP counts total number of subsequences "abc" across all strings. This matches the required answer.
Therefore, solution: iterate and apply updates.
Now discuss correctness: The DP essentially computes the sum of counts by building strings incrementally. The recurrence for '?' can be derived from combinatorial reasoning.
We can also prove by induction: After processing prefix of length i, cnt_i = number of assignments for prefix, a_i = sum_{assignments} (# of a in assignment), ab_i = sum (# of ab pairs), abc_i = sum (# of abc subsequences). Then we show the updates produce the correct values for i+1.
Thus solution is correct.
Now time complexity O(n), memory O(1). Works within constraints.
Now implement.
Potential pitfalls: In Python, using % MOD on each operation might be a bit slow but fine for 200k.
Alternative: we could precompute powers of 3 but not necessary.
Now write final answer.
We also should consider large n and speed. Python loops fine.
Now let's produce final solution.
But before final, we might want to test with random small strings via brute force to ensure DP matches.
I'll mentally test a few:
n=1,2 trivial (abc count always 0). DP: no triple so final abc=0.
n=3, s="?b?".
All assignments: (a,b,a), (a,b,b), (a,b,c), (b,b,a), (b,b,b), (b,b,c), (c,b,a), (c,b,b), (c,b,c). Count abc: only (a,b,c) gives 1. So total=1. DP:
Init: cnt=1,a=0,ab=0,abc=0
1:'?' -> cnt=3, a=1, ab=0, abc=0
2:'b' fixed -> ab = ab + a = 0+1=1, a unchanged? a=1 still, cnt=3.
3:'?' -> treat as '?': old cnt=3, a=1, ab=1, abc=0 -> new cnt=9, a=31+3=6, ab=31+1=4, abc=3*0+1=1 -> abc=1. Good.
Now s="a?b"? Actually length 3 with middle '?' and ends a and b? But need subsequence abc requires three letters, so length 3 only if full string is abc. So maybe test "?a?" etc. But DP seems fine.
Now what about strings with multiple possible abc subsequences? For example, s = "a??c"? length 4. Let's brute: possibilities: assign two '?' to letters. There are 9 strings. Count abc in each:
We can list: positions:1 a,2 ?,3 ?,4 c.
We need triples (i,j,k) = (1,2,4) with a,b,c; (1,3,4) with a,b,c; (2,3,4) would need a at 2, b at 3, c at 4, but 2 and 3 both '?'. Actually triples: (1,2,4) and (1,3,4) and (2,3,4). Let's count per assignment:
Assign (2,3):
- (a,a): string a a a c -> a at 1,2,3; c at4. Subseq: (1,2,4): a a c not abc; (1,3,4): a a c; (2,3,4): a a c. So 0.
- (a,b): a a b c: check (1,2,4): a a c; (1,3,4): a b c => 1; (2,3,4): a b c? Actually (2,3,4): a b c? 2 is a, 3 is b, 4 is c -> a b c? But a at pos2 is 'a', need 'a' for first? For (2,3,4) the first should be a, pos2 is a, second b, third c: yes a b c => another 1. So total 2.
- (a,c): a a c c: (1,2,4): a a c; (1,3,4): a c c; (2,3,4): a c c => 0.
- (b,a): a b a c: (1,2,4): a b c? pos1 a, pos2 b, pos4 c => 1; (1,3,4): a a c? 1 a, 3 a, 4 c => not; (2,3,4): b a c => b is not a => 0. So total 1.
- (b,b): a b b c: (1,2,4): a b c =>1; (1,3,4): a b c? pos1 a, pos3 b, pos4 c => 1; (2,3,4): b b c => not; total 2.
- (b,c): a b c c: (1,2,4): a b c =>1; (1,3,4): a c c =>0; (2,3,4): b c c =>0 =>1.
- (c,a): a c a c: (1,2,4): a c c =>0; (1,3,4): a a c =>0? pos1 a, pos3 a, pos4 c => a a c no; (2,3,4): c a c => not; total 0.
- (c,b): a c b c: (1,2,4): a c c =>0; (1,3,4): a b c? pos1 a, pos3 b, pos4 c =>1; (2,3,4): c b c => not; total 1.
- (c,c): a c c c: 0.
Now sum totals: 0+2+0+1+2+1+0+1+0 = 7.
Now compute with DP:
s = "a??c", n=4.
Init: cnt=1,a=0,ab=0,abc=0
1: 'a': a = a + cnt = 1, cnt=1.
2: '?': old cnt=1,a=1,ab=0,abc=0 -> new cnt=3, a=31+1=4, ab=30+1=1, abc=30+0=0
3: '?': old cnt=3,a=4,ab=1,abc=0 -> new cnt=9, a=34+3=12+3=15, ab=31+4=3+4=7, abc=30+1=1
4: 'c' fixed: abc = abc + ab = 1 + 7 = 8. That gives 8, not 7. Discrepancy! Let's re-evaluate.
Our manual sum gave 7. But DP gives 8. Something is off. Let's double-check manual counting.
s = "a??c": positions 1,2,3,4.
Assignments for positions 2 and 3 (each from {a,b,c}) independently: total 9 strings.
We need to count total number of "abc" subsequences across these strings.
We listed each and counted. Let's recompute carefully.
List all 9 assignments (pos2, pos3):
-
(a,a): string = a a a c -> "aaac". Subsequences "abc": we need an a, then a b, then a c. There are no 'b's in the string, so count = 0.
-
(a,b): a a b c -> "aabc". Let's list all triples (i<j<k) such that t[i]='a', t[j]='b', t[k]='c'. Positions: i can be 1 or 2 (both a). j must be 3 (b). k must be 4 (c). So triples: (1,3,4) and (2,3,4). Both satisfy: (1,3,4): a,b,c -> yes; (2,3,4): a,b,c -> yes. So count = 2. I had 2 earlier.
-
(a,c): a a c c -> "aacc". No b, so 0.
-
(b,a): a b a c -> "abac". Triples: (i,j,k). Need a, then b, then c. a positions: 1,3? Actually t[1]='a', t[2]='b', t[3]='a', t[4]='c'. So a at 1 and 3. b at 2 only. c at 4 only. So possible triples: (1,2,4) -> a,b,c -> yes. (3,2,4) invalid because i<j needed, 3>2. (1,3,4) -> a,a,c not b. (3,? ) no. So only 1. So count=1. I had 1.
-
(b,b): a b b c -> "abbc". a at 1, b at 2,3, c at 4. Triples: (1,2,4): a,b,c -> yes; (1,3,4): a,b,c -> yes; (2,3,4): b,b,c not a. So 2. I had 2.
-
(b,c): a b c c -> "abcc". a at1, b at2, c at3,4. Triples: (1,2,3): a,b,c -> yes; (1,2,4): a,b,c -> yes? Actually (1,2,4): t[1]='a', t[2]='b', t[4]='c' -> yes; (1,3,4): a,c,c -> no; (2,3,4): b,c,c -> no. So that's 2? Wait we have two triples: (1,2,3) and (1,2,4). Both are valid because third letter c appears at positions 3 and 4. So count = 2. But earlier I counted 1. Let's double-check: For (b,c): string is "abcc". Indices:1 a,2 b,3 c,4 c. Subsequence "abc": need a, then b, then c. The a can only be index1. b only index2. c can be index3 or 4. So two subsequences: (1,2,3) and (1,2,4). So total 2. I incorrectly counted 1 earlier. So correct count is 2.
-
(c,a): a c a c -> "acac". a at1,3; b none; c at2,4. No b, so 0.
-
(c,b): a c b c -> "acbc". a at1; b at3; c at2,4. Triples: (1,3,4): a,b,c -> yes. Also (1,3,2) invalid order. Could there be (1,2,4)? That would be a,c,c not b. (1,2,? ) no. (1,? ) maybe (1,3,? ) only c at4 works, so 1. So count=1. I had 1.
-
(c,c): a c c c -> "accc". no b, 0.
Now sum: 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8. So total is 8, not 7. So DP giving 8 is correct. My earlier manual sum was wrong due to miscount for case (b,c). So DP works.
Thus DP is verified.
Now we can implement.
But before finalizing, we should consider if the DP truly yields total sum (not expected) because we multiply by cnt appropriately. We need to ensure that in the '?' case, we didn't miss any factor: cnt_new = 3*cnt. For fixed letters, cnt remains same. So at the end, cnt = 3^{k}. The DP's total_abc is the sum over all assignments of number of abc subsequences.
Now prove that recurrence for '?' yields correct total_abc.
Let old state: for each assignment A of prefix (cnt of them), we have values a(A), ab(A), abc(A). After adding '?', we generate three assignments A_a, A_b, A_c (extended with respective letter). For each, the new counts are:
- For A_a: a' = a(A) + 1, ab' = ab(A), abc' = abc(A)
- For A_b: a' = a(A), ab' = ab(A) + a(A), abc' = abc(A)
- For A_c: a' = a(A), ab' = ab(A), abc' = abc(A) + ab(A)
Now sum over all assignments of these values:
Sum a' = sum_A ( (a+1) + a + a ) = sum_A (3a + 1) = 3sum a + cnt
Sum ab' = sum_A ( ab + (ab + a) + ab ) = sum_A (3ab + a) = 3sum ab + sum a
Sum abc' = sum_A ( abc + abc + (abc + ab) ) = sum_A (3abc + ab) = 3*sum abc + sum ab
Thus recurrence holds.
Now for fixed letters, it's similar but only one branch.
So DP is correct.
Thus solution is simple.
Now we should implement.
We must be careful: the input n is given but we can ignore it and just read string, but we can use it to check length.
Now code in Python:
def solve():
import sys
MOD = 10**9+7
data = sys.stdin.read().split()
if not data: return
n = int(data[0])
s = data[1].strip()
cnt = 1
a = 0
ab = 0
abc = 0
for ch in s:
if ch == 'a':
a = (a + cnt) % MOD
elif ch == 'b':
ab = (ab + a) % MOD
elif ch == 'c':
abc = (abc + ab) % MOD
else: # '?'
# new values
new_cnt = (cnt * 3) % MOD
new_a = (3 * a + cnt) % MOD
new_ab = (3 * ab + a) % MOD
new_abc = (3 * abc + ab) % MOD
cnt, a, ab, abc = new_cnt, new_a, new_ab, new_abc
print(abc % MOD)
But wait: In fixed 'a' update, we only add cnt to a, but we also need to consider that cnt remains same. But is there any effect on ab or abc? No.
But careful: In fixed 'b' update, we add a to ab, but we must not also inadvertently add something to a. That's fine.
Now test on given examples:
Example1: as computed, 24.
Example2: 2835.
Example3: 0.
Example4: 46.
All good.
But double-check Example2: we computed 2835, matches.
Now we must ensure that we mod correctly; Python ints are fine.
Now time complexity O(n) and space O(1). Good.
Now we can output answer.
Now some may argue that we need to use long long in C++, but we are using Python.
Now I'll produce final answer.
But before final, let's consider if there is any other interpretation: The problem asks for total number of subsequences "abc" in all resulting strings. Our DP counts exactly that.
Now we should also confirm that the DP correctly handles overlapping subsequences. Yes, because it counts all triples.
Now we can deliver.
Now I'll write final solution with explanation.
But the problem may require mod 1e9+7.
Now finalize.
Wait: There's a nuance: In the DP for fixed 'a', we did a = a + cnt. But what about the effect on cnt? cnt remains unchanged. But what about the "number of assignments"? Indeed, for fixed letter, cnt doesn't change because we are not adding any new choices. That's correct.
Now all good.
Now I'll produce final answer.
But I realize that the DP as described might have an issue: When we process '?', we used old cnt to compute new_a. However, in the formula new_a = 3a + cnt, we used old cnt. But note: after computing new_cnt = 3cnt, we assign cnt = new_cnt, but we used old cnt for new_a, which is correct. In the sequential assignment we compute new values using old cnt, a, ab, abc before updating.
Our code uses separate variables: new_cnt = cnt3, new_a = 3a + cnt, etc., then assign. That's correct.
Alternatively, we could do:
cnt = (cnt * 3) % MOD
a = (3 * a + cnt_old) % MOD
But we need cnt_old, so better compute with temps.
Thus our code is fine.
Now I'll produce final answer.
But to be thorough, test with a random small string and compare brute force for n up to maybe 8. Could do mentally but not needed.
Now final.
Potential pitfalls: reading input: there might be newline, but using split works.
Now produce final solution.
But also note that n can be up to 200000, the string length is n, so it's fine.
Now finalize.
I'll now write the answer. ```python
import sys
MOD = 10**9 + 7
def solve() -> None:
data = sys.stdin.read().split()
if not data:
return
n = int(data[0])
s = data[1].strip()
cnt = 1 # number of assignments for processed prefix
a = 0 # total number of 'a's over all assignments
ab = 0 # total number of "ab" subsequences
abc = 0 # total number of "abc" subsequences (the answer)
for ch in s:
if ch == 'a':
a = (a + cnt) % MOD
elif ch == 'b':
ab = (ab + a) % MOD
elif ch == 'c':
abc = (abc + ab) % MOD
else: # ch == '?'
new_cnt = (cnt * 3) % MOD
new_a = (3 * a + cnt) % MOD
new_ab = (3 * ab + a) % MOD
new_abc = (3 * abc + ab) % MOD
cnt, a, ab, abc = new_cnt, new_a, new_ab, new_abc
print(abc % MOD)
if name == "main":
solve()