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
Post a Comment