Given a string of characters, Check if the given string is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forwards, e.g. "racecar" or nurses run.
The first solution is intuitive and relies on the javascript's reverse()
, split()
and join()
method.
""
, so that every character will be a separate character in the array. Therefore, the string "race car"
becomes ["r", "a", "c", "e", " ", "c", "a", "r"]
reverse()
method to reverse the string.join()
method.equal to
the given string, return true
, else return false
O(n)
because we reverse the given string.left
and right
. Initialize left = 0
and right = stringLength - 1
.left < right
.str[i] !== str[j]
. If this is not the case, we can be sure that the strings are not palindrome. Because the extreme ends must be equal for a string to be a palindrome.left
AND decrement right
.O(n)
- Because we iterate atleast the half of the array.i
value in the palindromeCheck()
function.j
value by str.length - 1 - i
.(i >= j)
- this means we've crossed OR are standing at the middle of the array and we return true
;str[i] !== str[j]
- Trying to check if the values at i
and j
are not equal. If they're not equal, return true
i
value by palindromeCheck(str, i+1)
O(n)
because we will have to go till n/2
values at most.O(n)
because we will have to go till n/2
depth at most.