Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Decide whether a string can be split into words from a dictionary.
Problem: Decide whether a string can be split into words from a dictionary.
def wb(s, words):
W = set(words); dp = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
dp[i] = any(dp[j] and s[j:i] in W for j in range(i))
return dp[-1]
print(wb("applepenapple", ["apple", "pen"]), wb("catsandog", ["cats", "dog", "sand", "and", "cat"]))What is printed?- A. True True
- B. False False
- C. False True
- D. True False
Correct answer: D. True False
dp[i] is True if some earlier cut j is reachable and s[j:i] is a word. "catsandog" can reach index 7 (cats|and or cat|sand) but "og" is not a word. Greedy longest-match parsing fails on such inputs. O(n² · L) with slicing.
More Coding Interview Problems questions
- Problem: Return the maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best =…
- Problem: Can an array be split into two subsets with equal sums? python def cansplit(a): s = sum(a) if s % 2: return False reach = 1 for x…
- Problem: Return the length of the longest palindromic subsequence (not substring). python def lps(s): n = len(s); dp = [[0] n for in…
- Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications…
- Problem: A DP solution for 'minimum coins for amount A using c denominations' with A ≤ 10⁴ and c ≤ 100 is accepted. A friend proposes…
- Problem: Find the largest square of 1s in a binary matrix and return its area. python def square(m): R, C = len(m), len(m[0]); dp = [[0]…