Need help determining time complexity of this algorithm for leetcode question word break ii

as the other commenter mentioned the memoization is broken. a better way to solve the problem would be to define memo[n] as the number of ways to split up a string which is a substring of the original string that starts at position n and goes up to the end of the original string.

if we use that definition, we get the following pseudocode:

String str; // word to break
Set <String> dict; // dictionary

int solve (int n) {// returns the number of ways to break the substring of ’str’ which starts at n and goes up to the end of 'str'
    if (memo [n] != -1) // if this result has been calculated already
        return memo [n];

    if (n == str.length ()) // if you’ve reached the end of the string, you can’t break it up in anymore ways
        return memo [n] = 1;

    memo [n] = 0; // since its set to -1 initially, to signify the state hasn’t been calculated yet, we need to change it to 0, to avoid screwing up any calculations
    // for each substring of the string starting at position n, if it is in the dictionary, 'remove' it from the string, and calculate how many ways you can break the word now that the substring has been removed
    for (int pos = n + 1; pos <= str.length (); pos++)
        if (dict.contains (str.substring (n, pos)))
            memo [n] += solve (pos);

    return memo [n];
}

now, there are N states, and each state takes O(N) time to calculate so the overall complexity is O(N2) (not counting the complexity of the substring method).

hopefully this helps, this ended up being a lot longer than i expected lol

/r/algorithms Thread