Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

441
Views
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; 
 }
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!