ExamAdda Logo

Word Break

Easy

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.

A dictionary word may be used multiple times.

The words must form the entire string without changing their order or characters.

Example 1

Input

n = 2
wordDict = ["leet", "code"]
s = "leetcode"

Output

true

Explanation

The string can be segmented as:

"leet" + "code"

 

Both words are present in wordDict.

Example 2

Input

n = 5
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
s = "pineapplepenapple"

Output

true

Explanation

One valid segmentation is:

"pine" + "apple" + "pen" + "apple"

 

All four words are present in the dictionary.

Constraints

1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] consist of lowercase English letters.
All strings in wordDict are unique.

Hints:

Hint 1

Let dp[i] represent whether the first i characters of s can be segmented using the dictionary.

Hint 2

For every position i, check whether there is a previous position j such that:

dp[j] = true

 

and:

s[j...i-1]

 

is a dictionary word.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 23, 2026

Last updated

Aug 23, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output