Guest User

115. Distinct Subsequences | silvermete0r's solution (hardcoded)

a guest
May 5th, 2026
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. # https://leetcode.com/problems/distinct-subsequences/description/
  2.  
  3. import math
  4. from bisect import bisect_right
  5. from collections import defaultdict
  6.  
  7. class Solution:
  8.     def numDistinct(self, s: str, t: str) -> int:
  9.         if len(s) < len(t): return 0
  10.         if len(s) == len(t): return int(s == t)
  11.         st, tt = set(s), set(t)
  12.         if st == tt and len(st) == 1:
  13.             sl, tl = len(s), len(t)
  14.             return int(math.comb(sl, tl))
  15.         inds = defaultdict(list)
  16.         n = len(s)
  17.         for i in range(n):
  18.             inds[s[i]].append(i)
  19.         t = t[::-1]
  20.         dp = [0] * n
  21.         for i in inds[t[0]]:
  22.             dp[i] = 1
  23.         for k in range(1, len(t)):
  24.             new_vals = []
  25.             for i in inds[t[k]]:
  26.                 v = 0
  27.                 pos = bisect_right(inds[t[k-1]], i)
  28.                 for j in inds[t[k-1]][pos:]:
  29.                     v += dp[j]
  30.                 if v > 0:
  31.                     new_vals.append((i, v))
  32.             new_inds = []
  33.             for ind, new_val in new_vals:
  34.                 dp[ind] = new_val
  35.                 new_inds.append(ind)
  36.             inds[t[k]] = new_inds
  37.         ans = 0
  38.         for ind in inds[t[-1]]:
  39.             ans += dp[ind]
  40.         return ans
Advertisement
Add Comment
Please, Sign In to add comment