Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Dynamic Programming
HardLC 940

Distinct Subsequences II (LeetCode 940)

Target Frequency:GoogleAmazonByteDance

You get a string s of lowercase English letters. Deleting any number of its letters, possibly none, and keeping the rest in their original order gives a subsequence of s.

Count the different non-empty strings you can get this way. A string that several different choices of positions produce is counted once, not once per choice. The count can be very large, so return it modulo 109 + 7.

Worked Examples

Example 1
Input:s = "abc"
Output:7
Explanation: Every choice of letters gives a different string: "a", "b", "c", "ab", "ac", "bc" and "abc".
Example 2
Input:s = "aba"
Output:6
Explanation: The strings are "a", "b", "aa", "ab", "ba" and "aba". Picking only the first letter or only the last letter both give "a", which counts once.
Example 3
Input:s = "aaa"
Output:3
Explanation: The strings are "a", "aa" and "aaa"; every other choice of positions repeats one of them.

⚖️Formal Constraints & Bounds

  • 1 <= s.length <= 2000

  • s consists of lowercase English letters.

Deep-Dive & Conceptual Insights

Core Insight

Keep one running count per last letter, ends[c]. A new letter ch can finish every subsequence counted so far and can also stand alone, so ends[ch] becomes sum(ends) + 1 -- replacing, not adding to, the old ends[ch], because that old count is already included inside sum(ends).

Real-World Scenario & Production Applications

Counting how many distinct messages a noisy channel could have reduced to the received string, how many distinct search queries a typed prefix could abbreviate, or how many distinct DNA fragments a read could contain all reduce to counting distinct subsequences, where equal strings reached by different deletions must be counted once.

Step-by-Step Execution Trace Table

Example 1, s = "abc". Only the one letter ends[ch] touches on each row changes; every other entry of ends carries over unchanged:

Stepchsum(ends) beforeends[ch] = sum(ends) + 1ends after (nonzero entries)
Startends = [0] * 26
1a0ends['a'] = 0 + 1 = 1a: 1
2b1ends['b'] = 1 + 1 = 2a: 1, b: 2
3c3ends['c'] = 3 + 1 = 4a: 1, b: 2, c: 4
Endreturn sum(ends)7
Code Shape
Archetype Code Shape
Python
1Give every possible last letter its own running count: `ends[c]` is how many distinct non-empty subsequences built from the characters read so far end in `c`.
2A new character `ch` can finish `ch` alone, or finish any subsequence already counted by appending `ch` to it, so `ends[ch]` becomes `sum(ends) + 1`, and this replaces the old `ends[ch]` rather than adding to it.
3The shape: one array of 26 counts, one loop over the characters of `s`, one replace per character, and the sum of the 26 counts at the end.
4The trap: `ends[ch] += sum(ends) + 1` instead of `=`. The old `ends[ch]` already counted exactly the subsequences this same step rebuilds, so adding counts every one of them twice.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Counting every distinct subsequence of a string by listing them is exponential: a string of n letters has up to 2^n - 1 non-empty subsequences. Last-Character Counting DP reads s once instead, and keeps one running count per possible last letter: ends[c], how many distinct non-empty subsequences built from the letters read so far end in c. A new letter ch can finish every one of those counted subsequences by appending ch to it, and it can also stand alone as the one-letter subsequence "ch" -- both of those are new subsequences ending in ch, so ends[ch] becomes sum(ends) + 1.

🧺 The Analogy: One Basket per Last Ingredient, Refilled Each Time

Picture building every distinct trail mix you can make by adding ingredients one at a time, where two mixes are the same trail mix exactly when they contain the same ingredients in the same order. Keep one basket per ingredient, holding every distinct mix made so far that ends with that ingredient. When a new ingredient ch arrives, every mix in every basket can have ch added to its end to form a new, distinct mix -- plus ch on its own is a new one-ingredient mix -- so you empty the basket for ch and refill it with all of those at once. You never add to what was already in that basket, because every mix already in it is one of the mixes this same step just rebuilt by appending ch to a shorter mix.

🔑 Why It Works

The replace is what keeps every subsequence counted exactly once. The old ends[ch] already counted exactly the subsequences this same construction rebuilds: every subsequence that already ended in ch is reproduced, letter for letter, by appending ch to the subsequence left after removing that last ch -- so it is one of the sum(ends) subsequences ends[ch] = sum(ends) + 1 just built. Adding the new total on top of the old ends[ch], instead of replacing it, would count every one of those subsequences a second time.

  • Adding instead of replacing ends[ch]: ends[ch] += sum(ends) + 1 double-counts every subsequence that already ended in ch, since that old count is already one of the sum(ends) terms this step rebuilds. s = "aaa" must return 3 ("a", "aa", "aaa"), not more.

  • Forgetting the + 1 for the one-letter subsequence: ends[c] = sum(ends) never counts "c" alone. s = "abc" must return 7, not 0.

  • Forgetting the final % MOD on the return line: each ends[c] is already reduced modulo 109 + 7 on every write, but summing 26 already-reduced values can still add up past the modulus; return sum(ends) alone can return a number at or above 109 + 7, not the required remainder.

  • Treating it like Distinct Subsequences (LC 115): LC 115 counts the ways one target string t can be picked out of a second string s; here there is no second string, so the count is of every distinct subsequence of s itself, keyed by last letter instead of by position in t.

  • Treating a repeated '0' like '1' on LC 1987's transfer problem: ends0 = ends0 + ends1 + 1 rebuilds the lone "0" subsequence once per '0' seen instead of once for the whole string; binary = "000" must return 1, not 3.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Count the different non-empty strings you can get" with no second string to match: the count is of every distinct subsequence of s itself. That is the signal for Last-Character Counting DP: one running count per possible last letter.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After each letter ch of s is read, ends[c] is the number of distinct non-empty subsequences built so far that end in c, and every subsequence that already ended in c is already included inside that same count, so the next letter rebuilds it rather than adding to it.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • ends[c] = sum(ends) without the + 1: the one-letter subsequence "c" itself is never counted the first time c appears (s = "abc" returns 0 instead of 7).

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Last-Character Counting DP. I keep one running count per letter of the alphabet: ends of c is how many distinct non-empty subsequences I've built so far that end in c. For each new letter ch, every subsequence I've counted can have ch appended to it, and ch alone is also a new one-letter subsequence, so ends of ch becomes the sum of every count plus one. That replaces the old ends of ch, it doesn't add to it, because the old value is already inside that sum, and adding again would double-count every subsequence that already ended in ch. The answer is the sum of all 26 counts at the end. One pass over s, 26 counts to update each time, so O(N) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: for ch in s runs N times, and its body computes sum(ends) over the 26 entries and writes one of them, both O(1) because 26 is a fixed constant, not N. Total: O(26 * N) = O(N).

SPACE COMPLEXITY

O(1)

The code keeps one list, ends, of 26 counts, whatever the length of s: O(26) = O(1) extra space. The answer is one integer.

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "count the different non-empty strings you can get this way", "a string that several choices of positions produce is counted once". A count of every distinct subsequence of one string, with no second string to match against: Last-Character Counting DP, one running count per last letter.

CONSTRAINTS & BOUNDS

N≤2000N \le 2000N≤2000 letters, so 26⋅N≤52,00026 \cdot N \le 52{,}00026⋅N≤52,000 cheap steps. Listing every one of up to 2N−12^N - 12N−1 subsequences is exponential; the running counts are O(26⋅N)=O(N)O(26 \cdot N) = O(N)O(26⋅N)=O(N) time and O(26)=O(1)O(26) = O(1)O(26)=O(1) space. The answer is returned modulo 109+710^9 + 7109+7.

FAANG PRODUCTION TRAPS & EDGE CASES

In Java, C++, Go or Rust, sum(ends) + 1 must be reduced modulo 109+710^9 + 7109+7 on every write to ends[c], not only at the end: a fixed-width int silently overflows, including into a negative number, once the unreduced total passes the type's range. Python's integers never overflow, so the same mistake there only costs time on long strings.

