Problem · String

Maximum Insertions Without Three Consecutive A

Learn this problem
MediumTesla logoTeslaOA

Problem statement

Write a function solution that, given a string S consisting of N characters, returns the maximum number of letters 'a' that can be inserted into S (including at the front and end of S) so that the resulting string doesn't contain three consecutive letters 'a'. If string S already contains the substring "aaa", then your function should return -1.

Function

solution(S: String) → int

Examples

Example 1

S = "aabab"return = 3

A string "aabaabaa" can be made.

Example 2

S = "dog"return = 8

A string "aadaaoaagaa" can be made.

Example 3

S = "aa"return = 0

No longer string can be made.

Example 4

S = "baaaa"return = -1

There is a substring "aaa".

Constraints

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..200,000].
  • String S is made only of lowercase letters ('a' - 'z').

More Tesla problems

drafts saved locally
public int solution(String S) {
  // write your code here
}
S"aabab"
expected3
checking account