Reputation: 37
I'm checking if the given string is palindrom or not, but the execution time is too long.
My code is below:
function checkPalindrome(inputString) {
for (let i = 0; i < (inputString.length - 1) / 2; i++) {
const a = inputString[i];
const b = inputString.split("").reverse().join("")[i];
if (a !== b) {
return false;
}
continue;
}
return true;
}
const palindrome = checkPalindrome("abba");
console.log(palindrome);
How can I optimize the code in order to reduce it's execution time?
Upvotes: 1
Views: 512
Reputation: 586
here is a little efficient recursive
solution
function checkPalindrome(inputString) {
const n = inputString.length
if(n == 0 || n == 1)
return true;
else{
if(inputString[0] != inputString[n-1]){
return false;
}
}
const t = inputString.slice(1, n-1)
return checkPalindrome(t)
}
console.log(checkPalindrome("abbca"))
or either more efficient
function checkPalindrome(inputString) {
return (inputString.split("").reverse()).join('') === inputString
}
console.log(checkPalindrome("abba"))
Upvotes: 0
Reputation: 6359
Why you are iterating each letter, When you can reverse it using array methods?
function checkPalindrome(inputString) {
return inputString === inputString.split("").reverse().join("");
}
let palindrome = checkPalindrome("abba");
console.log(palindrome);
palindrome = checkPalindrome("random");
console.log(palindrome);
palindrome = checkPalindrome("abba isi abba");
console.log(palindrome);
Upvotes: 0
Reputation: 903
Even better:
function palindrome(str) {
var re = /[\W_]/g;
// convert to lower case and remove spaces
var lower = str.toLowerCase().replace(re, '');
// reverse the string
var reverse = lower.split('').reverse().join('');
// check if reversed and actual string is same
return reverse === lower;
}
console.log(palindrome("sir"))
console.log(palindrome("madam"))
Upvotes: 0
Reputation: 1165
You can check with a simple for
loop
function checkPalindrome(inputString) {
const len = inputString.length;
for (let i = 0; i < len / 2; i++) {
if (inputString[i] !== inputString[len - 1 - i])
return 'not a palindrome';
}
return 'palindrome';
}
console.log(checkPalindrome('madam'))
Upvotes: 1
Reputation: 136124
Dont repeat yourself! You're splitting and reversing the string every iteration.
function checkPalindrome(inputString) {
const reversed = inputString.split("").reverse()
for (let i = 0; i < (inputString.length - 1) / 2; i++) {
const a = inputString[i];
const b = reversed[i]
if (a !== b) {
return false;
}
continue; /// pointless also - you're already at the end of the loop
}
return true;
}
console.log(checkPalindrome("sir"))
console.log(checkPalindrome("madam"))
That's the big one, there are other micro optimizations you can make such as not evaluating the loop control every time, but it will make very little difference unless your input is huge.
Upvotes: 0