Bird
Raised Fist0
Interview Prepdp-lcs-stringhardGoogleAmazon

Palindrome Partitioning II (Min Cuts)

Choose your preparation mode4 modes available
</>
IDE
def minCut(s: str) -> int:public int minCut(String s)int minCut(string s)function minCut(s)
def minCut(s: str) -> int:
    # Write your solution here
    pass
class Solution {
    public int minCut(String s) {
        // Write your solution here
        return 0;
    }
}
#include <string>
using namespace std;

int minCut(string s) {
    // Write your solution here
    return 0;
}
function minCut(s) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 0Returning zero cuts for all inputs, ignoring actual partitions.✅ Implement dp array and update minimum cuts based on palindrome substrings.
Wrong: n-1Assuming no palindromes longer than 1 without checking substrings.✅ Add palindrome checks for substrings and update dp accordingly.
Wrong: TLEUsing brute force recursion without memoization or DP.✅ Use DP with palindrome preprocessing or center expansion to achieve O(n^2).
Wrong: Incorrect cuts for all identical charactersNot recognizing full string palindrome for identical chars.✅ Ensure palindrome table or checks mark entire string as palindrome.
✓
Test Cases
t1_01basic
Input{"s":"aab"}
Expected1

The palindrome partitioning ['aa','b'] requires 1 cut.

t1_02basic
Input{"s":"abccba"}
Expected0

The entire string 'abccba' is a palindrome, so no cuts needed.

t2_01edge
Input{"s":""}
Expected0

Empty string requires zero cuts by definition.

t2_02edge
Input{"s":"z"}
Expected0

Single character string is always palindrome, so zero cuts needed.

t2_03edge
Input{"s":"abcde"}
Expected4

No palindromic substrings longer than 1, so cuts = length-1 = 4.

t2_04edge
Input{"s":"aaaaa"}
Expected0

All identical characters form a palindrome, zero cuts needed.

t3_01corner
Input{"s":"ababbbabbababa"}
Expected3

Complex palindrome partitions require careful DP, greedy approach fails here.

t3_02corner
Input{"s":"aaaaa"}
Expected0

All identical characters form a palindrome, zero cuts needed.

t3_03corner
Input{"s":"abcbaefgfe"}
Expected1

Multiple palindromic substrings with overlapping centers require careful DP.

t4_01performance
Input{"s":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
⏱ Performance - must finish in 2000ms

Input length n=100, O(n^2) DP must complete within 2 seconds.

Practice

(1/5)
1. Consider the following Python function implementing a space-optimized DP for longest common substring. What is the returned value when called with s1 = 'abc' and s2 = 'xbc'?
def longest_common_substring_space_optimized(s1, s2):
    n, m = len(s1), len(s2)
    dp = [0] * (m + 1)
    max_len = 0
    for i in range(1, n + 1):
        for j in range(m, 0, -1):
            if s1[i - 1] == s2[j - 1]:
                dp[j] = dp[j - 1] + 1
                if dp[j] > max_len:
                    max_len = dp[j]
            else:
                dp[j] = 0
    return max_len
easy
A. 2
B. 1
C. 3
D. 0

Solution

  1. Step 1: Trace dp array updates for i=1 (s1[0]='a')

    Compare 'a' with 'c','b','x' in s2 backwards: no matches, dp remains zeros.
  2. Step 2: Trace dp updates for i=2 (s1[1]='b') and i=3 (s1[2]='c')

    At i=2, j=2 matches 'b' == 'b', dp[2] = dp[1]+1=1; max_len=1. At i=3, j=3 matches 'c' == 'c', dp[3] = dp[2]+1=2; max_len=2.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Longest common substring is 'bc' length 2 [OK]
Hint: Trace dp updates backward to avoid overwriting [OK]
Common Mistakes:
  • Iterating dp forward overwrites needed values
  • Off-by-one indexing errors
  • Confusing max_len update timing
2. 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
3. Consider the following buggy code for the space-optimized edit distance. Which line contains the subtle bug that causes incorrect results for empty strings or boundary cases?
def minDistance(word1: str, word2: str) -> int:
    m, n = len(word1), len(word2)
    dp = list(range(n + 1))
    for i in range(1, m + 1):
        prev = dp[0]
        dp[0] = 0  # Bug here
        for j in range(1, n + 1):
            temp = dp[j]
            if word1[i - 1] == word2[j - 1]:
                dp[j] = prev
            else:
                dp[j] = min(dp[j] + 1, dp[j - 1] + 1, prev + 1)
            prev = temp
    return dp[n]
medium
A. Line 4: dp = list(range(n + 1))
B. Line 6: prev = dp[0]
C. Line 7: dp[0] = 0 # Bug here
D. Line 11: dp[j] = min(dp[j] + 1, dp[j - 1] + 1, prev + 1)

Solution

  1. Step 1: Understand dp[0] initialization role

    dp[0] represents cost of deleting all characters from word1 prefix to match empty word2 prefix, so it must be i, not 0.
  2. Step 2: Identify incorrect dp[0] reset

    Setting dp[0] = 0 inside loop resets deletion cost incorrectly, breaking base case for empty prefixes.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct dp[0] update is dp[0] = i [OK]
Hint: dp[0] must track deletions, so dp[0] = i each iteration [OK]
Common Mistakes:
  • Resetting dp[0] to zero
  • Confusing prev and temp
  • Misindexing dp array
4. The following code attempts to implement the space-optimized DP for maximum uncrossed lines. Which line contains a subtle bug that can cause incorrect results?
medium
A. Line 7: temp = dp[j]
B. Line 12: prev = temp
C. Line 11: dp[j] = max(dp[j], dp[j - 1])
D. Line 9: dp[j] = dp[j - 1] + 1

Solution

  1. Step 1: Understand role of prev variable

    In space-optimized DP, dp[j] depends on prev (dp[j-1] from previous iteration), not dp[j-1] of current iteration.
  2. Step 2: Identify incorrect dp update

    Line 9 uses dp[j - 1] from current iteration, which may have been updated already, causing incorrect results. It should use prev instead.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Using dp[j-1] instead of prev breaks correctness in space-optimized DP [OK]
Hint: Use prev to avoid overwriting dp[j-1] before use [OK]
Common Mistakes:
  • Using dp[j-1] instead of prev in update
  • Not preserving previous dp[j] value before update
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