Tutorialspoint
Problem
Solution
Submissions

Distinct Subsequences

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 12

Write a C++ program to count the number of distinct subsequences of a given string. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example 1
  • Input: s = "abc"
  • Output: 8
  • Explanation:
    • The distinct subsequences are "", "a", "b", "c", "ab", "ac", "bc", and "abc".
Example 2
  • Input: s = "aba"
  • Output: 7
  • Explanation:
    • The distinct subsequences are "", "a", "b", "aa", "ab", "ba", "aba".
    • Note that "a" appears twice as a subsequence but is counted only once.
Constraints
  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters
  • Time Complexity: O(n²)
  • Space Complexity: O(n²)
StringsDynamic Programming CapgeminiApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem
  • Consider using a map or array to keep track of last occurrence of characters
  • Calculate number of distinct subsequences ending at each position
  • Be careful about handling duplicates in the string
  • Consider empty string as a valid subsequence

Steps to solve by this approach:

 Step 1: Initialize a dp array where dp[i] represents the number of distinct subsequences ending at position i.
 Step 2: Initialize dp[0] = 1 to account for the empty subsequence.
 Step 3: For each character, the number of subsequences doubles (we can either include or exclude it).
 Step 4: Track the last occurrence of each character to handle duplicates.
 Step 5: For duplicates, subtract the count of subsequences that would be counted twice.
 Step 6: Update the last occurrence map for each character.
 Step 7: Return dp[n] - 1 to exclude the empty subsequence if not counting it.

Submitted Code :