Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
Recursion issue with my approach or concept or the issue?

So I am doing an algorithm challenge where I am given an array of words and I must capitalize the first letter of the word and return the arr with the new words. it must be done with recursion. I believe my approach is wrong, but if it's conceptually please let me know and how I should be thinking about this. If anyone could help describe how I should be approaching this both conceptually and in code it would be really helpful.

To describe my idea of how this is working conceptually:

 1st call: ['Car'] + capitalizeFirst([taco, banana]);
 2nd call: ['Taco'] + capitalizeFirst([banana]);
 3rd call: ['Banana'] + capitalizeFirst(['']);

so then as it walks back it returns

['Banana'] + ['""']
['Taco'] + ['Banana']
['Car'] + ['Taco','Banana']
returns ['Car','Taco','Banana']

but what I Am getting is 'CarTacoBanana'.
here is the approach I took.

function capitalizeFirst (arr) {

  if (!arr.length) return '';
  arr[0] = arr[0].charAt(0).toUpperCase() + arr[0].slice(1);
  return [ arr[0] + capitalizeFirst(arr.slice(1)) ];

}

capitalizeFirst(['car','taco','banana']); // ['Car','Taco','Banana']

(edit) I was able to solve my approach was wrong! here was my solution

  let newArr = [];
  if (!arr.length) {
    return newArr;
  }
  else {
       arr[0] = arr[0].charAt(0).toUpperCase() + arr[0].slice(1);
       newArr.push(arr[0]);
    }
  

  console.log(newArr, 'test');

  return newArr.concat(capitalizeFirst(arr.slice(1)))
  // return newArr;

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

function capitalizeFirst(arr) {
  // define the recursion terminal condition
  if (!arr.length) return [];
  // utility to capitalize first letter
  const capWord = s => s.charAt(0).toUpperCase() + s.slice(1);
  
 
  // a well-written recursive function makes clear what each iteration does, here:
  // capitalize the first word, then recurse on the remaining words...
  const first = arr[0], rest = arr.slice(1);
  return [ capWord(first), ...capitalizeFirst(rest) ];
}

let arr = [ 'every', 'good', 'boy', 'does', 'fine' ];
let result = capitalizeFirst(arr);
console.log(result);

I think you got the rough idea but you missed some stuff from general algorithm design as well the implementation perspective. It's better to uniformly return something (like [] here) and then combine them to form the answer. So I changed the base case and inductive case a bit and then you can get the properly formatted answer.

This is the rough code and you can check for the basic corner case test on your own from this point onwards.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your thought process is close but I would suggest changing [""] to a simple [] – I don't see where the empty string is coming in, but it's not needed -

const capitalize = ([ first, ...more ]) =>
  first.toUpperCase() + more.join("")

const capitalizeAll = ([ first, ...more ]) =>
  first == null
    ? []
    : [capitalize(first), ...capitalizeAll(more)]

console.log(capitalizeAll(["car", "taco", "banana"]))

// ["Car", "Taco", "Banana"]

Note, capitalizeAll is nothing more than Array.prototype.map with a hard-coded call to capitalize -

const capitalize = ([ first, ...more ]) =>
  first.toUpperCase() + more.join("")

console.log(["car", "taco", "banana"].map(capitalize))

// ["Car", "Taco", "Banana"]

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda