Can Construct with Tabulation

Updated: 01 February 2024

Problem

The same problem as the Can Construct Memoization Problem but implemented using the tabular style in the previous problems

In this case, we will store an index for each letter and the value of whether or not it is possible to start a substring from that position - if it is possible then we will go to the end of ths substring and mark that position as false

Tabulation Implementation

The implementation of this can be seen below:

dynamic-programming/tabulation/can-construct.ts
export const canConstruct = (target: string, subs: string[]): boolean => {
  const table = new Array<boolean>(target.length + 1).fill(false);
  table[0] = true;

  for (let index = 0; index <= target.length; index++) {
    if (table[index]) {
      for (const sub of subs) {
        const fromIndex = target.slice(index);
        if (fromIndex.startsWith(sub)) {
          const nextIndex = index + sub.length;
          table[nextIndex] = true;
        }
      }
    }
  }

  return table[target.length];
};

In the above, the time complexity $O(m^2 *n)$ and space complexity $O(m^2)$

The reason we say $m^2$ and not $m$ in the time complexity is because of the array copy operation that we do to assign the latest value