S⃗

DP on Strings / Subsequences

LCS, edit distance, palindrome DP, and substring matching using 2D tables.

1 Problems3-4 hours1 Hard

Overview

String DP problems typically build a 2D table dp[i][j] representing the answer for the first i characters of s1 and the first j characters of s2.

Complexity Summary

Time Complexity

O(m × n)

Space Complexity

O(m × n) reducible to O(n)

Key Patterns & Techniques

Learn the core patterns in this topic. Each block explains when to use the pattern, the intuition behind it, and a compact code example.

1

LCS

Concept

dp[i][j] = dp[i-1][j-1]+1 if match, else max(dp[i-1][j], dp[i][j-1])

Practice questions for this pattern
2

Edit distance

Concept

dp[i][j] = 1 + min(insert, delete, replace)

Practice questions for this pattern
3

Longest palindromic subsequence

Concept

LCS of s and reverse(s)

Practice questions for this pattern
4

Palindrome partitioning

Concept

dp[i][j] = is substring i..j a palindrome

Practice questions for this pattern
5

Distinct subsequences

Concept

dp[i][j] counts ways to form t in s

Practice questions for this pattern
6

Interleaving strings

Concept

dp[i][j] = can s1[:i] and s2[:j] interleave to form s3

Practice questions for this pattern
DSA Practice Online - 150+ Coding Interview Questions | LeetCode Alternative | InstaMock - AI Mock Interview