prefixes and palindromes recursion problem so close to working, what is going wrong here? multiple test cases returning null

Viewed 771

For some reason, my solution is returning null instead of the value that is stored in 's'. Instructions and code are below:

You are given a string s. Consider the following algorithm applied to this string:

Take all the prefixes of the string, and choose the longest palindrome between them. If this chosen prefix contains at least two characters, cut this prefix from s and go back to the first step with the updated string. Otherwise, end the algorithm with the current string s as a result. Your task is to implement the above algorithm and return its result when applied to string s.

test case const s = "aaacodedoc"
expected output: ""

another test case
const s = "abbab" expected output: "b"

function solution(s) {

const prefixes =[]
if(s.length === 0){
    return ""
} 

if(s.length === 1){
    return s
} 


for(let i = 0; i < 1; i++){
    for(let j = i; j < s.length; j++){
        const substr = s.substring(i, j + 1)
        prefixes.push(substr)
    }
}

const palindromes = prefixes.filter(prefix => {
    let reverse = prefix.split('').reverse().join('');
    return prefix === reverse
})

let longest = palindromes.sort(
function (a, b) {
    return b.length - a.length;
})[0];

 if(longest.length >= 2){
    s = s.substring(longest.length)
    solution(s)
 } else{
    return s; 
 }
}
0 Answers
Related