1. Whole string cut
Reaching the end means every piece in the path is a palindrome.
if (start === s.length)Typorithm · medium
Step 1 of 8 · intro card
Backtracking
Cut the string at every position where the prefix is a palindrome, then recurse on the rest.
A partition splits the string into pieces that are each palindromes.
At each start, try every end; only recurse when the substring start..end is a palindrome.
Reaching the string's end means the current path is a complete valid partition.
Cut only palindromic prefixes.
Recurse on the remaining suffix.
Base case: start reaches the end.
function partition(s) {
const result = [];
function isPalindrome(left, right) {
while (left < right) {
if (s[left] !== s[right]) return false;
left += 1;
right -= 1;
}
return true;
}
function backtrack(start, path) {
if (start === s.length) {
result.push([...path]);
return;
}
for (let end = start; end < s.length; end += 1) {
if (!isPalindrome(start, end)) continue;
path.push(s.slice(start, end + 1));
backtrack(end + 1, path);
path.pop();
}
}
backtrack(0, []);
return result;
}Connect each part of the code to the concept before you type.
Reaching the end means every piece in the path is a palindrome.
if (start === s.length)Each end position is a candidate cut point for the next piece.
for (let end = start; end < s.length; end += 1)Only cut a piece that is itself a palindrome.
if (!isPalindrome(start, end)) continueAdd the palindromic substring to the current partition.
path.push(s.slice(start, end + 1))Remove the piece to try a different cut.
path.pop()Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText aab
Follow temporary values, local state and supporting structures at this step.
Live recursive calls, including their arguments. Returning releases the top frame.
Accepted partitions0 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state