← Questions

Longest substring without three repeats in a row

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests strings, sliding window and two pointers.

Given a string s, return the length of the longest substring of s in which no character appears three or more times in a row. Call such a substring semi-alternating: runs of one or two equal characters are fine, but a run of three is not.

Implement:

def longest_semi_alternating(s: str) -> int

A substring is a contiguous slice of s. Return 0 for the empty string.

Constraints

  • 0 <= len(s) <= 2 * 10^5
  • s may contain any characters (letters, digits, symbols), not only two letters.
  • Aim for O(n) time and O(1) extra space.

Example 1

s = "kkkhhkkkhh"
output: 6

The triple kkk appears twice. The longest stretch that avoids both is "kkhhkk" (indices 1 to 6).

Example 2

s = "ppqqpp"
output: 6

Every run has length at most two, so the whole string counts.

Interviewers often follow up by asking for the substring itself, a general limit of k repeats, or the number of valid substrings.

Clarifying questions

  • Are equal characters compared exactly, so "a" and "A" differ?
  • For a string shorter than three characters, is the answer its whole length?
  • Do we need only the length, or also where the substring starts?
  • Should a string of one repeated character, such as "aaaa", give 2?

What a strong answer covers

  • Uses one sliding window. When s[i] == s[i - 1] == s[i - 2], the window must restart at i - 1, because any valid substring ending at i can hold at most the last two of the triple.
  • Updates the best length at every index. That is O(n) time and O(1) memory.
  • Explains why the restart point is i - 1 and not i.
  • Tests the empty string, length 1 and 2, "aaaa", a triple at the very start and end, and both examples.

Follow-ups

  • Return the substring itself.
  • A general limit: no character k or more times in a row.
  • Count the valid substrings instead.
  • Find the fewest deletions that make the whole string valid.

Where it's asked

What it tests

strings · sliding window · two pointers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding