Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the minimum number of characters to insert to make a string a palindrome.
Problem: Return the minimum number of characters to insert to make a string a palindrome.
def min_insert(s):
t = s[::-1]; n = len(s)
dp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(n):
dp[i+1][j+1] = dp[i][j] + 1 if s[i] == t[j] else max(dp[i][j+1], dp[i+1][j])
return n - dp[n][n]
print(min_insert("mbadm"), min_insert("leetcode"), min_insert("zzazz"))What is printed?- A. 2 6 0
- B. 3 5 0
- C. 2 5 0
- D. 2 5 1
Correct answer: C. 2 5 0
Insertions needed = n − (longest palindromic subsequence) = n − LCS(s, reverse(s)). "mbadm": LPS "mbm"/"mam" = 3 → 2. "leetcode": LPS "eee" = 3 → 5. Already a palindrome → 0. O(n²).
More Coding Interview Problems questions
- 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…
- Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting…