Count Distinct Non-Empty Subsequences of a Search Query String
Last updated: November 29, 2026
Quick Overview
For autocomplete testing you need the number of distinct non-empty subsequences of a query string, counted as strings so duplicates are counted once. Return the count modulo 1,000,000,007.
0
0
0 solved
For autocomplete testing you need the number of distinct non-empty subsequences of a query string, counted as strings so duplicates are counted once. Return the count modulo 1,000,000,007.
A Google onsite hard where the doubling recurrence is easy but removing duplicates needs a precise argument about the last occurrence of each character. Interviewers check that you can explain exactly which subsequences get counted twice.
What the Interviewer Expects
- Start from the doubling recurrence for distinct-by-position subsequences
- Identify duplicates created by a repeated character
- Subtract the count from just before the previous occurrence
- Handle negative values under the modulus
- Exclude the empty subsequence at the end
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Count distinct subsequences of length exactly k.
- Count distinct palindromic subsequences.
- How many times does a pattern string appear as a subsequence?
- Return the k-th distinct subsequence in lexicographic order.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: string s of lowercase letters. Output the number of distinct non-empty strings that appear as a subsequence of s, mod . For 'aba' the answer is 6: a, b, ab, aa, ba, aba....
High-Level Design
Let dp[i] be the number of distinct subsequences of s[:i], including the empty one. Adding character c: every existing subsequence either skips c or appends it, doubling the count. But if c appear...