No, you can’t solve it using a sliding window. I mean you can, but you would require several nested for loops to keep track of decisions and that would mean a sub-optimal or non-optimial runtime.
The problem is asking us if every portion of the input string s
could be divided in such a way that every substring is found in the dictionary.
Logically speaking,
Intuition
So, since now we know it’s a decision tree problem where the results of the entire string contributes to the final answer, we are sure to use DFS with memo or dynamic programming.
Generally speaking tabular DP produces little code, although some may argue it’s more abstracted and difficult to get around at first.
Whenever working with DP ensure that you are first defining the state
and transition equation
.
state
=dp[i]
= Is the substrings[0:i+1]
a valid substring? Meaning, iss[0:i+1]
itself in the dictionary OR could it be broken down into smaller substrings WHICH are found in the dictionary?
transition
= To determine the value ofdp[i]
, we check ifs[i - len(w)]
was successfully segmented ORs[i - len(w) + 1: i] == w
.
Code
Python3
Big O Analysis
-
Runtime
The runtime complexity here is where N is length of
s
and M is length ofwordDict
. -
Memory
The memory usage is since we use an array to cache results.
— A