Skip to main content

83. Word Break

mediumAsked at Ola

Decide if a string can be segmented into dictionary words.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • Words consist of lowercase English letters

Examples

Example 1

Input
s = "leetcode", wordDict = ["leet","code"]
Output
true

Example 2

Input
s = "applepenapple", wordDict = ["apple","pen"]
Output
true

Approaches

1. Recursive split

Try every prefix in the dictionary and recurse on the suffix.

Time
O(2^n)
Space
O(n)
// raw recursion without memo; exponential

Tradeoff:

2. DP over prefix lengths

dp[i] is true if s[0..i] can be split; for each i, check dp[j] && s[j..i] in dict.

Time
O(n^2)
Space
O(n)
function wordBreak(s, wordDict) {
  const set = new Set(wordDict);
  const dp = Array(s.length + 1).fill(false);
  dp[0] = true;
  for (let i = 1; i <= s.length; i++) {
    for (let j = 0; j < i; j++) {
      if (dp[j] && set.has(s.slice(j, i))) { dp[i] = true; break; }
    }
  }
  return dp[s.length];
}

Tradeoff:

Ola-specific tips

Ola interviewers ask classic DP scaffolding; tie it to tokenizing concatenated zone codes back into known dispatch keywords.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Word Break and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →