Problem
Write an algorithm to find Whether Given String is palindrome or Not.
Definition
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Recursion
Algorithm
- If the first and last characters don’t match, return
false
(not a palindrome). - If they match, remove the first and last characters and call the function recursively with the remaining substring. This continues until the entire string is checked.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
assuming recursion stack
Method 2 - Using 2 Pointer Approach
Start with 2 iterators at the start and the end till they meet in middle, and check each character. If they don’t match, we return false. If we reached end of loop, we return true.
Here is the video explanation:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Method 3 - Reversing the string
Code
|
|