MEDIUM NC#112 Blind #19 2-D Dynamic Programming

1143. Longest Common Subsequence

📖 Problem

Given two strings text1 and text2, return the length of their longest common subsequence.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • Array DP table updates
  • State transition thinking
  • Base case initialization

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Dynamic Programming reasoning pattern

💡 Approach

  • Use dp[i][j] = LCS length for text1[0:i] and text2[0:j+1]
  • If characters match: dp[i][j] = dp[i-1][j-1] + 1
  • If they don't: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
  • Time: O(m * n), Space: O(m * n)

🛠️ Hints & Pitfalls

Hints

  • Use dp[i][j] = LCS length for text1[0:i] and text2[0:j+1]
  • If characters match: dp[i][j] = dp[i-1][j-1] + 1
  • If they don't: dp[i][j] = max(dp[i-1][j], dp[i][j-1])

Common Pitfalls

  • Time: O(m * n), Space: O(m * n)

🧪 Test Cases

Test Case 1
Not run
Input:
longestCommonSubsequence('abcde', 'ace');
Expected:
null
Test Case 2
Not run
Input:
longestCommonSubsequence('abc', 'abc');
Expected:
null
Test Case 3
Not run
Input:
longestCommonSubsequence(text1: string, text2: string);
Expected:
Computed from hidden reference

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit