Data Structures & AlgorithmsHard

For counting subsequences equal to a fixed pattern (like 'abc'), why must the DP update the longer prefixes first?

  1. A. Updating in any order gives the same result, so it does not matter.
  2. B. Updating longer prefixes first prevents one character from extending a prefix that it already created in the same step.
  3. C. The DP needs the pattern to be sorted.
  4. D. Longer prefixes must be cleared before the scan starts.

Correct answer: B. Updating longer prefixes first prevents one character from extending a prefix that it already created in the same step.

When a character matches pattern position k, the count for prefix k must use the old count for prefix k−1, so the update runs from the end of the pattern backwards. Otherwise one character would be used twice.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic