Skip to content

1987. Number of Unique Good Subsequences 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  // Similar to 940. Distinct Subsequences II
  int numberOfUniqueGoodSubsequences(string binary) {
    constexpr int kMod = 1'000'000'007;
    // endsWith[i] := # of subseqs ends with '0' + i
    vector<int> endsWith(2);

    for (const char c : binary) {
      endsWith[c - '0'] = (endsWith[0] + endsWith[1]) % kMod;
      // Don't cound '0' since we want to avoid the leading zeros case.
      // However, we can always count '1'.
      if (c == '1')
        ++endsWith[1];
    }

    // Count '0' in the end.
    return (endsWith[0] + endsWith[1] +
            (binary.find('0') == string::npos ? 0 : 1)) %
           kMod;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  // Similar to 940. Distinct Subsequences II
  public int numberOfUniqueGoodSubsequences(String binary) {
    final int kMod = 1_000_000_007;
    // endsWith[i] := # of subseqs ends with '0' + i
    int[] endsWith = new int[2];

    for (final char c : binary.toCharArray()) {
      endsWith[c - '0'] = (endsWith[0] + endsWith[1]) % kMod;
      // Don't cound '0' since we want to avoid the leading zeros case.
      // However, we can always count '1'.
      if (c == '1')
        ++endsWith[1];
    }

    // Count '0' in the end.
    return (endsWith[0] + endsWith[1] + (binary.indexOf('0') == -1 ? 0 : 1)) % kMod;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  # Similar to 940. Distinct Subsequences II
  def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
    kMod = 1_000_000_007
    # endsWith[i] := # of subseqs ends with '0' + i
    endsWith = {'0': 0, '1': 0}

    for c in binary:
      endsWith[c] = sum(endsWith.values()) % kMod
      # Don't cound '0' since we want to avoid the leading zeros case.
      # However, we can always count '1'.
      if c == '1':
        endsWith['1'] += 1

    # Count '0' in the end.
    return (sum(endsWith.values()) + ('0' in binary)) % kMod