← Home

1616. Split Two Strings to Make Palindrome

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
prefix sumsC++Markdown
161

The trick here is to name the state correctly, then let the implementation follow. For 1616. Split Two Strings to Make Palindrome, the solution in this repository is mainly a prefix sums solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: prefix sums, greedy.

The notes already sitting in the source point us in the right direction:

  • naive O(N^2)
  • TLE
  • 65 / 102 test cases passed.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isPalindrome, checkPalindromeFormation, check.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Substring checks are convenient but not free, so they are part of the real complexity story.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//naive O(N^2)
02//TLE
03//65 / 102 test cases passed.
04class Solution {
05public:
06    bool isPalindrome(string s){
07        int n = s.size();
08        
09        for(int i = 0; i < n-1-i; ++i){
10            if(s[i] != s[n-1-i]) return false;
11        }
12        
13        return true;
14    }
15    
16    bool checkPalindromeFormation(string a, string b) {
17        int n = a.size();
18        
19        if(isPalindrome(a) || isPalindrome(b)) return true;
20        
21        for(int i = 1; i < n; ++i){
22            //prefix min length: 1
23            //suffix min length: 1
24            if(isPalindrome(a.substr(0, i) + b.substr(i))) return true;
25            if(isPalindrome(b.substr(0, i) + a.substr(i))) return true;
26        }
27        
28        return false;
29    }
30};
31
32//O(N^2)
33//TLE
34//76 / 102 test cases passed.
35class Solution {
36public:
37    bool isPalindrome(string s, int start, int end){
38        int n = s.size();
39        
40        for(int i = 0; start+i < end-i; ++i){
41            if(s[start+i] != s[end-i]) return false;
42        }
43        
44        return true;
45    }
46    
47    bool checkPalindromeFormation(string a, string b) {
48        int n = a.size();
49        
50        if(isPalindrome(a, 0, n-1) || isPalindrome(b, 0, n-1))
51            return true;
52        
53        int i = 0;
54        //a prefix + b suffix
55        while(a[i] == b[n-1-i]){
56            //split before n-1-i: a[0...i] + a[i+1...n-1-i-1] + b[n-1-i:]
57            //split after i     : a[0...i] + b[i+1...n-1-i-1] + b[n-1-i:]
58            if(isPalindrome(a, i+1, n-1-i-1)) return true;
59            if(isPalindrome(b, i+1, n-1-i-1)) return true;
60            ++i;
61        }
62
63        i = 0;
64        //b prefix + a suffix
65        while(b[i] == a[n-1-i]){
66            if(isPalindrome(b, i+1, n-1-i-1)) return true;
67            if(isPalindrome(a, i+1, n-1-i-1)) return true;
68            ++i;
69        }
70        
71        return false;
72    }
73};
74
75//O(N)
76//Runtime: 100 ms, faster than 33.33% of C++ online submissions for Split Two Strings to Make Palindrome.
77//Memory Usage: 28.9 MB, less than 16.67% of C++ online submissions for Split Two Strings to Make Palindrome.
78class Solution {
79public:
80    bool isPalindrome(string s, int start, int end){
81        int n = s.size();
82        
83        for(int i = 0; start+i < end-i; ++i){
84            if(s[start+i] != s[end-i]) return false;
85        }
86        
87        return true;
88    }
89    
90    pair<int,int> palindromeRange(string s){
91        int n = s.size();
92        
93        /*
94        n = 4, (i,j) = (1,2)
95        n = 5, (i,j) = (1,3)
96        */
97        int i = n/2-1, j = n/2+(n%2);
98        
99        while(i >= 0 && j < n && s[i] == s[j]){
100            --i;
101            ++j;
102        }
103        
104        return {i+1, j-1};
105    }
106    
107    bool checkPalindromeFormation(string a, string b) {
108        int n = a.size();
109        
110        pair<int, int> apr = palindromeRange(a);
111        pair<int, int> bpr = palindromeRange(b);
112        
113        if(apr.first == 0 || bpr.first == 0)
114            return true;
115        
116        int i = 0;
117        //a prefix + b suffix
118        while(a[i] == b[n-1-i]){
119            //split before n-1-i: a[0...i] + a[i+1...n-1-i-1] + b[n-1-i:]
120            //split after i     : a[0...i] + b[i+1...n-1-i-1] + b[n-1-i:]
121            if(i+1 >= apr.first) return true;
122            if(i+1 >= bpr.first) return true;
123            ++i;
124        }
125
126        i = 0;
127        //b prefix + a suffix
128        while(b[i] == a[n-1-i]){
129            if(i+1 >= bpr.first) return true;
130            if(i+1 >= apr.first) return true;
131            ++i;
132        }
133        
134        return false;
135    }
136};
137
138//O(N) greedy
139//https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/888885/C%2B%2BJava-Greedy-O(n)-or-O(1)
140//Runtime: 76 ms, faster than 50.00% of C++ online submissions for Split Two Strings to Make Palindrome.
141//Memory Usage: 24.5 MB, less than 25.00% of C++ online submissions for Split Two Strings to Make Palindrome.
142//time: O(N), space: O(1)
143class Solution {
144public:
145    bool isPalindrome(string& s, int i, int j){
146        while(i < j && s[i] == s[j]){
147            ++i;
148            --j;
149        }
150        
151        return i >= j;
152    }
153    
154    bool check(string& a, string& b){
155        int n = a.size();
156        int i = 0;
157        
158        /*
159        Greedy: match their two sides as more as possible,
160        so the middle part is more likely to be a palindrome
161        */
162        while(i < n-1-i && a[i] == b[n-1-i]){
163            ++i;
164        }
165        
166        return i >= n-1-i || isPalindrome(a, i, n-1-i) || isPalindrome(b, i, n-1-i);
167    }
168    
169    bool checkPalindromeFormation(string a, string b) {
170        return check(a, b) || check(b, a);
171    }
172};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.