Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)?
Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)?
def inter(s1, s2, s3):
if len(s1) + len(s2) != len(s3): return False
dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
dp[0][0] = True
for i in range(len(s1) + 1):
for j in range(len(s2) + 1):
if i and s1[i-1] == s3[i+j-1] and dp[i-1][j]: dp[i][j] = True
if j and s2[j-1] == s3[i+j-1] and dp[i][j-1]: dp[i][j] = True
return dp[-1][-1]
print(inter("aab", "axy", "aaxaby"), inter("aab", "axy", "abaaxy"))What is printed?- A. True True
- B. False True
- C. False False
- D. True False
Correct answer: D. True False
'aaxaby' = a(s1) a(s2) x(s2) a(s1) b(s1) y(s2). 'abaaxy' fails: its 'b' comes second, but s1's b needs both of s1's a's first and s2 has no b. The DP tries every split, so a greedy choice of which string's 'a' to use cannot mislead it.
More Coding Interview Problems questions
- Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every…
- Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1…
- Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running…
- Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.) python def can(a, k): s = sum(a) if s %…
- Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c. python def flips(a, b, c): res = 0 while a or b or…
- Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick. python m = 0b101101 s, cnt = m, 0 while s: cnt += 1 s…