Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the longest substring in which every character appears at least k times (divide and conquer on characters that are too rare).

Problem: Find the longest substring in which every character appears at least k times (divide and conquer on characters that are too rare).
def longest_k(s, k):
    if len(s) < k: return 0
    for ch in set(s):
        if s.count(ch) < k:
            return max(longest_k(part, k) for part in s.split(ch))
    return len(s)
print(longest_k("aaabb", 3), longest_k("ababbc", 2), longest_k("abcde", 2))
What is printed?
  1. A. 5 5 0
  2. B. 3 6 0
  3. C. 3 5 1
  4. D. 3 5 0

Correct answer: D. 3 5 0

Any character that occurs fewer than k times can never be in a valid substring, so split around it and recurse. "aaabb": b occurs twice < 3 → "aaa". "ababbc": split on c → "ababb" (a ×2, b ×3) = 5. O(26 · n) levels of splitting at most, O(26·n) per level.

More Coding Interview Problems questions

Exams that ask this topic