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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

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
1D dynamic programming
Distinct subsequences
Last occurrence
Inclusion exclusion
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements

Input: string s of lowercase letters. Output the number of distinct non-empty strings that appear as a subsequence of s, mod 109+710^9+7. 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...


Submit Your Answer
Markdown supported