MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / isPalindromeIterative

Function isPalindromeIterative

String/IsPalindrome.js:19–37  ·  view source on GitHub ↗
(x)

Source from the content-addressed store, hash-verified

17*/
18
19export function isPalindromeIterative(x) {
20 if (typeof x !== 'string' && typeof x !== 'number') {
21 throw new TypeError('Input must be a string or a number')
22 }
23
24 // Convert x to string whether it's number or string
25 const string = x.toString()
26 const length = string.length
27
28 if (length === 1) return true
29
30 // Apply two pointers technique to compare first and last elements on each iteration
31 for (let start = 0, end = length - 1; start < end; start++, end--) {
32 // Early return if compared items are different, input is not a palindrome
33 if (string[start] !== string[end]) return false
34 }
35 // If early return in condition inside for loop is not reached, then input is palindrome
36 return true
37}

Callers 1

Calls 1

toStringMethod · 0.45

Tested by

no test coverage detected