Kayla Famurewa
Kayla Famurewa

Reputation: 63

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

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; 
 }
}

Upvotes: 2

Views: 2037

Answers (1)

cfitzgerald
cfitzgerald

Reputation: 11

Scott's comment was correct:

You're right. You are very close. You don't return anything in the recursive call. If you replace solution (s) with return solution (s), it should work.

Encountered this same issue and it was just a missing return statement on the recursive call. Explains why some of your test cases passed that checked for len < 2.

Upvotes: 1

Related Questions