Heads-up: They have an interesting definition of a subsequence. According to their definition "AC" is a subsequence of "ABC", which it wouldn't be according to my understanding. Maybe everyone else agrees with theirs, but I thought I'd highlight it.
–
Joachim SauerMar 1 '11 at 7:11

9

@Joachim why not ? "AC" is a subsequence and "AB" and "BC" are substrings maybe you confuse with the substring and subsequence
–
user467871Mar 1 '11 at 7:16

2

maybe I do and maybe their definition is the correct one anyway, I'm not arguing that. I just said that intuitively I'd have interpreted it differently and wanted to provide a heads-up if anyone had the same (possibly wrong) idea as I had.
–
Joachim SauerMar 1 '11 at 7:18

Initially, we assume we can append a[i] to all subsequences ending on previous characters, but this might violate the condition that the counted subsequences need to be distinct. Remember that last[a[i]] gives us the last position a[i] appeared on until now. The only subsequences we overcount are those that the previous a[i] was appended to, so we subtract those.

sum[i] = sum[i - 1] + dp[i]
last[a[i]] = i

Update these values as per their definition.

If your indexing starts from 0, use a[i - 1] wherever I used a[i]. Also remember to wrap your computations in a mod function if you're going to submit code. This should be implemented like this:

mod(x) = (x % m + m) % m

In order to correctly handle negative values in some languages (such as C/C++).

The idea is : If all character of the string are distinct, total number of subsequences is 2^n. Now, if we find any character that have already occurred before, we should consider it's last occurrence only(otherwise sequence won't be distinct). So we have to subtract the number of subsequences due to it's previous occurrence.