Two pointers: Valid Palindrome
by Raul Bojalil
HTML
<p>Write a function that takes a string, <code>s</code>, as an input and determines whether or not it is a palindrome.</p>
<div class="h-auto w-full whitespace-normal after:clear-both after:table after:content-none markdown-container-div"><div class="markdownViewer select-text markdown-default markdown-table markdown-viewer markdown-viewer-heading" role="none"><h4 class="hover-anchor" id="Solution-summary" data-id="87bbf7e35fe27305a7087e59419168c3">Solution summary<a href="#Solution-summary"><span class="anchor-link">#</span></a></h4>
<ul data-id="b71478cdbd73a1f6dc63faa5f5fca306">
<li>Initialize two pointers and move them from opposite ends.</li>
<li>The first pointer starts at the beginning of the string and moves toward the middle, while the second pointer starts at the end and moves toward the middle.</li>
<li>Compare the elements at each position to detect a nonmatching pair.</li>
<li>If both pointers reach the middle of the string without encountering a nonmatching pair, the string is a palindrome.</li>
</ul>
<h4 class="hover-anchor" id="Time-complexity" data-id="e7551b98ca1180b803b88ad14ecc30ed">Time complexity<a href="#Time-complexity"><span class="anchor-link">#</span></a></h4>
<p data-id="a1b82309ba0e9d92d53da2cdf3947ccb">The time complexity is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>O</mi><mo stretchy="false">(</mo><mi>n</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">O(n)</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.02778em;">O</span><span class="mopen">(</span><span class="mord mathnormal">n</span><span class="mclose">)</span></span></span></span>, where <span class="katex"><span class="katex-mathml"><math...
JavaScript
function isPalindrome (input) {
let lp = 0;
let rp = input.length - 1;
while (rp > lp) {
if (input[lp] !== input[rp]) return false;
rp--;
lp++;
}
return true;
}
let testCases = ["RACEACAR", "A", "ABCDEFGFEDCBA",
"ABC", "ABCBA", "ABBA", "RACEACAR"],
i = 1;
testCases.map((s, index) => {
console.log("Test Case #", i);
console.log("-".repeat(100));
console.log(`The input string is '${s}' and the length of the string is ${s.length}.`);
console.log("\nIs it a palindrome?.....", isPalindrome(s));
console.log("-".repeat(100));
i++;
});