Bird
Raised Fist0
Interview Prepdp-lcs-stringmediumAmazonMicrosoftGoogleFacebook

Longest Palindromic Substring

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize DP Table and Variables

Create a 5x5 DP table initialized with false, and set start=0 and max_len=1 to track the longest palindrome found so far.

💡 Initializing the DP table and variables sets the foundation for marking palindromic substrings.
Line:n = len(s) dp = [[false] * n for _ in range(n)] start, max_len = 0, 1
💡 We need a table to record palindrome status for all substrings and variables to track the longest palindrome.
📊
Longest Palindromic Substring - Watch the Algorithm Execute, Step by Step
Watching the table fill reveals how smaller palindrome results build up to larger ones, making the logic crystal clear.
Step 1/13
·Active fill★Answer cell
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
s[0] = 'b' palindrome
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'b' != 'a'
Item 1 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'a' != 'b'
Item 2 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'b' != 'a'
Item 3 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'a' != 'd'
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'bab' palindrome
Item 1 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'aba' palindrome
Item 2 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'b' != 'd'
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'b' != 'a'
Item 1 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'a' != 'd'
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
'b' != 'd'
Item 0 - wt:0 val:0
i\w01234
i=0
i=1
i=2
i=3
i=4
Longest palindrome 'bab'

Key Takeaways

✓ The DP table diagonal represents all single-character palindromes.

This base case is easy to overlook but is essential for building longer palindromes.

✓ Two-character substrings are palindromes only if both characters match.

This step bridges the base case and the general case, showing how the table starts to fill beyond single characters.

✓ For substrings longer than 3, palindrome status depends on the substring inside the ends.

This dependency is the core insight of the DP approach and is visually clear when watching the table fill diagonally.

Practice

(1/5)
1. You are given two strings and need to find the shortest string that contains both as subsequences. Which algorithmic approach guarantees finding this shortest common supersequence efficiently?
easy
A. Greedy approach that merges characters from both strings whenever they differ
B. Dynamic programming based on longest common subsequence to build the shortest supersequence
C. Pure brute force recursion enumerating all supersequences and selecting the shortest
D. Sorting characters of both strings and merging them in lexicographical order

Solution

  1. Step 1: Understand the problem requires minimal length supersequence containing both strings as subsequences

    Greedy or sorting approaches fail because they do not consider subsequence order constraints.
  2. Step 2: Recognize that longest common subsequence (LCS) helps identify overlapping parts to minimize duplication

    Dynamic programming using LCS length allows building the shortest common supersequence efficiently.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    LCS-based DP is the classic and optimal approach for shortest common supersequence [OK]
Hint: Shortest common supersequence uses LCS-based DP [OK]
Common Mistakes:
  • Thinking greedy merging always works
  • Confusing substring with subsequence
  • Assuming sorting helps
2. The following code attempts to count palindromic substrings by expanding around centers. Identify the line containing the subtle bug that causes incorrect counts for even-length palindromes.
def countSubstrings(s: str) -> int:
    n = len(s)
    count = 0

    def expand(left, right):
        nonlocal count
        while left >= 0 and right < n and s[left] == s[right]:
            count += 1
            left -= 1
            right += 1

    for i in range(n):
        expand(i, i)      # Odd length palindromes
        expand(i, i)      # Even length palindromes (bug here)

    return count
medium
A. Line calling expand(i, i) for even length palindromes
B. Line calling expand(i, i) for odd length palindromes
C. Line decrementing left inside expand function
D. Line incrementing right inside expand function

Solution

  1. Step 1: Understand even length palindrome expansion

    Even length palindromes require expanding around two adjacent indices, i and i+1.
  2. Step 2: Identify incorrect call

    Calling expand(i, i) twice means even length expansions are not checked; should be expand(i, i+1).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Even length palindromes like "aa" missed due to wrong center [OK]
Hint: Even length palindromes need expand(i, i+1) call [OK]
Common Mistakes:
  • Using same indices for odd and even expansions
3. The following code attempts to count distinct subsequences of t in s using space-optimized DP. Which line contains a subtle bug that causes incorrect results on some inputs?
medium
A. Line 6: dp = [0] * (n + 1)
B. Line 9: for j in range(1, n + 1): # iterating forwards
C. Line 4: dp[0] = 1
D. Line 10: if s[i - 1] == t[j - 1]:

Solution

  1. Step 1: Identify iteration direction over dp array

    The inner loop iterates j forwards from 1 to n, which causes dp[j-1] to be overwritten before use.
  2. Step 2: Understand consequence of forward iteration

    Forward iteration corrupts dp values needed for correct counting, leading to undercount or overcount of subsequences.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct code iterates j backward to preserve dp[j-1] values [OK]
Hint: Inner loop must iterate backward to avoid overwriting dp[j-1] [OK]
Common Mistakes:
  • Iterating dp array forwards in space-optimized DP
4. What is the time and space complexity of the space-optimized bottom-up DP solution for the Minimum ASCII Delete Sum problem, given strings of lengths m and n?
medium
A. Time: O(m+n), Space: O(m+n)
B. Time: O(m*n), Space: O(n)
C. Time: O(m*n), Space: O(m*n)
D. Time: O(2^(m+n)), Space: O(m+n)

Solution

  1. Step 1: Identify nested loops

    Outer loop runs m times, inner loop runs n times -> total O(m*n) time.
  2. Step 2: Analyze space usage

    Only one dp array of size n+1 is used, so space is O(n).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Matches known DP optimization for string problems [OK]
Hint: Nested loops multiply time; dp array size defines space [OK]
Common Mistakes:
  • Confusing recursion stack space with DP array space
5. Suppose you want to count palindromic substrings in a string where characters can be replaced any number of times (reusable characters). Which modification to the expand around center approach correctly handles this variant?
hard
A. No modification needed; the original expand around center approach already counts palindromes with replacements.
B. Modify expand to allow skipping mismatched characters to find palindromes with replacements.
C. Precompute all possible character replacements and run the original expand around center for each variant.
D. Use dynamic programming with memoization to store counts for substrings allowing character replacements.

Solution

  1. Step 1: Understand the variant

    Allowing character replacements means palindrome checks must consider substitutions, not exact matches.
  2. Step 2: Evaluate approaches

    Expand around center relies on exact matches; skipping mismatches breaks palindrome definition. Precomputing all variants is exponential. DP with memoization can track allowed replacements efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP can handle flexible palindrome definitions with substitutions [OK]
Hint: Exact match expansion fails when replacements allowed [OK]
Common Mistakes:
  • Assuming original approach works without changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard