AlgoMaster Logo

Word Break

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursion

Intuition:

In this approach, we will use recursion to break down the problem. The idea is to check if the current prefix of the string can be found in the word dictionary, and if it is, we recursively check the remaining substring. If any path returns true, we know the string can be segmented according to the dictionary.

This method may have overlapping subproblems, which makes it inefficient for larger inputs.

Code:

2. Recursion with Memoization

Intuition:

To optimize the previous recursive solution, we store the result of already processed substrings in a memoization table to avoid recomputation. This approach utilizes dynamic programming concepts to store results of subproblems, thus reducing redundant calculations.

Code:

3. Dynamic Programming

Intuition:

We can further improve the solution by using dynamic programming. The idea is to use a boolean dp array where dp[i] represents whether the substring s[0...i] can be segmented using the dictionary. For each position, we check all possible partitions, updating the dp array based on previously computed results.

Code: