Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome.
Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome.
def lps(s):
n = len(s); dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
dp[i][j] = dp[i+1][j-1] + 2 if s[i] == s[j] else max(dp[i+1][j], dp[i][j-1])
return dp[0][n-1]
s = "character"
L = lps(s)
print(L, len(s) - L)What is printed?- A. 3 6
- B. 4 5
- C. 5 4
- D. 6 3
Correct answer: C. 5 4
The longest palindromic subsequence of 'character' is 5 (e.g. 'carac'). Every character outside it needs a mirrored partner, so the minimum insertions are n − LPS = 9 − 5 = 4.
More Coding Interview Problems questions
- Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute…
- Problem: With e identical eggs, find the minimum number of drops that always identifies the critical floor of an f-floor building. The…
- Problem: Count the ways to place n non-attacking queens on an n × n board. python def queens(n): cols, d1, d2 = set(), set(), set() def…
- Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings…
- Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space. python def…
- Building a binary heap from n given keys: what are the worst-case costs of (i) bottom-up heapify and (ii) n successive inserts into an…