Day 3: Palindrome in JavaScript – 3 Methods with Simple Explanations

 ๐Ÿš€ Day 3 – Check if a String is a Palindrome (JavaScript DSA)


Hey developers ๐Ÿ‘‹,

Welcome to Day 3 of my JavaScript + DSA Interview Series – Code With Jaffer.


Today, we’re solving a super common and super important problem:


> ๐Ÿง  Check if a given string is a palindrome.





---


๐Ÿ” What is a Palindrome?


A palindrome is a word, phrase, number, or sequence that reads the same forward and backward.


๐Ÿ”ค Examples:


✅ "madam" → Palindrome


❌ "hello" → Not a palindrome


✅ "racecar" → Palindrome




---


๐Ÿ’ก Problem Statement:


Input: A string

Output: true if it's a palindrome, else false



---


✅ Solution 1: Built-in JavaScript Functions


function isPalindrome(str) {

  return str === str.split('').reverse().join('');

}


๐Ÿง  Explanation:


split(''): Converts string to array


reverse(): Reverses array


join(''): Combines back into a string


Compares reversed and original



๐Ÿ’ฌ Tips to Remember:


> Split → Reverse → Join → Compare

Use this when you need a quick and clean answer.




⏱️ Time: O(n) | ๐Ÿง  Space: O(n)

✅ Best for quick solutions in interviews



---


✅ Solution 2: Two-Pointer Approach (Efficient)


function isPalindrome(str) {

  let left = 0;

  let right = str.length - 1;


  while (left < right) {

    if (str[left] !== str[right]) return false;

    left++;

    right--;

  }

  return true;

}


๐Ÿง  Explanation:


Set two pointers: start and end


Compare characters from both ends


If mismatch → return false



๐Ÿ’ฌ Tips to Remember:


> “Left meets Right” — simple pointer technique

✅ Use this in coding rounds where performance matters




⏱️ Time: O(n) | ๐Ÿง  Space: O(1)

✅ Best for low memory usage



---


✅ Solution 3: Recursion (For Logic Practice)


function isPalindrome(str) {

  if (str.length <= 1) return true;

  if (str[0] !== str[str.length - 1]) return false;

  return isPalindrome(str.slice(1, -1));

}


๐Ÿง  Explanation:


Base case: 1 or 0 length string → true


Recursive call: compare outer chars, slice and check middle



๐Ÿ’ฌ Tips to Remember:


> Think like onion peeling ๐Ÿง… – remove outer layers recursively




⏱️ Time: O(n²) (due to slicing) | ๐Ÿง  Space: O(n)

⚠️ Avoid for large strings – good for concept-building



---


๐Ÿง  Interview Tips:


✅ Use the 2-pointer approach to show algorithmic thinking

✅ Use recursion only if interviewer asks for it

✅ Always explain your logic + complexity clearly

Comments

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge