'Coding has over 700 languages', '67% of programming jobs arenâ€™t in the
technology industry', 'Coding is behind almost everything that is powered
by electricity'

In this article, we'll explore the concept of palindrome numbers and how to determine them in Python without using extra space. Palindromes are unique numbers that read the same forwards and backward. We'll focus on Python's efficient methods for identifying such numbers, highlighting space-efficient strategies suitable for various programming scenarios.

What is Palindrome?

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. In other words, it is a sequence of characters that is spelled the same way from left to right and right to left. Examples of palindromes include "racecar," "level," and "madam." Palindromes are often used in puzzles, word games, and cryptography.

Get the tech career you deserve, faster!

Connect with our expert counsellors to understand how to hack your way to success

User rating 4.7/5

1:1 doubt support

95% placement record

Akash Pal

Senior Software Engineer

326% Hike After Job Bootcamp

Himanshu Gusain

Programmer Analyst

32 LPA After Job Bootcamp

After Job Bootcamp

What is a Palindrome Number in python?

A number that is unchanged when the number or digits are reversed is known as a palindrome number in Python. For example, the palindrome numbers are 131, 22, 515, 2332, and 84848. I hope now you have got an fair understanding of the Palindrome Number in Python.

Let's have a look at the Problem statement based on Palindrome number in Python.

Problem statement

A number is provided to us. Our objective is to determine whether the provided number is a palindrome or not.

Before we move to the code logic for finding Palindrome Number in Python, letâ€™s understand through some examples of Palindrome numbers in Python.

Sample Examples

The below are some examples of Palindrome Number in Python .

Input: n = 1991991

Output: YES

Explanation:

Original: 1991991

After reversing: 1991991

The given number is the same as the reversed number formed by doing certain operations. This implies that the provided number is a palindrome number in python.

Input: 33568

Output: NO

Explanation:

Original: 33543

After reversing: 86533

The given number is not the same as the reversed number formed. This implies that the number is definitely not a palindrome number in python.

Now, Letâ€™s move on to the code the logic for finding a Palindrome Number using Python.

Palindrome in Python Code

Method 1: Using While Loop (number)

num = 1001
temp = num
reverse_num = 0
while temp != 0:
digit = temp % 10
reverse_num = (reverse_num * 10) + digit
temp //= 10
if num == reverse_num:
print(num, "is a palindrome number")
else:
print(num, "is not a palindrome number")

In this code, we first take the input number from the user. We then create a temporary variable to store the number and a variable called reverse_num to store the reversed number. We use a while loop to extract the digits of the number one by one and build the reversed number by multiplying the current reverse_num by 10 and adding the current digit. Once the loop is done, we check if the original number is equal to the reversed number and print an appropriate message.

Output

1001 is a palindrome number

Method 2: Using While Loop (strings)

string = "palap"
length = len(string)
i = 0
j = length - 1
while i < j:
if string[i] != string[j]:
print(string, "is not a palindrome string")
break
i += 1
j -= 1
else:
print(string, "is a palindrome string")

In this code, we first take the input string from the user and find its length. We then initialize two variables i and j to point to the first and last characters of the string, respectively. We use a while loop to compare the characters at the i and j indices of the string. If they don't match, we print a message saying that the string is not a palindrome and break out of the loop. If the loop completes without breaking, we print a message saying that the string is a palindrome.

Output

palap is a palindrome string

Palindrome Number Program in Python

Approach 1: Iterative Method

So, assuming input is provided in the string format or Type (Because if the number is greater than 10^18, then we have to store it in a String variable),

Run a loop from starting to length/2 and check the string's first and last characters, as well as the second and third ones, and so on. Any character mismatch would make the string a non-palindrome Number or string. Here the input is provided in string format

def isPalindrome(str):
#Loop from index 0 to mid of the string.
for i in range(0, len(str)//2):
if str[i] != str[len(str)-i-1]:
return False
return True
# Driver code of function
str = "33568"
if(checkPalindrome(str) == True):
print("Yes, it is a palindrome!")
else:
print("No, it is not a palindrome!")

Output: No, it is not a palindrome!

Time Complexity: O(|str|) As the for loop inside the function isPalindrome is iterating from 0 to mid of the str, in this case, we can say that the iteration is over n/2 digits, and that makes our complexity as O(|str|)

Space Complexity: O(1) As there is no extra space used by the program, Hence the space complexity is constant. Moving ahead to check another approach of the same time and space complexity.

Approach 2: Using the Reverse number

Assuming input is a number here, i.e., it is stored in int Format and not as string.

Run a loop from till the number doesn't get equal to Zero. In every iteration, Take the number %10 to get the Last digit, keep forming the reverse in the iteration, and later divide the number by ten so that number gets shorter. Here the input is not provided in string format.

n=1991991
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("Yes, the number is a palindrome!")
else:
print("No, the number isn't a palindrome!")

Output: Yes, the number is a palindrome!

Time Complexity: O(n) Here n is the number of digits in the provided number.

Space Complexity: O(1) As there is no extra space used by the program, Hence the space complexity is constant. I hope now you understand the logic behind the Palindrome numbers program.

def is_palindrome(n):
"""
Returns True if n is a palindrome number, False otherwise.
"""
# Base case: one-digit numbers are always palindromes
if n // 10 == 0:
return True
# Recursive case: compare first and last digits, then check the remaining digits
first_digit = n % 10
last_digit = n // (10 ** (len(str(n)) - 1))
if first_digit != last_digit:
return False
else:
# Remove the first and last digits from the number and check the remaining digits recursively
return is_palindrome((n % (10 ** (len(str(n)) - 1))) // 10)
# Example usage:
print(is_palindrome(12321)) # True

Output: True

Time Complexity: O(n) Here n is the number of digits in the provided number.

Space Complexity: O(1) The space complexity of the above code is O(log n), where n is the input number.

This is because the recursive function is_palindrome() is called recursively for each pair of digits at the beginning and end of the input number. The depth of the recursion is equal to the number of digits in the input number, which is O(log n) in terms of the number of digits.

You can practice by yourself with the help of online python compiler for better understanding.

A string is a palindrome in Python if it remains the same when reversed. This can be checked by comparing the original string with its reversed version using slicing syntax or the built-in reversed() function.

How do you check the number is palindrome or not?

To check if a number is a palindrome, convert it to a string and compare it with its reverse. In Python, this can be done with str(num) == str(num)[::-1]. If the original number and its reversed version are the same, the number is a palindrome.

Why do we use palindrome in Python?

We use palindromes in Python for a variety of purposes, such as data validation, string manipulation, and solving algorithmic problems. Palindromes help us validate input data, manipulate strings, and solve various problems involving palindromic sequences.

What is the fastest way to find palindrome in Python?

The fastest way of checking palindrome in Python is using indexing. We create a reversed copy of the string and then compare it with the string itself; if they both are the same, then we conclude that the string is, in fact, a palindrome.

How many loops required to check palindrome?

To check if a string is a palindrome, you only need to iterate over half of the characters in the string, which is approximately len(string) // 2 (rounded down) using a loop that compares the characters at opposite ends of the string.

Conclusion

This article thoroughly explored how to identify palindrome numbers in Python. We delved into the definition of palindromes and examined Python's succinct and efficient approach to determining if a given number exhibits this symmetrical property without additional memory resources.