Distinct Subsequences
Problem Statement
You are given two strings s and t. Count the ways to get t by deleting some letters from s. Two ways are different when they keep a different set of positions in s, even if they spell the same text. Return the count. The test cases make sure the answer fits in a 32-bit signed integer.
Two strings, s and t. The letters are English letters, upper or lower case.
The number of ways t can be made by deleting letters from s.
s has three b's, and rabbit needs two of them. Choosing which two b's gives 3 ways.
Five different sets of positions in s spell bag.
- • 1 ≤ s.length, t.length ≤ 1000
- • The answer fits in a 32-bit signed integer.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Recurse on (i, j): skip s's last letter, or if it matches, use it for t's last letter
dp[i][j] for every pair of prefixes; each cell is filled once from two cells above
One array row[j]; for each letter of s, update j from high to low
Let ways(i, j) be the number of ways the first j letters of t appear among the first i letters of s. If j = 0, there is exactly one way: use nothing. If i = 0 and j > 0, there are none. Otherwise skip s[i−1], which gives ways(i−1, j). If s[i−1] = t[j−1], also use it, which gives ways(i−1, j−1). Add the two cases.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Strings translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.