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

198
Vistas
Array item `String` is not mutable

I'm trying to solve 557 on leetCode with two pointers, and I found a strange behavior, which I cannot explain.

Below is my code

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    // return s.split(" ").map(w => w.split("").reverse().join("")).join(" ")
    let arr = s.split(" "), w
    for(let i = 0; i < arr.length; i++){
        let x = arr[i], left = 0, right = x.length - 1, holder = null
        while(left < right){
            holder = x[left]
            x[left] = x[right]
            x[right] = holder
            left += 1
            right -= 1
        }
    }
    return arr.join(" ")
};

and example "Let's take LeetCode contest"

while I can move the while loop to a function and solve it in a different way, I'm not sure why x is not changing, from my understanding this is an array item and can be changed.

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

0

This happens because the variable "x" is not an array but a String which comes from the variable "arr" to make it work you need to change

let x = arr[i]

to

let x = arr[i].split("")

the correct code is:

var reverseWords = function(s) {
    // return s.split(" ").map(w => w.split("").reverse().join("")).join(" ")
    let arr = s.split(" "), w
    for(let i = 0; i < arr.length; i++){
        let x = arr[i].split(""), left = 0, right = x.length - 1, holder = null
        while(left < right){
            holder = x[right]
            x[right] = x[left]
            x[left] = holder
            left += 1
            right -= 1
        }
        arr[i] = x.join("");
    }
    return arr.join(" ")
};
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