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

247
Visualizações
JavaScript syntactic sugar when incrementing/decrementing variable

LeetCode 680. Valid Palindrome II Easy

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Can someone tell me why the first code below is much faster than the second code? The only difference between them is how I'm incrementing and decrementing my variables in the isPalindrome function.

var validPalindrome = function (s) {
  let left = 0;
  let right = s.length - 1;
  while (left < right) {
    if (s[left] !== s[right]) {
      return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
    }
    left++;
    right--;
  }
  return true;
};

let isPalindrome = (s, left, right) => {
  while (left < right) {
    if (s[left++] !== s[right--]) { // writing it this way is much faster
      return false;
    }
  }
  return true;
}

/*
Runtime: 72 ms, faster than 98.87% of JavaScript online submissions for Valid Palindrome II.
Memory Usage: 48.7 MB, less than 21.51% of JavaScript online submissions for Valid Palindrome II.
*/
var validPalindrome = function (s) {
  let left = 0;
  let right = s.length - 1;
  while (left < right) {
    if (s[left] !== s[right]) {
      return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1);
    }
    left++;
    right--;
  }
  return true;
};

let isPalindrome = (s, left, right) => {
  while (left < right) {
    if (s[left] !== s[right]) {
      return false;
    }
    left++; // this is slightly slower
    right--;
  }
  return true;
}

/*
Runtime: 116 ms, faster than 58.84% of JavaScript online submissions for Valid Palindrome II.
Memory Usage: 48.2 MB, less than 27.24% of JavaScript online submissions for Valid Palindrome II.
*/
Example 1:

Input: s = "aba"
Output: true
Example 2:

Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:

Input: s = "abc"
Output: false
about 4 years ago · Juan Pablo Isaza
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