Python Interview coding 2 With Funny Example

🔁 How to Check if a String is a Palindrome in Python

Ever wondered if a word or phrase reads the same forward and backward? That's called a palindrome! 😃 Words like radar, level, and madam are palindromes.

In this blog, we’ll learn how to write a Python program to check for palindromes using different methods. Let’s get started! 🚀

🛠️ Method 1: Using String Slicing [::-1]

The easiest way to check for a palindrome is by reversing the string and comparing it with the original.


def is_palindrome(s):
    return s == s[::-1]  # Reverse and compare

# Example Usage
word = "racecar"
print(f"Is '{word}' a palindrome? {is_palindrome(word)}")

word2 = "hello"
print(f"Is '{word2}' a palindrome? {is_palindrome(word2)}")

    

🔍 Explanation (Line-by-Line)

  • def is_palindrome(s): → Define a function that takes a string s as input.
  • return s == s[::-1] → Reverse the string using slicing ([::-1]) and check if it matches the original string.
  • word = "racecar" → Example word to test.
  • print(f"Is '{word}' a palindrome? {is_palindrome(word)}") → Print whether "racecar" is a palindrome.

📊 Time and Space Complexity

  • Time Complexity: O(n) → Reversing the string takes linear time.
  • Space Complexity: O(n) → A new reversed string is created.

✅ Method 2: Using a Loop

If you don’t want to use slicing, you can compare characters one by one from both ends.


def is_palindrome_loop(s):
    left, right = 0, len(s) - 1  # Initialize pointers at both ends
    while left < right:
        if s[left] != s[right]:  # Compare characters
            return False
        left += 1  # Move left pointer forward
        right -= 1  # Move right pointer backward
    return True  # If all characters match, it's a palindrome

# Example Usage
word = "level"
print(f"Is '{word}' a palindrome? {is_palindrome_loop(word)}")

word2 = "python"
print(f"Is '{word2}' a palindrome? {is_palindrome_loop(word2)}")

    

🔍 Explanation (Line-by-Line)

  • left, right = 0, len(s) - 1 → Start two pointers at opposite ends.
  • while left < right: → Loop while left is before right.
  • if s[left] != s[right]: return False → If any mismatch, return False.
  • left += 1 → Move left pointer forward.
  • right -= 1 → Move right pointer backward.
  • return True → If no mismatches, return True.

📊 Time and Space Complexity

  • Time Complexity: O(n) → We traverse the string once.
  • Space Complexity: O(1) → No extra space is used.

🏆 Conclusion: Which Method is Best?

Method Pros Cons Time Complexity Space Complexity
Slicing [::-1] Simple and clean Uses extra memory O(n) O(n)
Loop Memory efficient More code O(n) O(1)

Both methods work well! If you need a quick check, use slicing. If you need better efficiency, use a loop. 🚀

Try it out! What are some funny palindromes you know? 😆

python-interview-coding-3-with-funny-example

Comments