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?
  1. A. True True
  2. B. False False
  3. C. False True
  4. 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

Exams that ask this topic