Python handles text as unicode. As such, what character is alphabetic and what is not depends on the character unicode category, enconpassing all characters defined on the unicode version compiled along with Python. That is tens of hundreds of characters, and hundreds of scripts, etc... each with their own alphabetic ranges. Although it all boils down to numeric ranges of the codepoints that could be compared using other algorithms, it is almost certain all characters are iterated, and the character unicode category is checked. If you want the complexity, it is then O(n) .

(Actually, it would have been O(n) on your example as well, since all characters have to be checked. For a single character, Python uses a dict, or dict-like table to get from the character to its category infomation, and that is O(1))

Answer from jsbueno on Stack Overflow
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 69058844 โ€บ time-complexity-of-loop-statement-using-isalnum-python
Time complexity of loop statement using isalnum() (Python) - Stack Overflow
I believe the time complexity for the isalnum function is o(n) since it will go through each character to check if its an alphanumeric and we iterate over n words.
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ str โ€บ isalnum.html
isalnum โ€” Python Reference (The Right Way) 0.1 documentation
>>> ''.isalnum() False >>> 'abc123'.isalnum() True >>> 'abc'.isalnum() True >>> '123'.isalnum() True >>> 'Abc'.isalnum() True >>> '!@#'.isalnum() False >>> ' '.isalnum() False >>> 'ABC'.isalnum() True
Discussions

