Skip to main content
LeetCode 940, Hard. Topics: String, Dynamic Programming. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 21 parametrized pytest cases, and a playground notebook:

Problem

Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of “abcde” while "aec" is not.

Examples

Constraints

  • 1 <= s.length <= 2000
  • s consists of lowercase English letters.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026