Tutorialspoint
Problem
Solution
Submissions

Check if a String is a Palindrome

Certification: Basic Level Accuracy: 69.88% Submissions: 166 Points: 5

Write a Python program to check if a given string is a palindrome. A palindrome is a string that reads the same forwards and backwards.

Example 1
  • Input: "racecar"
  • Output: True
  • Explanation:
    • Step 1: Reverse the string "racecar" to get "racecar".
    • Step 2: Compare the original string with the reversed string.
    • Step 3: Since "racecar" == "racecar", return True.
Example 2
  • Input: "hello"
  • Output: False
  • Explanation:
    • Step 1: Reverse the string "hello" to get "olleh".
    • Step 2: Compare the original string with the reversed string.
    • Step 3: Since "hello" != "olleh", return False.
Constraints
  • 1 ≤ len(string) ≤ 10^6
  • The string contains printable ASCII characters.
  • Time Complexity: O(n), where n is the length of the string.
  • Space Complexity: O(1)
StringsControl StructuresCognizanteBay
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Compare the string with its reverse: s == s[::-1]
  • Use a loop to compare characters from the start and end moving towards the center.
  • Handle edge cases where the string is empty or has only one character.

The following are the steps to check if a string is a palindrome:


  • Function Definition: The function is_palindrome takes an input string.
  • Cleaning the String: It removes spaces and converts the string to lowercase.
  • Checking for Palindrome: It compares the cleaned string with its reverse.
  • Result: If both are the same, the function returns True; otherwise, False.
  • Example Output: For the input "racecar", the function returns True.

Submitted Code :