Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Dynamic Programming

Word Break

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

You are provided with a string s and a set of words called wordDict. Write a function to determine whether s can be broken down into a sequence of one or more words from wordDict, where each word can appear more than once and there are no spaces in s. If s can be segmented in such a way, return true; otherwise, return false.

Input:

s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]

Output:

false

Explanation: There is no valid segmentation of "catsandog" into dictionary words from wordDict.

Input:

s = "hellointerview", wordDict = ["hello","interview"]

Output:

true

Explanation: Return true because "hellointerview" can be segmented as "hello" and "interview".
Note that you are allowed to reuse a dictionary word.

Explanation

This solution uses bottom-up dynamic programming to solve the problem.
We create a boolean array dp of size n + 1 where n is the length of the input string. dp[i] is true if the first i characters of s can be segmented into a valid sequence of dictionary words. dp[0] is True because the empty string is a valid sequence - all other values are false to start.
Visualization
Python
Language
def wordBreak(s, wordDict):
wordSet = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True # Empty string is a valid break
for i in range(1, len(s) + 1):
for j in range(i):
sub = s[j:i]
if dp[j] and sub in wordSet:
dp[i] = True
break
return dp[len(s)]
catsandogcatsandogdp0123456789

word break

0 / 1

We then use a for-loop i which goes from 1 to n to iterate through the string. Inside the body of this loop, we determine the correct value for dp[i]. We do this by using another for-loop j, which goes from 0 to i and represents the start of the substring we are considering. If dp[j] is true and the substring from j to i (sub) is in the dictionary, then we have found a valid segmentation, and can therefore set dp[i] to True.
Visualization
Python
Language
def wordBreak(s, wordDict):
wordSet = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True # Empty string is a valid break
for i in range(1, len(s) + 1):
for j in range(i):
sub = s[j:i]
if dp[j] and sub in wordSet:
dp[i] = True
break
return dp[len(s)]
i = 1catsandogcatsandogTFFFFFFFFFdp0123456789

i = 1

0 / 11

Iterating until we set `dp[i] = True` for the first time.
As soon as we find a valid segmentation, we can break out of the inner for-loop and move on to the next character in the string.
Finally, after we finished iterating, we return dp[n] which is the value of the last element in the array. This value will be True if the entire string can be segmented into valid dictionary words, and False otherwise.
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n²) where n is the length of the input string s. We use nested loops to check all possible substrings.

Space Complexity: O(n + m) where n is the length of the input string s and m is the length of wordDict. This includes the dp array and the additional space used to create wordSet from wordDict.

Solution

Visualization
Python
Language
Try these examples:
def wordBreak(s, wordDict):
wordSet = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True # Empty string is a valid break
for i in range(1, len(s) + 1):
for j in range(i):
sub = s[j:i]
if dp[j] and sub in wordSet:
dp[i] = True
break
return dp[len(s)]
catsandogcatsandogdp0123456789

word break

0 / 88

Alternative Solution

An alternative solution follows the same bottom-up approach. We use the same for loop to iterate through the string, but instead of iterating over all substrings ending at i, we instead iterate over all words in the dictionary. If the current word matches the substring ending at i and if dp[i - word.length] is True, then we have found a valid segmentation and can set dp[i] to True.
Visualization
Python
Language
Try these examples:
def wordBreak(s, wordDict):
dp = [False] * (len(s) + 1)
dp[0] = True # Empty string is a valid break
for i in range(1, len(s) + 1):
for word in wordDict:
if i >= len(word) and dp[i - len(word)]:
sub = s[i - len(word):i]
if sub == word:
dp[i] = True
break
return dp[len(s)]
catsandog

word break

0 / 65

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n * m) where n is the length of the input string s and m is the length of wordDict. We iterate through the string and check against each word in the dictionary.

Space Complexity: O(n) where n is the length of the input string s for the dp array.

Mark as read

Next: Maximum Profit in Job Scheduling

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Solution

Alternative Solution

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress