FastPrepCount Magical Adjacent Substring Triplets

Count Magical Adjacent Substring Triplets

Google logoGoogle● HardFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Two nonempty strings form a magical pair when their sets of distinct lowercase letters are equal.

Return the number of triplets (i,j,k) with i <= j < k for which adjacent substrings text[i..j] and text[j+1..k] form a magical pair.

Function

countMagicalTriplets(text: String) → long

Examples

Example 1

text = "aa"return = 1

The two one-letter substrings have the same set.

Example 2

text = "ababa"return = 4

Several adjacent pairs share {a,b}, with additional one-letter matches.

Example 3

text = "abc"return = 0

No adjacent pair has equal distinct-character sets.

Constraints

  • 0 <= text.length <= 5000.
  • The string contains lowercase English letters.
  • The answer fits in a signed 64-bit integer.

More Google problems

See Google hiring insights
public long countMagicalTriplets(String text) {
    // write your code here
}
text"aa"
expected1
Checking account…