Theory Context•Dynamic Programming
HardLC 940

Distinct Subsequences II (LeetCode 940)

Target Frequency:GoogleAmazonByteDance

You get a string s of lowercase English letters. Deleting any number of its letters, possibly none, and keeping the rest in their original order gives a subsequence of s.

Count the different non-empty strings you can get this way. A string that several different choices of positions produce is counted once, not once per choice. The count can be very large, so return it modulo 109 + 7.

Worked Examples

Example 1
Input:s = "abc"
Output:7
Explanation: Every choice of letters gives a different string: "a", "b", "c", "ab", "ac", "bc" and "abc".
Example 2
Input:s = "aba"
Output:6
Explanation: The strings are "a", "b", "aa", "ab", "ba" and "aba". Picking only the first letter or only the last letter both give "a", which counts once.
Example 3
Input:s = "aaa"
Output:3
Explanation: The strings are "a", "aa" and "aaa"; every other choice of positions repeats one of them.

⚖️Formal Constraints & Bounds

  • 1 <= s.length <= 2000

  • s consists of lowercase English letters.

Deep-Dive & Conceptual Insights

Core Insight

Keep one running count per last letter, ends[c]. A new letter ch can finish every subsequence counted so far and can also stand alone, so ends[ch] becomes sum(ends) + 1 -- replacing, not adding to, the old ends[ch], because that old count is already included inside sum(ends).

Real-World Scenario & Production Applications

Counting how many distinct messages a noisy channel could have reduced to the received string, how many distinct search queries a typed prefix could abbreviate, or how many distinct DNA fragments a read could contain all reduce to counting distinct subsequences, where equal strings reached by different deletions must be counted once.

Step-by-Step Execution Trace Table

Example 1, s = "abc". Only the one letter ends[ch] touches on each row changes; every other entry of ends carries over unchanged:

Stepchsum(ends) beforeends[ch] = sum(ends) + 1ends after (nonzero entries)
Startends = [0] * 26
1a0ends['a'] = 0 + 1 = 1a: 1
2b1ends['b'] = 1 + 1 = 2a: 1, b: 2
3c3ends['c'] = 3 + 1 = 4a: 1, b: 2, c: 4
Endreturn sum(ends)7
Code Shape
Archetype Code Shape
Python
1Give every possible last letter its own running count: `ends[c]` is how many distinct non-empty subsequences built from the characters read so far end in `c`.
2A new character `ch` can finish `ch` alone, or finish any subsequence already counted by appending `ch` to it, so `ends[ch]` becomes `sum(ends) + 1`, and this replaces the old `ends[ch]` rather than adding to it.
3The shape: one array of 26 counts, one loop over the characters of `s`, one replace per character, and the sum of the 26 counts at the end.
4The trap: `ends[ch] += sum(ends) + 1` instead of `=`. The old `ends[ch]` already counted exactly the subsequences this same step rebuilds, so adding counts every one of them twice.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Counting every distinct subsequence of a string by listing them is exponential: a string of n letters has up to 2^n - 1 non-empty subsequences. Last-Character Counting DP reads s once instead, and keeps one running count per possible last letter: ends[c], how many distinct non-empty subsequences built from the letters read so far end in c. A new letter ch can finish every one of those counted subsequences by appending ch to it, and it can also stand alone as the one-letter subsequence "ch" -- both of those are new subsequences ending in ch, so ends[ch] becomes sum(ends) + 1.

🧺 The Analogy: One Basket per Last Ingredient, Refilled Each Time

Picture building every distinct trail mix you can make by adding ingredients one at a time, where two mixes are the same trail mix exactly when they contain the same ingredients in the same order. Keep one basket per ingredient, holding every distinct mix made so far that ends with that ingredient. When a new ingredient ch arrives, every mix in every basket can have ch added to its end to form a new, distinct mix -- plus ch on its own is a new one-ingredient mix -- so you empty the basket for ch and refill it with all of those at once. You never add to what was already in that basket, because every mix already in it is one of the mixes this same step just rebuilt by appending ch to a shorter mix.

🔑 Why It Works

