TikTok OA Interview Problem: Count Length-3 Substrings Containing a Vowel

20 Views
No Comments

You are given a string chatMessage. Your task is to count the number of substrings of exactly length 3 that contain at least one vowel (a, e, i, o, u, or their uppercase counterparts). Return this number as an integer.

Examples:

For chatMessage = "CodeSignal", the output should be solution(chatMessage) = 8.

The substrings of length 3 are: Cod, ode, deS, eSi, Sig, ign, gna, and nal. All these substrings contain at least one vowel. Thus, the answer is 8.

For chatMessage = "StrEngThen", the output should be solution(chatMessage) = 5.

The substrings of length 3 are: Str, trE, rEn, Eng, ngT, gTh, The, and hen. The substrings that contain at least one vowel are trE, rEn, Eng, The, and hen. Thus, the answer is 5.

Input/Output

  • [execution time limit] 4 seconds (py3)
  • [memory limit] 1 GB
  • [input] string chatMessage
    A sequence of characters representing a chat message.
  • [output] integer
    The number of substrings of exactly length 3 where at least one character is a case-insensitive vowel.

This is a fixed-size sliding window problem: scan every consecutive substring of length 3 and count those that contain at least one vowel, case-insensitively. Because the window length is constant, a simple O(n) pass is enough, optionally maintaining the number of vowels currently in the window. The examples show that strings like "CodeSignal" produce 8, while "StrEngThen" produce 5.

END
 0