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

246
Views
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
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!