Valid Palindrome

Program to check Valid Palindrome – Medium Level

Given a string s, return true if it is a palindrome, otherwise return false.

A palindrome is a string that reads the same forward and backward. It is also case-insensitive and ignores all non-alphanumeric characters.

Valid Palindrome

Explanation: After considering only alphanumerical characters we have “wasitacaroracatisaw”, which is a palindrome.

Explanation: “tabacat” is not a palindrome.

Constraints:

  • 1 <= s.length <= 1000
  • s is made up of only printable ASCII characters.

Valid Palindrome Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(n) time and O(1) space, where n is the length of the input string.

Hints for solving problems

Hint 1 :

A brute force solution would be to create a copy of the string, reverse it, and then check for equality. This would be an O(n) solution with extra space. Can you think of a way to do this without O(n) space?

Hint 2 :

Can you find the logic by observing the definition of palindrome or from the brute force solution?

Hint 3 :

A palindrome string is a string that is read the same from the start as well as from the end. This means the character at the start should match the character at the end at the same index. We can use the two pointer algorithm to do this efficiently.

There are mainly 2 approach to solve this problem-

  1. Reverse String Method
  2. Two Pointer Method

1. Reverse String Method

This approach involves reversing the string representation of the array elements, sorting the reversed strings, and then checking for the longest consecutive sequence. However, it’s not commonly used for this problem as it focuses on string manipulation.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

2. Two Pointers Method

In this method, you sort the array and use two pointers to iterate through the array while maintaining a count of consecutive elements to find the longest sequence. This is efficient when combined with sorting.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles