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;
    // endsIn[i] := the number of subsequence that end in ('0' + i)
    vector<int> endsIn(2);

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

    // Count '0' in the end.
    return (endsIn[0] + endsIn[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;
    // endsIn[i] := the number of subsequence that end in ('0' + i)
    int[] endsIn = new int[2];

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

    // Count '0' in the end.
    return (endsIn[0] + endsIn[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
    # endsIn[i] := the number of subsequence that end in ('0' + i)
    endsIn = {'0': 0, '1': 0}

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

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