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

198
Views
Javascript reduce method returns wrong value

I need to find the length of the longest substring in a string, I do it by this:

var lengthOfLongestSubstring = function(s) {
    let arr = [];
    let obj = {};
    for(let i = 0; i<s.length; i++){
        
        if(arr.indexOf(s[i])!==-1){
            copy=arr.slice();
            obj[i]=copy;
            arr=[];
            arr.push(s[i])
        }
        else{
            arr.push(s[i]);
        }
    }
    console.log(obj)
    return Object.values(obj).reduce((acc, nextItem)=>{
        if(acc&acc.length>=nextItem&&nextItem.length){
            return acc.length;
        }
        else{
            return nextItem.length
        }
    }, [])
};

console.log (lengthOfLongestSubstring ('abcabcbb'));

For test case "abcabcbb" it returns 1 instead of 3 and I don't understand why; btw what complexity (in terms of big O) would my code achieve?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

the variant you have should work, just fix few typos in your code:

  return Object.values(obj).reduce((acc, nextItem) => acc >= nextItem.length ? acc.length : nextItem.length , 0)
about 4 years ago · Juan Pablo Isaza Report
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!