The replace is what keeps every subsequence counted exactly once. The old ends[ch] already counted exactly the subsequences this same construction rebuilds: every subsequence that already ended in ch is reproduced, letter for letter, by appending ch to the subsequence left after removing that last ch -- so it is one of the sum(ends) subsequences ends[ch] = sum(ends) + 1 just built. Adding the new total on top of the old ends[ch], instead of replacing it, would count every one of those subsequences a second time.

  • Adding instead of replacing ends[ch]: ends[ch] += sum(ends) + 1 double-counts every subsequence that already ended in ch, since that old count is already one of the sum(ends) terms this step rebuilds. s = "aaa" must return 3 ("a", "aa", "aaa"), not more.

  • Forgetting the + 1 for the one-letter subsequence: ends[c] = sum(ends) never counts "c" alone. s = "abc" must return 7, not 0.

  • Forgetting the final % MOD on the return line: each ends[c] is already reduced modulo 109 + 7 on every write, but summing 26 already-reduced values can still add up past the modulus; return sum(ends) alone can return a number at or above 109 + 7, not the required remainder.

  • Treating it like Distinct Subsequences (LC 115): LC 115 counts the ways one target string t can be picked out of a second string s; here there is no second string, so the count is of every distinct subsequence of s itself, keyed by last letter instead of by position in t.

  • Treating a repeated '0' like '1' on LC 1987's transfer problem: ends0 = ends0 + ends1 + 1 rebuilds the lone "0" subsequence once per '0' seen instead of once for the whole string; binary = "000" must return 1, not 3.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Count the different non-empty strings you can get" with no second string to match: the count is of every distinct subsequence of s itself. That is the signal for Last-Character Counting DP: one running count per possible last letter.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After each letter ch of s is read, ends[c] is the number of distinct non-empty subsequences built so far that end in c, and every subsequence that already ended in c is already included inside that same count, so the next letter rebuilds it rather than adding to it.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • ends[c] = sum(ends) without the + 1: the one-letter subsequence "c" itself is never counted the first time c appears (s = "abc" returns 0 instead of 7).

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use Last-Character Counting DP. I keep one running count per letter of the alphabet: ends of c is how many distinct non-empty subsequences I've built so far that end in c. For each new letter ch, every subsequence I've counted can have ch appended to it, and ch alone is also a new one-letter subsequence, so ends of ch becomes the sum of every count plus one. That replaces the old ends of ch, it doesn't add to it, because the old value is already inside that sum, and adding again would double-count every subsequence that already ended in ch. The answer is the sum of all 26 counts at the end. One pass over s, 26 counts to update each time, so O(N) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: for ch in s runs N times, and its body computes sum(ends) over the 26 entries and writes one of them, both O(1) because 26 is a fixed constant, not N. Total: O(26 * N) = O(N).

SPACE COMPLEXITY

O(1)

The code keeps one list, ends, of 26 counts, whatever the length of s: O(26) = O(1) extra space. The answer is one integer.

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "count the different non-empty strings you can get this way", "a string that several choices of positions produce is counted once". A count of every distinct subsequence of one string, with no second string to match against: Last-Character Counting DP, one running count per last letter.

CONSTRAINTS & BOUNDS

N≤2000N \le 2000N≤2000 letters, so 26⋅N≤52,00026 \cdot N \le 52{,}00026⋅N≤52,000 cheap steps. Listing every one of up to 2N−12^N - 12N−1 subsequences is exponential; the running counts are O(26⋅N)=O(N)O(26 \cdot N) = O(N)O(26⋅N)=O(N) time and O(26)=O(1)O(26) = O(1)O(26)=O(1) space. The answer is returned modulo 109+710^9 + 7109+7.

FAANG PRODUCTION TRAPS & EDGE CASES

In Java, C++, Go or Rust, sum(ends) + 1 must be reduced modulo 109+710^9 + 7109+7 on every write to ends[c], not only at the end: a fixed-width int silently overflows, including into a negative number, once the unreduced total passes the type's range. Python's integers never overflow, so the same mistake there only costs time on long strings.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•