string - Python: Time complexity of .isAlpha - Stack Overflow
So I can't find the official documentation on how the isalpha method was written (of the string module), but I imagine the algorithm used would be: 1). Convert char in question to int.2). Compare i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
strings - Improving time complexity of finding the longest palindrome in Python - Code Review Stack Exchange
The Longest Palindromic Substring challenge from InterviewBit: Given a string S, find the longest palindromic substring in S. where a "substring" must be contiguous, and in case of ties... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
June 1, 2016
What time complexity should one assume when using built in sort functions?
aromatic ripe concerned mountainous racial gray chop coherent wild lavish This post was mass deleted and anonymized with Redact More on reddit.com
๐ŸŒ r/leetcode
11
15
April 15, 2024
How to differentiate between numeric strings and alphabetical strings?
There are string methods str.isnumeric, str.isdigit, str.isalpha, str.isalnum, etc. For example, print("9".isdigit()) print("a".isalpha()) You can check out Python's string methods in the documentation . More on reddit.com
๐ŸŒ r/learnpython
16
12
June 27, 2021
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ valid-palindrome โ€บ solutions โ€บ 770898 โ€บ python-on-without-using-isalnum-function-easy-explanation
Python O(n) without using isalnum() function
Can you solve this real interview question? Valid Palindrome - A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
๐ŸŒ
LeetCode Meditations
rivea0.github.io โ€บ blog โ€บ leetcode-meditations-valid-palindrome
LeetCode Meditations: Valid Palindrome
March 2, 2024 - This time we get the alphanumeric characters with a handy method named str.isalnum() and using list comprehensions. The time complexity for this version is ยท O ยท ( n ยท ) O(n)O(n), because we iterate through the array once for each loop. The space complexity is ยท
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ string-isalnum-and-isalpha-methods-with-examples.aspx
Python String isalnum() and isalpha() Methods
December 15, 2024 - # str1 with alphabets and numbers str1 = "Helloworld123" # str2 with only alphabets str2 = "Helloworld" # str3 with numbers only str3 = "12345" # str4 with alphanumeric characters and space str4 = "Amit Shukla 21" # check whether string contains # only alphanumeric characters or not print(str1.isalnum()) print(str2.isalnum()) print(str3.isalnum()) print(str4.isalnum()) ... Python String isdecimal() Vs.
Find elsewhere
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ stdtypes.html
Built-in Types โ€” Python 3.14.4 documentation
February 25, 2026 - Numeric literals containing a decimal point or an exponent sign yield floating-point numbers. Appending 'j' or 'J' to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-test-if-the-string-only-numbers-and-alphabets
Python Program to test if the String only Numbers and Alphabets
August 10, 2023 - The function is designed to iterate through each character of the string and use the isalnum() method to check if it is alphanumeric. This approach has a time complexity of O(n), where n is the length of the string.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ isalnum
Python String isalnum() (With Examples)
Become a certified Python programmer. Try Programiz PRO! ... The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers).
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ string_isalnum.htm
Python String isalnum() Method
The python string isalnum() method is used to check whether the string consists of alphanumeric characters. This method returns true if all the characters in the input string are alphanumeric and there is at least one character.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Understanding the isalpha Method: Time Complexity in Python - YouTube
Dive into the `isalpha` method in Python, exploring how it determines if characters are alphabetic and its time complexity. Find out why it operates in O(n) ...
Published ย  April 16, 2025
Views ย  0
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ remove-all-alphanumeric-elements-from-the-list-python
Remove all Alphanumeric Elements from the List - Python - GeeksforGeeks
July 23, 2025 - Python3 ยท l1 = ['A+B', '()', '50', 'xyz', '-', '/', '_', 'pq95', '65B'] l2 = list() for word in l1: if not word.isalnum(): l2.append(word) print(l2) Output: ['A+B', '()', '-', '/', '_'] Time Complexity: O(N) Auxiliary Space: O(N) isalpha() is a Python string method that returns True if all characters are alphabets.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-string-isalnum
Python String isalnum() | DigitalOcean
August 3, 2022 - import unicodedata count = 0 for codepoint in range(2 ** 16): ch = chr(codepoint) if ch.isalnum(): print(u'{:04x}: {} ({})'.format(codepoint, ch, unicodedata.name(ch, 'UNNAMED'))) count = count + 1 print(f'Total Number of Alphanumeric Unicode Characters = {count}')
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_isalnum.asp
Python String isalnum() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
๐ŸŒ
HackerRank
hackerrank.com โ€บ challenges โ€บ string-validators โ€บ forum
String Validators Discussions | Python | HackerRank
4 weeks ago - #O(n) Approach if __name__ == '__main__': s = input() res = [False]*5 for i in s: res[0] = res[0] or i.isalnum() res[1] = res[1] or i.isalpha() res[2] = res[2] or i.isdigit() res[3] = res[3] or i.islower() res[4] = res[4] or i.isupper() for r in res: print(r)
๐ŸŒ
Javatpoint
javatpoint.com โ€บ python-string-isalnum-method
Python String | isalnum() method with Examples - Javatpoint
Python Function Programs ยท capitalize() casefold() center(width ,fillchar) count(string,begin,end) encode() endswith(suffix ,begin=0,end=len(string)) expandtabs(tabsize = 8) find(substring ,beginIndex, endIndex) format(value) index(subsring, beginIndex, endIndex) isalnum() isalpha() isdecimal() isdigit() isidentifier() islower() isnumeric() isprintable() isupper() isspace() istitle() isupper() join(seq) ljust(width[,fillchar]) lower() lstrip() partition() replace(old,new[,count]) rfind(str,beg=0,end=len(str)) rindex(str,beg=0,end=len(str)) rjust(width,[,fillchar]) rstrip() rsplit(sep=None, ma
Top answer
1 of 1
2

[EDIT] I believe the time-out occurs if you are not fast enough typing your code in the website where this challenge is posted. I believe it is not about optimizing code to run faster, but how quickly you can come up with working code. The following is still true in regards to Code Review:

I might not have all improvements, but here are some I would do

from re import sub

you could rewrite this function:

def clean_string(self, string):
    return sub(r'[^a-zA-Z0-9]', '', string) 

and rewrite this function:

def is_palindrome(self, string):
    return string[::-1]==string

Then the first if statement in def longestPalindrome(self, A) would change too:

def longestPalindrome(self, A):
    if self.is_palindrome(A):
        return A

No need for this:

    if len(A)==1:
        return A

You can replace the while loops with for loops, something like this:

def longestPalindrome(self, A):
    if self.is_palindrome(A):
        return A
    cleaned = self.clean_string(A)
    for l in range(len(cleaned)-1,0,-1):  ## l = lenght to check high to low
        for i in range(0, len(cleaned)-l+1):  ## i is position in A to check
            if self.is_palindrome(A[i:l+i]):  
                return A[i:l+i]
    return None

Those changes would be faster then your original code, but I did not do any scientific tests, so the obligatory: "YMMV"

[EDIT]

In fact you can shorten the code further:

from re import sub


class Solution:

    def longest_palindrome(self, a):
        if a[::-1] == a:
            return a
        a = sub(r'[^a-zA-Z0-9]', '', a)
        for l in range(len(a)-1, 0, -1):
            for i in range(0, len(a)-l+1):
                if a[i:l+i][::-1] == a[i:l+i]:
                    return a[i:l+i]
        return None

s = Solution()
print(s.longest_palindrome("abbcccaaadaaakl"))

and you really don't need a class here:

from re import sub


def lp(a):
    if a[::-1] == a:
        return a
    a = sub(r'[^a-zA-Z0-9]', '', a)
    for l in range(len(a)-1, 0, -1):
        for i in range(0, len(a)-l+1):
            if a[i:l+i][::-1] == a[i:l+i]:
                return a[i:l+i]
    return None

print(lp("abbcccaaadaaakl"))
๐ŸŒ
Medium
medium.com โ€บ @tanvijain17 โ€บ 1-valid-palindrome-solution-for-leetcode-125-easy-in-python-26b67a79c570
1. Valid Palindrome โ€” Solution for Leetcode 125 (EASY) in Python | by Tanvi Jain | Medium
December 11, 2023 - Time complexity: O(n) where n is the length of the input string. The function uses a two-pointer approach, and in each iteration, it either moves the pointers inward or returns False.