Word break using memoization – Code

Word break is to divide a string into sub-strings that defined in dictionary. The problem is usually solved with recursion. The time complexity is exponential. Here we introduce word break using memoization, which helps to improve complexity.

Memoization is one of Dynamic programming(DP) techniques. DP is able to solve a complex problem by breaking it down into sub-problems. Each following steps can re-use the result from the previous steps, and avoid redundant calculations or operations. This improves the time complexity significantly, from exponential to O(n^3) or O(n^2).


word break

The approach of using memoization is:

  1. Solve the problem with recursion.

    This consists of a wrapper method and a helper method. The wrapper method define the initial input and output, then call helper. The helper method is a recursion function which solves sub-problem.

  2. Add memoization variable.

    Declare a variable (called memo) in wrapper method. The data structure is often list or set. Add this variable as one input parameter of helper method. At the beginning, check whether the input is stored in memo. if it is, return memo value directly. Within the body of helper method, Update the memo value before call itself.

Amazon Interview Question (CareerCup):
How would you like to efficiently find the total number of possible ways with which given string may be converted to whole dictionary words.
Example :
String = “Dogeatscare”
possible combinations – “Dog, eat, scare ” and “Dog, eats, care”
output is 2.

Java

JavaScript

Python

Doodle

shortest path bfs doodle

Output:
Input: dogeatscare
[dog eats care, dog eat scare]
Word break count: 2

Input: catsanddogs
[cat sand dogs, cats and dogs]
Word break count: 2

O Notation:

Recursion with memoization:
Time complexity: O(s^3)
Space complexity: O(s^2)

Note:
If you have any questions or want to put comments, please post at youtube. I will answer you!
The code displayed here is the improved version after the enhancement in the 2nd edition of Java coding interview pocket book.


Download WordBreak.java
Word break using memoization (YouTube)
Java coding interview pocket book insight

Comments are closed