Script
Script3y ago

Script – 13-45 Feb 2

I am trying to create a palindrome algorithm to make a word a palindrome and return the index I have to remove to make it a palindrome. I came up with this:
function palindromeIndex(s) {
let re = /[\W_]/g;

let lowRegStr = s.toLowerCase().replace(re, "").split("");
let reverseStr = s.toLowerCase().replace(re, "").split("").reverse();
let removed;
let removedRev;

if (lowRegStr.join("") === reverseStr.join("")) {
return -1;
}

for (let i = 0, k = s.length - 1; i < s.length; i++, k--) {
removed = lowRegStr.splice(i, 1);
removedRev = reverseStr.splice(k, 1);

if (lowRegStr.join("") === reverseStr.join("")) {
return i;
}
lowRegStr.splice(i, 0, ...removed);
reverseStr.splice(k, 0, ...removedRev);
}

return -1;
}
console.log(palindromeIndex("eye"));
function palindromeIndex(s) {
let re = /[\W_]/g;

let lowRegStr = s.toLowerCase().replace(re, "").split("");
let reverseStr = s.toLowerCase().replace(re, "").split("").reverse();
let removed;
let removedRev;

if (lowRegStr.join("") === reverseStr.join("")) {
return -1;
}

for (let i = 0, k = s.length - 1; i < s.length; i++, k--) {
removed = lowRegStr.splice(i, 1);
removedRev = reverseStr.splice(k, 1);

if (lowRegStr.join("") === reverseStr.join("")) {
return i;
}
lowRegStr.splice(i, 0, ...removed);
reverseStr.splice(k, 0, ...removedRev);
}

return -1;
}
console.log(palindromeIndex("eye"));
It works fine but after running tests I discovered its not efficient. What other efficient way can be used?
11 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Script
ScriptOP3y ago
palindromeIndex("eye") Input is a string Expected output should be -1 because it's a palindrome already But if we have "eyes", expected output should be 3 which is the index of the letter needed to be removed to make it a palindrome Definition of palindrome : a word, verse, or sentence (such as "Able was I ere I saw Elba") or a number (such as 1881) that reads the same backward or forward.
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Script
ScriptOP3y ago
it would return -1
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Script
ScriptOP3y ago
2
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Script
ScriptOP3y ago
sorry 1
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Script
ScriptOP3y ago
yy
reactibot
reactibot3y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/938429855521972264

Did you find this page helpful?