FastPrepMaximum Insertions Without Three Consecutive A
Problems/Maximum Insertions Without Three Consecutive A

Maximum Insertions Without Three Consecutive A

Tesla logoTesla● MediumOA
QuestionFunctionExamplesConstraints

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

  • Flatten a Branched List into a Doubly Linked ListPHONE SCREEN · Seen Sep 2026
  • Reduce-Based Map and Filter PipelinePHONE SCREEN · Seen Sep 2026
  • Resilient Fake API ClientPHONE SCREEN · Seen Sep 2026
All Tesla interview questionsSee Tesla hiring insights
Saved
class Solution {
    public int solution(String S) {
      // write your code here
    }
}
Checking account…