# 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). 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.

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.

## 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: