Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Backtracking/PalindromePartitioning.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Palindrome Partitioning Algorithm
* Given a string, find all possible ways to partition it into palindromic substrings
*/

function isPalindrome(s, left, right) {
while (left < right) {
if (s[left] !== s[right]) return false;
left++;
right--;
}
return true;
}

function partition(s) {
const result = [];
const current = [];

function backtrack(start) {
if (start === s.length) {
result.push([...current]);
return;
}

for (let end = start; end < s.length; end++) {
if (isPalindrome(s, start, end)) {
current.push(s.substring(start, end + 1));
backtrack(end + 1);
current.pop();
}
}
}

backtrack(0);
return result;
}

export { partition };
Loading