Longest Palindrome After Substring Concatenation II

HARD

Description

You are given two strings, s and t.

You can create a new string by selecting a substring from s (possibly empty) and a substring from t (possibly empty), then concatenating them in order.

Return the length of the longest palindrome that can be formed this way.

 

Example 1:

Input: s = "a", t = "a"

Output: 2

Explanation:

Concatenating "a" from s and "a" from t results in "aa", which is a palindrome of length 2.

Example 2:

Input: s = "abc", t = "def"

Output: 1

Explanation:

Since all characters are different, the longest palindrome is any single character, so the answer is 1.

Example 3:

Input: s = "b", t = "aaaa"

Output: 4

Explanation:

Selecting "aaaa" from t is the longest palindrome, so the answer is 4.

Example 4:

Input: s = "abcde", t = "ecdba"

Output: 5

Explanation:

Concatenating "abc" from s and "ba" from t results in "abcba", which is a palindrome of length 5.

 

Constraints:

  • 1 <= s.length, t.length <= 1000
  • s and t consist of lowercase English letters.

Approaches

Checkout 2 different approaches to solve Longest Palindrome After Substring Concatenation II. Click on different approaches to view the approach and algorithm in detail.

Brute-Force Enumeration of Substrings

The most straightforward approach is to exhaustively check every possible palindrome that can be formed. We can iterate through all substrings of s and all substrings of t, concatenate them, and check if the resulting string is a palindrome. We keep track of the maximum length found.

Algorithm

  • Initialize maxLength to 0.
  • Generate all possible non-empty substrings of s. Let a substring be sub_s.
  • Generate all possible non-empty substrings of t. Let a substring be sub_t.
  • For each pair of (sub_s, sub_t):
    • Create the concatenated string newStr = sub_s + sub_t.
    • Check if newStr is a palindrome.
    • If it is, update maxLength = max(maxLength, newStr.length()).
  • Also consider cases where one of the substrings is empty. This means finding the longest palindromic substring within s and t individually and updating maxLength.
  • Return maxLength.

This method involves a nested loop structure to generate all substrings and then test them.

  1. Generate Substrings: We use four nested loops to define the start and end indices for substrings from both s and t.
  2. Concatenate and Test: For each pair of substrings, sub_s and sub_t, we form a new string. A helper function is used to check if this new string is a palindrome. This check can be done by comparing the string with its reverse.
  3. Handle Empty Substrings: The problem allows for empty substrings. This is equivalent to finding the longest palindromic substring within s or t alone. This should be done as a base case.

Here is a conceptual code snippet for the core logic:

public int longestPalindrome(String s, String t) {
    int n = s.length();
    int m = t.length();
    int maxLen = 0;

    // Helper to find longest palindromic substring in a single string
    // maxLen = Math.max(lps(s), lps(t));

    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            String sub_s = s.substring(i, j + 1);
            for (int k = 0; k < m; k++) {
                for (int l = k; l < m; l++) {
                    String sub_t = t.substring(k, l + 1);
                    String combined = sub_s + sub_t;
                    if (isPalindrome(combined)) {
                        maxLen = Math.max(maxLen, combined.length());
                    }
                }
            }
        }
    }
    return maxLen;
}

private boolean isPalindrome(String str) {
    int left = 0, right = str.length() - 1;
    while (left < right) {
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

Complexity Analysis

Time Complexity: O(N² * M² * (N + M)). There are O(N²) substrings in `s` and O(M²) in `t`. For each pair, concatenation takes O(N+M) and the palindrome check takes O(N+M). This is computationally prohibitive.Space Complexity: O(N + M), where N and M are the lengths of `s` and `t`. This space is used to store the concatenated string.

Pros and Cons

Pros:
  • Simple to understand and implement.
Cons:
  • Extremely inefficient due to the large number of substring pairs.
  • The time complexity makes it infeasible for the given constraints.

Code Solutions

Checking out 3 solutions in different languages for Longest Palindrome After Substring Concatenation II. Click on different languages to view the code.


Video Solution

Watch the video walkthrough for Longest Palindrome After Substring Concatenation II



Patterns:

Two PointersDynamic Programming

Data Structures:

String

Subscribe to Scale Engineer newsletter

Learn about System Design, Software Engineering, and interview experiences every week.

No spam, unsubscribe at any time.