LeetCode, 𝐃𝐚𝐲-9/365-DSA-Coding 𝐉𝐨𝐮𝐫𝐧𝐞𝐲…Google Prep…

Aaqib Ali
2 min readJan 8, 2025

--

Today I Learned: Problem — Check If a 9. Palindrome Number

Today, I solved the problem of checking whether a given integer is a palindrome. A number is considered a palindrome if it reads the same backward as forward, such as 121 or -121 (ignoring the negative sign). However, in this particular problem, negative numbers are automatically not palindromes.

My Approach to Solve This Problem:

I used a simple two-pointer-like method:

  1. Convert the number to a string: This allows us to easily access individual digits as characters.
  2. Determine the length of the string: Using len(), we know how many characters are in the string.
  3. Compare corresponding characters from both ends:
  • Loop through the string up to its middle.
  • Compare the character at the current index with the character from the end (s[s_len - index - 1]).
  • If any pair of characters doesn’t match, the number is not a palindrome.
  1. Return true or false based on the comparisons.

This approach is easy to understand and implement but works efficiently for small to moderate-sized integers.

Other Possible Approaches:

  1. Reversing the Integer:
  • Reverse the integer and compare it with the original.
  • If the reversed integer equals the original, it’s a palindrome.

2. Mathematical Approach (Without String Conversion):

  • Reverse only the second half of the integer (efficient for large numbers).
  • Use arithmetic to extract digits (e.g., % and //).
  • Compare the first half with the reversed second half.
  • Example:
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
s_len = len(s)

for index, char in enumerate(s):
if index > s_len / 2:
return True

if char != s[s_len - index - 1]:
return False

return True
  1. Recursive Approach:
  • Use recursion to compare digits at the start and end, moving inward.
  • This approach is less common but showcases problem-solving creativity.

Learnings:

  1. Two-pointer technique is versatile and widely applicable to problems involving symmetry.
  2. Efficient use of string manipulation and index calculation can simplify logic.
  3. Mathematical solutions often save space and avoid unnecessary type conversions.
  4. Always explore edge cases (e.g., negative numbers, single-digit numbers, numbers ending in zero).

Usage:

The palindrome check is a fundamental concept with applications in:

  1. String manipulations (e.g., checking palindromic substrings in strings).
  2. Data validation (e.g., ensuring certain patterns or formats are maintained).
  3. Algorithmic challenges where symmetry plays a role (e.g., DNA sequences).

Thank you for reading this! If you want to discuss your approach, let’s connect and collaborate. Special thanks to iCodeGuru for their constant support and guidance. Remember: Keep learning, sharing, smiling, living, loving, and coding!

--

--

No responses yet