Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
Why does my code not work out well replacing strings characters?

The exercise: The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

Examples "din" => "((("

"recede" => "()()()"

"Success" => ")())())"

"(( @" => "))(("

My code was like that:

    function duplicateEncode(word) {
      let str = "";
    
      for (let i = 0; i < word.length; i++) { //This iteration is to examine every character in the string;
        for (let j = 0; j < word.length; j++) { //This iteration is to compare every character to every other inside the string, in order to check if there is any repetition
          if (j === i) { //This first conditon was selected because a character is not supposed to be compared to itself
            continue;
          } else if (word[i] === word[j]) {
            str = str + ")";
            break;
          } else if (j !== word.length - 1) {
            continue;
          } else if (j === word.length - 1) {
            str = str + "(";
          } 
        }
      }
      return str;
    }

Does anyone can help me figure out why it doesn't work for all cases?

For example:

console.log(duplicateEncode("abc"));

It should return ((( instead of ((

But,

console.log(duplicateEncode("mulherm"));

returns exacly what it supposed to: )((((()

Apparently, whenever a string does not have a character that repeats,the function returns a string without the first element. But whenerver the string has at least one element that repeats it returns exacly what it's supposed to.

What is going on with my code?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think the issue is that when you use your snippet below, you prevent yourself from entering the last loop.

if (j === i) { 
   continue;
}

The issue is present whenever a word with a non duplicated letter is last. i.e.

This works

console.log(duplicateEncode("aba")); //returns )()

This does not

console.log(duplicateEncode("aab")); //returns ))

What you could do is add a statement that when

i === word.length - 1

and no "(" are in your str variable, you can append another ")" to your str.

In other words, if you have found no duplicated characters after checking the before last position while iterating over your entire word, the last is guaranteed to be unique as well.

Console logs below

function duplicateEncode(word) {
    let str = "";

    for (let i = 0; i < word.length; i++) { //This iteration is to examine every character in the string;
    for (let j = 0; j < word.length; j++) { //This iteration is to compare every character to every other inside the string, in order to check if there is any repetition
        console.log(i);
        console.log(j);
        console.log(str);
        if (j === i) { //This first conditon was selected because a character is not supposed to be compared to itself
            console.log("continue")
            continue;
        } else if (word[i] === word[j]) {
            console.log("append )")
            str = str + ")";
        break;
        } else if (j !== word.length - 1) {
            console.log("j !== length")
        continue;
        } else if (j === word.length - 1) {
            console.log("append (")
            str = str + "(";
        } 
    }
    }
    return str;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a debugger to step through your code line by line. There are cases where the inner loop completes without ever meeting one of the conditions for a adding a character to the string.

Instead, use a boolean flag to denote whether the letter is duplicated, set that inside the loop (much simpler logic), then after the loop do str += (found ? ')' : '(');. This ensures you add exactly one character to the output string per iteration of the outer loop.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda