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?- A. 5 5 0
- B. 3 6 0
- C. 3 5 1
- 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
- Problem: Return the minimum number of characters to insert to make a string a palindrome. python def mininsert(s): t = s[::-1]; n = len(s)…
- Problem: Count the number of islands after each 'add land' operation on an initially all-water grid. python def islandsonline(R, C, ops)…
- Problem: Return the length of the shortest path that visits every node of a small undirected graph (start and end anywhere, edges…
- Problem: Count the number of ways to assign n distinct tasks to n workers where task i cannot go to worker i (derangements), modulo 10⁹ +…
- Problem: Reconstruct a queue of people (h, k) where k = number of people in front with height ≥ h. python def rebuild(people)…
- Problem: Find the minimum number of refuelling stops to travel a distance, given stations (position, fuel) and start fuel. python import…