You are given a string s. Write a function to find the length of the longest "awesome" substring. An awesome substring is a non-empty substring of s that has an equal number of 'a's, 'b's, and 'c's. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given a string s. We need to find the length of the longest substring that has an equal number of 'a', 'b', and 'c'. So the substring must have count(a) = count(b) = count(c).
Let's think about it. For a substring, we want the counts to be equal. That means that if we denote the difference between counts of each letter, we can use some prefix sum technique.
Observation: For a substring from i to j (0-indexed, substring s[i:j+1]), we have:
Let A, B, C be counts of 'a','b','c' in that substring. Condition: A=B=C.
We can also think in terms of differences: A-B=0 and A-C=0. Or equivalently, (A-B) and (A-C) are both zero.
We can define a prefix sum for each letter. Let prefix[i] = (count_a up to i-1, count_b up to i-1, count_c up to i-1). But we can reduce dimensions.
Alternative approach: Since we need A=B and B=C, so A=B and B=C implies A=B=C. But we can also consider A-B and B-C. Or A-B and A-C. But note that A-B=0 and A-C=0 implies B-C=0. So we need two independent differences to be zero.
We can use a state represented by (diff_ab, diff_bc) or (diff_ab, diff_ac). But we can also reduce to one dimension? Not exactly, but we can map the state to a single integer by using base encoding.
Idea: For each prefix, we compute two differences:
Let for a prefix ending at index i (0-indexed, prefix from 0 to i inclusive, but we can define prefix sum array P where P0 = (0,0,0) and P[i] counts up to index i-1). Then for substring from l to r, the differences are:
A - B = (P[r+1].a - P[l].a) - (P[r+1].b - P[l].b) = (P[r+1].a - P[r+1].b) - (P[l].a - P[l].b)
Similarly, A - C = (P[r+1].a - P[r+1].c) - (P[l].a - P[l].c)
So the condition is that for the prefix at r+1 and at l, the differences (a-b) and (a-c) are equal. So we need P[r+1] and P[l] to have the same (a-b, a-c). So we can define a state for each prefix as (a-b, a-c). Then we want to find two prefixes with same state, and maximize the distance between them.
But note: the substring from l to r corresponds to prefix indices l and r+1. So length = (r+1) - l.
So if we have an array of states for prefix indices from 0 to n (where n = len(s)), then for each state value, we want the earliest index it appears and the latest index it appears. Then the longest substring is max over states of (last_index - first_index).
But careful: The state includes two integers. They can be negative. We can represent them as a tuple of two integers.
But wait: Is that sufficient? Because we require A=B=C. But having A-B=0 and A-C=0 ensures A=B and A=C, so indeed B=C as well. So yes.
So algorithm:
Initialize a dictionary first_occurrence to store the first index where a state (diff_ab, diff_ac) appears. We start with prefix index 0: state (0,0) at index 0.
Traverse the string and maintain current counts of a,b,c. For each character at position i (0-indexed), update counts. Then compute diff_ab = count_a - count_b, diff_ac = count_a - count_c. That's the state after processing i characters? Actually, after processing i+1 characters? Let's define prefix index k as the prefix of length k, i.e., after processing k characters. So for prefix index k (0<=k<=n), we have counts of the first k characters. Then for substring starting at l (prefix index l) and ending at r (inclusive), we use prefix indices l and r+1. So we want to consider states for prefix indices from 0 to n.
So we compute state for each prefix index k from 0 to n.
3. For each state, if we have seen it before, then candidate length = current_index - first_index. Update max_length. But note: we want the maximum difference between any two occurrences of the same state. So we can either store the first occurrence and then for each later occurrence, compute difference. But that only gives us the difference with the first occurrence. However, the maximum difference for a given state is indeed between the first and the last occurrence. So if we store the first occurrence and then later update the last occurrence? Alternatively, we can store the minimum index for each state and then when we see the state again, we compute the difference. But to get the maximum overall, we can also store the earliest index and then for each state, we keep updating the maximum length as we see the state again. But that only considers pairs with the first occurrence. What about pairs that are not including the first? For example, if state appears at indices 2,3,5, then the max difference is 5-2=3, but if we only store first and then see at 3, we get 3-2=1, at 5 we get 5-2=3. So that's fine because we always compute current_index minus the first occurrence. That gives the maximum possible for that state because the first occurrence is the smallest index. So indeed, for each state, the maximum length is last_index - first_index, where last_index is the largest index where state appears. So we can simply record the first time we see a state, and then every time we see it again, we compute the difference and update max. But careful: if we see the state multiple times, the difference with the first is always increasing as we go further? Not necessarily monotonic? Actually, if we see the state at indices i1 < i2 < i3, then i3 - i1 is larger than i2 - i1. So by always taking the difference with the first, we get the largest when we see the last. So we can do: for each state, store the first index. Then when we encounter the state at index j, compute j - first_index and update max. That will eventually give the max for that state when we reach the last occurrence.
But what if the state appears only once? Then no substring.
Also note: We must consider that the substring is non-empty. So we require at least one character. That means we need two different prefix indices. So we only compute when we have seen the state before.
So steps:
Initialize state (0,0) at index 0.
max_len = 0.
Traverse k from 1 to n:
update counts based on s[k-1] (since k is prefix index after k characters)
compute state.
if state in first_occurrence:
length = k - first_occurrence[state]
max_len = max(max_len, length)
else:
first_occurrence[state] = k
At the end, return max_len.
But wait: Is it possible that the maximum substring does not start at the first occurrence? For example, if state appears at indices 0,2,4. Then the longest is 4-0=4. But what if we have state at 1,3,5? Then 5-1=4. But if we only store the first occurrence for each state, then for state that first appears at 1, we get 5-1=4. But what if we have state that appears at 0,2,5? Then 5-0=5. That is captured because we stored first at 0. But what if the state also appears at 3? Then 3-0=3, but that's smaller than 5-0. So indeed, the maximum for a state is last_index - first_index. So storing first is enough because when we see the last, we compute that difference.
But caution: What if the state appears at indices 0 and then later at 2, and then at 4, and then at 6? We compute at index 2: 2-0=2, at index 4: 4-0=4, at index 6: 6-0=6. So we get increasing. So by the time we finish, we have the max.
But what if the state appears at 0, then at 3, then at 1? That can't happen because indices are increasing as we traverse. So we only encounter indices in increasing order. So first_occurrence stores the smallest index. Then every time we see the state, we compute current_index - first_index, which is increasing as current_index increases. So the last time we see the state gives the maximum difference. So we can simply do as above.
But wait: There is a subtlety: The state is defined by (diff_ab, diff_ac). These differences can be large? The string length up to? Not specified, but we assume reasonable. We can store them as tuples.
But is there a possibility that we need to consider states that are not exactly the same? Actually, our reasoning is correct: For substring to have equal counts, we need the differences to be zero. But note: We defined state as (a-b, a-c). Then condition is that state at l and r+1 are equal. So yes.
Example: s = "abc".
Index 0: state (0,0) at prefix index 0.
After 'a': counts a=1,b=0,c=0 => diff_ab=1, diff_ac=1 -> state (1,1)
After 'b': counts a=1,b=1,c=0 => diff_ab=0, diff_ac=1 -> state (0,1)
After 'c': counts a=1,b=1,c=1 => diff_ab=0, diff_ac=0 -> state (0,0)
We see state (0,0) again at index 3. So length = 3-0 = 3. But the substring from index 0 to 2 is "abc" which has equal counts. So that works.
What about s = "aabc"?
Prefix states:
0: (0,0)
After 'a': (1,1)
After 'a': (2,2)
After 'b': (1,2) ? Actually: after two 'a's: a=2,b=0,c=0 -> diff_ab=2, diff_ac=2. Then after 'b': a=2,b=1,c=0 -> diff_ab=1, diff_ac=2.
After 'c': a=2,b=1,c=1 -> diff_ab=1, diff_ac=1 -> state (1,1) which we saw at index1? At index1 state was (1,1). So we have state (1,1) at prefix index 1 and 4. So length = 4-1=3. That substring is from index1 to 3? indices: prefix index1 means after first character, so substring from l=1 to r=3? That gives s[1:4] = "abc"? Actually s="aabc", indices: 0:'a',1:'a',2:'b',3:'c'. Substring from l=1 to r=3 is "abc" which has one a,b,c? No: it has one a, one b, one c? Actually at index1 it's 'a', index2 'b', index3 'c': so indeed one each. But wait: the substring "abc" starting at index1? That gives characters: s[1]='a', s[2]='b', s[3]='c' => counts a=1,b=1,c=1. Yes. But what about substring from index0 to index2? That's "aab" not equal. So longest is 3. But also substring from index0 to index3? That's "aabc": a=2,b=1,c=1 not equal. So 3 is correct.
But also note: we might have state (0,0) at index0 and index3? At index3: after processing "aab", we had state (1,2). After index4? Actually prefix index4 is after processing all 4 characters? No, we have 4 characters, so prefix indices from 0 to 4. At index4: after "aabc", we have state (1,1) as computed. Not (0,0). So we didn't get state (0,0) at index4. But at index0 and index3 we got (0,0) and (0,0)? Actually at index3 we had (0,0) for s="abc". For s="aabc", at index3 we had (1,2). So no.
So algorithm seems correct.
But wait: What about substrings that do not start at the beginning? Our method considers all substrings because we consider all pairs of prefix indices.
But there is a catch: The state (diff_ab, diff_ac) can be large in magnitude. But we can store as tuple. The number of distinct states? Possibly O(n^2) worst-case? Actually, the differences can range from -n to n, so there are O(n^2) possible pairs? But we only encounter n+1 states, so dictionary size O(n). That's fine.
But is there a possibility of optimization? Possibly, but not needed.
However, we must consider that the string may contain only 'a','b','c'? The problem says substring with equal number of 'a','b','c'. It might contain other characters? The problem statement says: "An awesome substring is a non-empty substring of s that has an equal number of 'a's, 'b's, and 'c's." It doesn't say the string only contains a,b,c. So there could be other characters. But then what does it mean? It says "equal number of 'a's, 'b's, and 'c's". That means among the characters that are 'a','b','c', their counts are equal. But there could be other letters that we ignore? Or does it mean that the substring must have only a,b,c and they are equal? The problem likely implies that the string consists of only a,b,c? But it doesn't explicitly say. Let's read the original problem? This is a known LeetCode problem: "Longest Awesome Substring" but that one is about digits and having at most one odd count. But here it's about equal counts of a,b,c. I recall a problem "Longest Substring with Equal Number of 0s, 1s, and 2s" which is similar. Usually the string contains only '0','1','2'. So I'll assume s only contains 'a','b','c'. But if there are other letters, then we ignore them? Actually, the condition is about counts of 'a','b','c' being equal. So if there is a 'd', it doesn't affect the equality? But then the substring could have other letters and still have equal a,b,c counts. But the problem says "equal number of 'a's, 'b's, and 'c's". It doesn't say that the substring must consist only of these. So we should consider that other characters are allowed and they don't contribute to the counts. But then our counting method: we only count a,b,c. For other characters, we don't change the counts. So in our prefix sums, we only increment counts for 'a','b','c'. That is fine.
But careful: The state (a-b, a-c) only depends on counts of a,b,c. So if there is a character that is not a,b,c, we simply do not change counts. So our update step: when we see a character, if it is 'a', increment a; if 'b', increment b; if 'c', increment c; otherwise, do nothing.
Then the condition for substring to have equal number of a,b,c is that the state at two prefix indices are equal. That still holds because the differences in counts between the two prefixes are the counts in the substring. So it's fine.
But what if the substring has no a,b,c at all? Then counts are all zero, so equal. But is that considered? The substring must have equal number of a,b,c. If there are zero of each, that is equal. But is an empty substring allowed? The problem says non-empty substring. But if a substring has no a,b,c, then it has zero of each, so it satisfies? But then any substring that contains no a,b,c would be awesome. For example, if s = "def", then any non-empty substring has zero a,b,c, so all substrings are awesome? But that seems odd. Usually, the problem implies that we consider only a,b,c. But let's read: "has an equal number of 'a's, 'b's, and 'c's." That means the count of 'a' equals count of 'b' equals count of 'c'. If there are none, then 0=0=0, so yes. So any substring that contains no a,b,c is awesome. Then the longest awesome substring would be the entire string if it has no a,b,c? But that would be trivial: if the string has no a,b,c, then the whole string is awesome. But then the problem becomes: find the longest substring with equal counts of a,b,c, including possibly zero counts. But then if the string has some a,b,c, we might have substrings with zero counts? For example, s = "a" -> substrings: "a" has a=1,b=0,c=0 not equal. Substrings with no a,b,c? There are none because the string only contains 'a'. So not all substrings are awesome. But if there is a part of the string that has no a,b,c, then that part is awesome. So we need to consider that.
But in our method, we only count a,b,c. So for a substring that has no a,b,c, the counts of a,b,c are all zero. That means the state at the two prefix indices must be equal. But note: our state includes differences a-b and a-c. If there are no a,b,c in the substring, then the counts don't change, so the state at the two prefix indices is the same. So our method would capture that as well. But then what is the state? For example, suppose we have a substring that consists only of 'd's. Then from prefix index l to r+1, the counts of a,b,c don't change, so state at l and r+1 are identical. So we would get a substring of length (r+1)-l. But that substring might be long if there is a long run of non-abc characters. But is that allowed? The problem says "has an equal number of 'a's, 'b's, and 'c's." It doesn't require that there is at least one of each? It says "equal number", which includes zero. So yes.
But then consider s = "aaaa". All substrings have a>0, b=0, c=0, so not equal unless the substring has no a? But if it has no a, then it must have no b and no c, so it would be a substring with no a,b,c. But in "aaaa", every non-empty substring contains at least one 'a', so it has a>0, b=0, c=0, so not equal. So no awesome substring? But wait, what about the empty substring? Non-empty required. So answer 0? But the problem says non-empty substring, so if none exists, we should return 0? But usually they ask for the length, so if none, return 0.
But in our method, we would not find any pair of prefix indices with same state? Actually, we always have state (0,0) at index 0. But then when we process characters, state changes. For "aaaa", after first 'a': (1,1). After second: (2,2). After third: (3,3). After fourth: (4,4). So states: index0: (0,0); index1: (1,1); index2: (2,2); index3: (3,3); index4: (4,4). All distinct. So no pair except possibly if state repeats? They don't repeat. So max_len remains 0. That is correct.
But what about s = "d"? Then states: index0: (0,0); after 'd': still (0,0) because no change. So at index1, state (0,0) is seen before at index0. So length = 1-0=1. That gives substring from index0 to index0? Actually, prefix index l=0 and r+1=1 gives substring s[0:1] = "d". That has zero a,b,c, so equal. So answer 1. That seems correct according to the definition.
But is that intended? Possibly the problem expects only substrings that contain at least one of each? But it doesn't say. Usually in such problems, zero counts are allowed. But let's check known problem: On LeetCode, there is "Longest Substring with Equal Number of 0s and 1s" which allows zero counts? For that problem, the substring must have equal number of 0s and 1s, and it can have other characters? Actually, that problem typically the string is binary. But here, if we have other characters, they are ignored? The condition is only about a,b,c. So I think our interpretation is correct.
But wait: The problem statement says: "An awesome substring is a non-empty substring of s that has an equal number of 'a's, 'b's, and 'c's." It doesn't mention other characters. So we assume that the string may contain any characters, but we only care about counts of a,b,c. So our method works.
But there is another nuance: The substring must have equal numbers of a,b,c. That means that the counts are equal. But if the substring has, say, 2 a, 2 b, 2 c, that's fine. But also if it has 0 a, 0 b, 0 c, that's fine. So our state method captures both.
However, is it possible that the state repeats but the substring in between does not have equal counts? Let's check: Suppose we have state at l and r+1 equal. Then for the substring from l to r, the differences in counts of a-b and a-c are both zero. That means A-B=0 and A-C=0, so A=B and A=C, so A=B=C. So yes.
So algorithm is correct.
But we must be careful about the representation of state. We use (a-b, a-c). These integers can be negative. That's fine.
Complexity: O(n) time and O(n) space.
But wait: Could there be an issue with overflow? The differences can be as large as n in absolute value. But n is length of string, so we can store as integers.
Now, let's test with some examples.
Example 1: s = "abc" -> max_len=3.
Example 2: s = "aabc" -> max_len=3.
Example 3: s = "abcc" ->
prefix states:
0: (0,0)
1: after 'a' -> (1,1)
2: after 'b' -> (0,1)
3: after 'c' -> (0,0) -> state (0,0) seen at index0, length=3-0=3? Actually, index3 corresponds to after three characters? Wait, indices: we have s="abcc", length 4.
prefix index0: before any char.
After char0 'a': prefix index1: (1,1)
After char1 'b': prefix index2: (0,1)
After char2 'c': prefix index3: (0,0)
After char3 'c': prefix index4: (0,-1)? Actually after second 'c': counts: a=1,b=1,c=2 -> diff_ab=0, diff_ac=-1.
So states: (0,0) at index0 and index3. So substring from l=0 to r=2? That is s[0:3]="abc", length 3. That is correct. Also at index4 state (0,-1) new.
So max=3.
But what about substring "bcc"? That has b=1,c=2,a=0 -> not equal. So 3 is correct.
Example 4: s = "aabbbcc" ->
We want equal counts? Perhaps substring "abbc"? But counts: a=1,b=2,c=1 not equal. Maybe "abbbc"? a=1,b=3,c=1 not. Actually, we need all three equal. So possible: "abc" from somewhere? But there is "abc"? The string is "aabbbcc". The only 'a's are at start. So maybe substring "abbbcc"? That has a=1,b=3,c=2 no. "aabbbc"? a=2,b=3,c=1 no. "aabbbcc": a=2,b=3,c=2 no. So maybe there is no substring with equal counts? But wait, what about substring that has zero a? Then we need zero b and zero c, so only non-abc characters? But there are none. So maybe answer 0? But let's check systematically.
We can compute states.
prefix0: (0,0)
1: after 'a': (1,1)
2: after 'a': (2,2)
3: after 'b': (1,2) because a=2,b=1 -> diff_ab=1, diff_ac=2.
4: after 'b': (0,2) a=2,b=2 -> diff_ab=0, diff_ac=2.
5: after 'b': (-1,2) a=2,b=3 -> diff_ab=-1, diff_ac=2.
6: after 'c': (-1,1) a=2,b=3,c=1 -> diff_ab=-1, diff_ac=1.
7: after 'c': (-1,0) a=2,b=3,c=2 -> diff_ab=-1, diff_ac=0.
So states: (0,0), (1,1), (2,2), (1,2), (0,2), (-1,2), (-1,1), (-1,0). All distinct? Yes. So no repeat. So max_len=0. That seems correct.
But wait, what about substring from index2 to index6? That is "bbbcc"? No 'a', so a=0, b=3, c=2 -> not equal. So indeed no.
So algorithm works.
But is there a possibility that the maximum substring has length that is a multiple of 3? Not necessarily, because we can have other characters. For example, if we have a substring with 2 a, 2 b, 2 c and some other letters, that's length 6+others. But our condition only cares about a,b,c counts being equal, not about total length. So the substring length can be anything as long as the counts of a,b,c are equal. The other characters don't matter.
But in our state method, we only count a,b,c. So the state differences are based solely on a,b,c. So it's correct.
Now, what about performance? We traverse the string once, and dictionary operations are O(1) average. So O(n) time and space.
But can we reduce space? Possibly by using a fixed-size array if we know the range of differences? The differences can range from -n to n, so that's O(n) range. But we have two dimensions, so O(n^2) states possible, but we only store at most n+1 states. So dictionary is fine.
But we might be able to use a single integer key by encoding: (diff_ab + offset) * (2*n+1) + (diff_ac + offset). But we need to handle negative. But not necessary.
Now, what about the initial state? We set first_occurrence for state (0,0) at index 0. That is important because a substring starting at index0 with equal counts would be captured when we see state (0,0) again later.
Now, consider the case where the entire string is awesome. Then we will have state (0,0) at index n. Then length = n - 0 = n.
Now, let's implement the function.
Function signature: def longest_awesome(s: str) -> int:
But the problem says "Write a function to find the length of the longest 'awesome' substring." So we return an integer.
Now, we need to explain the algorithm. We'll write the code and then an explanation.
But before finalizing, let's think if there is any edge case: string empty? s empty -> then no non-empty substring, return 0. Our method: we initialize with state (0,0) at index0, then we don't traverse because n=0, so max_len remains 0. That's correct.
String with one character that is not a,b,c? Then state at index1 is same as index0? Actually, if character is 'd', we do nothing, so state remains (0,0). So we see state (0,0) at index1, and first_occurrence has (0,0) at index0, so length=1-0=1. That is correct: substring "d" has zero a,b,c.
If the character is 'a', then state becomes (1,1), not seen before, so no update. So max_len=0. That is correct because "a" has a=1,b=0,c=0 not equal.
So that seems consistent.
But wait: What about a substring that has a,b,c counts equal but not necessarily all zero? Our method captures that as well.
Now, I recall a similar problem: "Find the longest substring with equal number of 0s, 1s and 2s" which uses the same technique.
So we are good.
But there is a known trick: Instead of two differences, we can use one difference by noting that if A=B=C, then A-B=0 and B-C=0. But that's two. Alternatively, we can define state as (a-b, b-c). That also works. But any two independent differences work.
But we can also use a single value: Since A-B and A-C determine B-C? Actually B-C = (A-C)-(A-B). So if both are zero then B-C=0. But we need both to be zero. So state must be two-dimensional.
Alternatively, we can use a single key by offsetting and combining.
Now, I'll write the code.
Implementation details:
We'll have counts a, b, c as integers.
first_occurrence = {} # dict mapping state tuple to first index.
Initialize: first_occurrence[(0,0)] = 0.
max_len = 0.
For i in range(n): # i from 0 to n-1, processing s[i]
if s[i]=='a': a+=1
elif s[i]=='b': b+=1
elif s[i]=='c': c+=1
else: do nothing
diff_ab = a - b
diff_ac = a - c
state = (diff_ab, diff_ac)
if state in first_occurrence:
length = (i+1) - first_occurrence[state]
max_len = max(max_len, length)
else:
first_occurrence[state] = i+1
Return max_len.
That's it.
But wait: What about the possibility that the state (0,0) appears at index0 and then later at some index, we compute length. But what if the state (0,0) appears again at index k, then we get length k. But also if it appears at index l later, we get l. So we get the maximum when we see the last occurrence.
But what if the state appears multiple times? We only store the first occurrence. So when we see it at index j, we compute j - first. That's fine.
But is there a case where the maximum substring does not correspond to the first occurrence of that state? For example, suppose state S appears at indices 0, 2, 4. Then the substring from 0 to 3 (prefix indices 0 and 4) gives length 4. But what about substring from 2 to 3? That is length 2. So maximum is 4. So by using first occurrence, we get 4 when we see index4. But what if state S appears at indices 1, 3, 5? Then first is 1, and at index5 we get 4. That's the maximum. So it's fine.
But what if state S appears at indices 0 and 3 only? Then we get length 3. That's fine.
So storing only the first occurrence is sufficient for the maximum difference because the first occurrence is the smallest index.
But consider: What if we have state S that appears at indices 2 and 5, and also at index1? Actually, if it appears at index1 and index2, then first is 1. At index2 we compute 1, at index5 we compute 4. But what about pair (2,5)? That gives 3, which is less than 4. So the max is indeed with the first.
But what if the state appears at indices 2 and 5, but not at index1? Then first is 2, at index5 we compute 3. That's the max. So it's fine.
But what if the state appears at indices 0, 10, and 20. Then we compute at 10: 10, at 20: 20. So we get 20. But what about pair (10,20)? That gives 10, less than 20. So maximum is with the first.
Thus, storing only the first occurrence is enough.
But wait: What if the state appears at indices 0 and 20, but also at index10. Then we compute at index10: 10, at index20: 20. So we get 20. That's the max. So yes.
Therefore, the algorithm is correct.
Now, we should also consider that the substring might be of length 0? Non-empty, so we don't consider length 0.
Now, I'll write the function and explanation.
But the problem says "Write a function that solves this problem, and explain your algorithm." So we need to provide both.
I'll write in Python.
Optimization: We can use a single dictionary. But what about memory? For large n, we store at most n+1 states. That's O(n). That's acceptable.
Now, I'll produce the final answer.
But before final, let's test with a case that has other characters: s = "daabec".
We want longest substring with equal a,b,c.
Compute manually:
"daabec": characters: d, a, a, b, e, c.
Counts for substrings:
We can look for substring with equal a,b,c.
Maybe "aabec"? a=2,b=1,c=1 no.
"daabe"? a=2,b=1,c=0 no.
"abec"? a=1,b=1,c=1 yes! That's "abec" from index1 to 4? Actually indices: 0:d,1:a,2:a,3:b,4:e,5:c. "abec" would be indices 2,3,4,5? That's "abec"? Actually index2='a',3='b',4='e',5='c' -> that has a=1,b=1,c=1? But there is an 'e' which we ignore. So counts: a=1,b=1,c=1. So yes. Length 4.
Also "daabec" whole string? a=2,b=1,c=1 no.
So answer should be 4.
Let's run our algorithm:
prefix0: (0,0) at index0.
i=0, char 'd': no change -> state (0,0). Seen at index0? Actually we are at i=0, so prefix index is i+1=1. State (0,0) is in first_occurrence (at index0). So length = 1-0=1. max_len=1.
But wait, we just processed the first character 'd', and we got state (0,0) at prefix index1. That means substring from index0 to index0? That's "d", which has zero a,b,c, so it is awesome. So length 1 is valid. But we are looking for the longest, so that's fine.
i=1, char 'a': a=1, state (1,1). Not seen. first_occurrence[(1,1)]=2? Actually index is i+1=2.
i=2, char 'a': a=2, state (2,2). New. first_occurrence[(2,2)]=3.
i=3, char 'b': a=2,b=1 -> diff_ab=1, diff_ac=2? Actually a=2,c=0 -> diff_ac=2. state (1,2). New. first_occurrence[(1,2)]=4.
i=4, char 'e': no change, state remains (1,2). But wait, we just processed 'e', so state same as before? Actually after processing 'e', counts are still a=2,b=1,c=0? No, we have not seen c yet. So state is (2-1=1, 2-0=2). So (1,2). This state was seen at index4? Actually we stored it at index4? At i=3 we stored state (1,2) at prefix index4. Now at i=4, prefix index5, state is still (1,2). So we see it again. Then length = 5 - first_occurrence[(1,2)] = 5-4=1. So we get a substring of length 1? That would be from l=4 to r=4? That is the substring consisting of 'e'? That has zero a,b,c? Actually, from prefix index4 to prefix index5: that corresponds to s[4:5] which is 'e'. That has zero a,b,c, so it is awesome. But we already have length 1 from the first 'd'. But we want longer. So we continue.
i=5, char 'c': a=2,b=1,c=1 -> diff_ab=1, diff_ac=1. state (1,1). We have seen (1,1) at prefix index2? Actually we stored (1,1) at index2. So length = 6-2=4. That gives max_len=4. That corresponds to substring from l=2 to r=5? prefix index2 means after first 2 characters? Actually prefix index2 is after processing s[0] and s[1]. That is "da". So l=2 means starting at index2? Wait: substring from l to r is given by prefix indices l and r+1. So if prefix index l=2 and r+1=6, then r=5. So substring from index2 to 5 inclusive: that is s[2:6] = "abec"? Actually s[2]='a', s[3]='b', s[4]='e', s[5]='c' -> "abec". Yes, that has a=1,b=1,c=1. So length 4. That's the answer.
So our algorithm returns 4. Good.
Now, what about a substring that starts at index0? For example, s = "abcabc".
Prefix states:
0: (0,0)
1: after 'a' -> (1,1)
2: after 'b' -> (0,1)
3: after 'c' -> (0,0) -> length 3
4: after 'a' -> (1,1) -> seen at index1, length 4-1=3? Actually that gives substring from index1 to 3? That's "bca"? But we have also at index6? Let's compute fully.
After 'a': index1: (1,1)
After 'b': index2: (0,1)
After 'c': index3: (0,0) -> length 3-0=3.
After 'a': index4: (1,1) -> length 4-1=3.
After 'b': index5: (0,1) -> length 5-2=3.
After 'c': index6: (0,0) -> length 6-0=6.
So max=6. That is the entire string, which has 2 each. So correct.
Now, what about s = "aaabbbccc"? That has 3 each. But the entire string has 3 a,3 b,3 c? Actually it has 3 a,3 b,3 c. So state at index9 should be (0,0). But also at index0. So length 9. But wait, the string is "aaabbbccc", so after processing all, counts a=3,b=3,c=3 -> diff_ab=0, diff_ac=0. So yes, state (0,0) at index9. So length 9. But are there other substrings? Possibly longer? No.
But what about s = "abcabcabc"? That also gives state (0,0) at the end? Actually after 9 characters, a=3,b=3,c=3, so (0,0). So length 9.
But what about s = "abacaba"? That has a=4,b=1,c=1? Not equal. But maybe substring "bac"? b=1,a=1,c=1? That is length 3. But let's compute:
s = "abacaba"
prefix0: (0,0)
1: 'a' -> (1,1)
2: 'b' -> (0,1)
3: 'a' -> (1,1) -> seen at index1, length 3-1=2? That's substring from index1 to 2? That is "ba"? a=1,b=1,c=0 not equal. Wait, state at index1 is (1,1). At index3 we have (1,1) again. That means from l=1 to r=2? Actually prefix index1 and 3: substring s[1:3] = "ba". That has a=1,b=1,c=0. But our state condition says A-B=0 and A-C=0? Here A=1,B=1,C=0, so A-B=0 but A-C=1 not zero. So why did we get state (1,1) both? Let's recalc:
After first character 'a': a=1,b=0,c=0 -> diff_ab=1, diff_ac=1 -> state (1,1).
After second character 'b': a=1,b=1,c=0 -> diff_ab=0, diff_ac=1 -> state (0,1).
After third character 'a': a=2,b=1,c=0 -> diff_ab=1, diff_ac=2 -> state (1,2). I made a mistake!
Let's do carefully:
s = "abacaba"
Indices: 0:a,1:b,2:a,3:c,4:a,5:b,6:a.
counts:
prefix0: (0,0)
i=0, char 'a': a=1 -> state (1,1)
i=1, char 'b': a=1,b=1 -> state (0,1) because a-b=0, a-c=1.
i=2, char 'a': a=2,b=1 -> state (1,2) because a-b=1, a-c=2.
i=3, char 'c': a=2,b=1,c=1 -> state (1,1) because a-b=1, a-c=1.
i=4, char 'a': a=3,b=1,c=1 -> state (2,2)
i=5, char 'b': a=3,b=2,c=1 -> state (1,2)
i=6, char 'a': a=4,b=2,c=1 -> state (2,3)
So states:
0: (0,0)
1: (1,1)
2: (0,1)
3: (1,2)
4: (1,1) -> seen at index1, so length = 4-1=3? That corresponds to substring from l=1 to r=3? That is s[1:4] = "bac"? Actually indices: l=1 means starting at index1? prefix index1 means after first character? So substring from index1 to index3 inclusive? That is s[1], s[2], s[3] -> 'b','a','c'. That has a=1,b=1,c=1. Yes! So length 3.
Then later at i=5: state (1,2) seen at index3, so length = 6-3=3? That gives substring from index3 to 5? s[3:6] = "cab"? That has a=1,b=1,c=1? Actually s[3]='c', s[4]='a', s[5]='b' -> a=1,b=1,c=1. Yes.
And at the end: state (2,3) new.
So max length is 3.
But also we have state (0,0) only at index0. So no longer.
So algorithm works.
Now, what about the substring that starts at index0? For example, if we have state (0,0) at index0 and later at indexk, then substring from 0 to k-1 has equal counts. That is captured.
So all good.
Now, we should write the explanation clearly.
Explanation:
We use prefix sums and a hash map to store the first occurrence of each state defined by the differences between counts of 'a' and 'b', and between 'a' and 'c'. The idea is that for any substring s[l...r], the differences in counts of 'a','b','c' between the two endpoints (prefix l and prefix r+1) must be zero. So if the state at prefix l equals the state at prefix r+1, then the substring has equal numbers of 'a','b','c'. By tracking the earliest index for each state, we can compute the maximum length when we encounter a repeated state.
Complexity: O(n) time, O(n) space.
Now, code.
But wait: There is an alternative interpretation: The problem might be from LeetCode 1542. "Find Longest Awesome Substring" but that is about digits and having at most one odd count. That is different. So I think this is a custom problem.
But anyway.
Now, I'll write the function.
One more thing: We should be careful about the variable naming. I'll use a,b,c for counts.
But what if the string is huge? The state tuple might be hashed efficiently. That's fine.
Now, let's write the code.
def longest_awesome(s: str) -> int:
# first_occurrence: dict mapping (diff_ab, diff_ac) to the first index (prefix index) where it occurs.
first_occurrence = {}
# initial state at prefix index 0
first_occurrence[(0,0)] = 0
a = b = c = 0
max_len = 0
for i, ch in enumerate(s):
if ch == 'a':
a += 1
elif ch == 'b':
b += 1
elif ch == 'c':
c += 1
# else: no change
diff_ab = a - b
diff_ac = a - c
state = (diff_ab, diff_ac)
prefix_index = i+1 # because we have processed i+1 characters
if state in first_occurrence:
length = prefix_index - first_occurrence[state]
if length > max_len:
max_len = length
else:
first_occurrence[state] = prefix_index
return max_len
That should work.
But let's test with the examples we did.
I'll run mentally.
Now, is there any possibility of integer overflow? No.
But what about the state being a tuple? That's fine.
Now, we can also consider using a single integer key to avoid tuple overhead? But not necessary.
Now, I'll produce the final answer with explanation and code.
But the user asked: "Please write a function that solves this problem, and explain your algorithm." So we need to output both.
I'll structure the response: first the explanation, then the code.
But since it's a single response, I'll combine.
Now, what about the possibility that the substring has equal counts but we might have multiple states? Our method is correct.
One more test: s = "abcabc" -> we got 6.
s = "aabbcc" -> does it have a substring with equal counts? The whole string: a=2,b=2,c=2, so yes, length 6. Our algorithm: states?
prefix0: (0,0)
1: after 'a' -> (1,1)
2: after 'a' -> (2,2)
3: after 'b' -> (1,2) because a=2,b=1 -> diff_ab=1, diff_ac=2.
4: after 'b' -> (0,2) a=2,b=2 -> diff_ab=0, diff_ac=2.
5: after 'c' -> (0,1) a=2,b=2,c=1 -> diff_ab=0, diff_ac=1.
6: after 'c' -> (0,0) -> length 6-0=6. So correct.
Now, what about s = "abac" -> we had a substring "bac" of length 3. But also "abac" whole? a=2,b=1,c=1 not equal. So max 3. Our algorithm:
prefix0: (0,0)
1: 'a' -> (1,1)
2: 'b' -> (0,1)
3: 'a' -> (1,2)
4: 'c' -> (1,1) -> seen at index1, length=4-1=3. So max=3. Correct.
Now, consider s = "cba" -> similar to "abc", should give 3.
prefix0: (0,0)
1: 'c' -> a=0,b=0,c=1 -> diff_ab=0, diff_ac=-1? Actually a-b=0, a-c=-1 -> state (0,-1)
2: 'b' -> a=0,b=1,c=1 -> diff_ab=-1, diff_ac=-1 -> state (-1,-1)
3: 'a' -> a=1,b=1,c=1 -> state (0,0) -> length 3-0=3. So correct.
So algorithm works.
Now, we should also consider the case where the string contains only two of the letters? For example, s = "abab" -> no 'c'. Then can we have substring with equal a,b,c? That would require equal counts of a,b,c. But if there is no c, then to have equal counts we need a=b=c=0. So any substring that contains no a and no b? But the string has a and b. So any substring that contains a or b will have non-zero count for at least one of a or b, but c is zero, so unless a and b are also zero, it won't be equal. So only substrings with no a and no b would work. But if the string has only a and b, then any substring that contains no a and no b? That would be empty or substrings of other characters? But there are no other characters. So no non-empty substring? Actually, if the string has only a and b, then any non-empty substring will have either a or b or both, so at least one of a or b is positive, but c is zero. So to have a=b=c, we need a=b=0 as well. So the only way is if the substring contains no a and no b. That is impossible if the substring is non-empty and the string only contains a and b. So answer 0. But wait, what about substring that has a and b but no c? Then a and b must be equal? But condition is a=b=c, so c must equal a and b. If c=0 then a and b must be 0. So indeed, if the string has no c, then any substring that contains a or b will have a or b positive, so not equal to c=0. So only substrings with no a and no b would work, but that would be empty or substrings of other letters? But there are none. So answer 0.
But what if the string has other letters? For example, s = "abx". Then substring "x" has zero a,b,c, so length 1. So that works.
So in the case of only a and b, our algorithm:
s="abab"
prefix0: (0,0)
1: 'a' -> (1,1)
2: 'b' -> (0,1)
3: 'a' -> (1,2)
4: 'b' -> (0,2)
States: (0,0), (1,1), (0,1), (1,2), (0,2). No repeat of (0,0) except at start. So max_len remains 0. That is correct because no substring has equal a,b,c (with c=0). But wait, what about substring "ab"? That has a=1,b=1,c=0. That does not satisfy a=b=c because c=0 but a=1. So not equal. So indeed, no.
But what about substring "ba"? same.
So algorithm gives 0.
But what about substring "abab"? a=2,b=2,c=0 not equal.
So correct.
Now, what if the string has only 'a' and 'c'? Similar.
So our algorithm handles all cases.
Now, I think it's correct.
But wait: There is a subtle point: Our state uses (a-b, a-c). But what if we have a substring that has a=b=c, but the state at l and r+1 are equal. That is correct. But is it possible that the state at l and r+1 are equal but the substring does not have equal counts? Let's check:
State at l: (a_l - b_l, a_l - c_l)
State at r+1: (a_{r+1} - b_{r+1}, a_{r+1} - c_{r+1})
Difference:
(a_{r+1}-b_{r+1}) - (a_l - b_l) = (a_{r+1}-a_l) - (b_{r+1}-b_l) = A - B.
Similarly for a-c: A - C.
So if states are equal, then A-B=0 and A-C=0. So A=B and A=C, so A=B=C. So yes.
Thus, necessary and sufficient.
So we are done.
Now, I'll write the final answer.
But the user might expect the function to be named something specific? They said "Write a function". So I'll define it as def longest_awesome(s): or maybe def longestAwesome(s):? I'll use snake_case as per Python convention.
But since it's a coding problem, I'll provide a clear function.
Now, for the explanation, I'll write a paragraph.
I'll produce:
Algorithm:
We use the concept of prefix sums for counts of 'a', 'b', 'c'. For each prefix index i (from 0 to n), we compute the counts of 'a', 'b', 'c' in the first i characters. For any substring from l to r, the counts in that substring are given by subtracting prefix counts at l from those at r+1. The condition for the substring to be awesome is that the number of 'a's equals the number of 'b's and equals the number of 'c's. This is equivalent to (A-B=0) and (A-C=0). Therefore, if we define a state as the pair (a-b, a-c) for a prefix, then two prefixes having the same state implies that the substring between them has equal numbers of 'a','b','c'. We traverse the string, maintaining the current counts and state. We keep a dictionary mapping each state to the first prefix index where it occurs. Whenever we encounter a state that has been seen before, we compute the length as current_prefix_index - first_index, and update the maximum length. The answer is the maximum length found.
Complexity: O(n) time, O(n) space.
Code:
Now, I'll output the code.
But wait: We need to handle other characters? We already do by not changing counts for non-abc.
Now, final answer.
Algorithm Explanation
We need the longest substring where the counts of 'a', 'b', and 'c' are equal.
For any substring s[l..r], let A, B, C be its counts of 'a', 'b', 'c'. The condition A = B = C is equivalent to A − B = 0 and A − C = 0.
Using prefix sums, define for prefix index i (the first i characters) the counts a_i, b_i, c_i.
For substring s[l..r], we have:
code
A = a_{r+1} − a_l, B = b_{r+1} − b_l, C = c_{r+1} − c_l
Thus A − B = (a_{r+1} − b_{r+1}) − (a_l − b_l) and similarly for A − C.
So the substring is awesome iff the state (a_i − b_i, a_i − c_i) at prefix l equals the state at prefix r+1.
We traverse the string, maintaining current counts and the current state.
A dictionary first_occurrence maps each state to the first prefix index where it appears.
Initially, prefix index 0 (empty prefix) has state (0,0).
For each character:
Update counts for 'a', 'b', 'c' (ignore other characters).
Compute current state (a−b, a−c) and current prefix index i+1.
If the state has been seen before, the substring from the first occurrence to the current position is awesome; its length is (i+1) − first_index. Update the maximum length.
Otherwise, record the current prefix index as the first occurrence of this state.
The maximum length found is the answer. If no awesome substring exists, we return 0.
Complexity
Time: O(n), one pass over the string.
Space: O(n) for the dictionary (at most n+1 distinct states).
Code
python
def longest_awesome(s: str) -> int:
"""
Returns the length of the longest substring of s that has an equal number
of 'a's, 'b's, and 'c's.
"""
# Map state (diff_ab, diff_ac) to the earliest prefix index where it occurs.
first_occurrence = {}
first_occurrence[(0, 0)] = 0 # empty prefix
a = b = c = 0
max_len = 0
for i, ch in enumerate(s):
if ch == 'a':
a += 1
elif ch == 'b':
b += 1
elif ch == 'c':
c += 1
# Other characters are ignored (no change to counts)
diff_ab = a - b
diff_ac = a - c
state = (diff_ab, diff_ac)
prefix_idx = i + 1 # after processing s[i]
if state in first_occurrence:
length = prefix_idx - first_occurrence[state]
if length > max_len:
max_len = length
else:
first_occurrence[state] = prefix_idx
return max_len