× logo Home HTML CSS Javascript React-App Angular logo
logo

Mastering Top 10 Javascript Algorithms

**Algorithm Name**: Palindrome Check

* **Questions**:
Does case matter in our palindrome check?
Do we keep or remove white spaces, digits or special characters when checking for the palindrome property?
How do we handle null or undefined input?

* **Time Complexity**:
- Single Solution: O(n) where n is the length of the string.

* **Space Complexity**:
- Single Solution: O(n) where n is the length of the string. Javascript's string split method will create a new array that contains every character in the string as individual elements.

* **Approaches**:
- **Summary of Steps**

- Split the string into an array of individual characters.
- Reverse the order of the array of characters.
- Join the reversed array of characters back into a string.
- Compare the reversed string to the original string.

* **Explanation**:
A palindrome is a word, phrase or sequence that reads the same backwards as forwards. Therefore, to determine if the string is a palindrome, we need to reverse the string and check it against the original string. If they are the same, we can say that the string is a palindrome otherwise it is not.

* **Sample Code**:javascript

function isPalindrome(str) {

// Split the string into individual characters
const charArray = str.split('');

// Reverse the order of charArray
const reversedArray = charArray.reverse();

// Join the reversed array back into a string
const reversed = reversedArray.join('');
// Return whether the reversed string is equal to the original string

return str === reversed;
}

* **Example**:
- Input: 'racecar'
- Output: true
Here is an example demo with the racecar input:
//Unit Test
console.log(isPalindrome("racecar")); // Outputs: true




logo