Longest Palindromic Substring in DSA Python - Time & Space Complexity
We want to understand how the time needed to find the longest palindromic substring changes as the input string gets longer.
Specifically, how does the number of steps grow when checking all possible palindromes?
Analyze the time complexity of the following code snippet.
def longest_palindrome(s: str) -> str:
start, max_len = 0, 1
for i in range(len(s)):
# Check odd length palindrome
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > max_len:
start = l
max_len = r - l + 1
l -= 1
r += 1
# Check even length palindrome
l, r = i, i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > max_len:
start = l
max_len = r - l + 1
l -= 1
r += 1
return s[start:start + max_len]
This code checks all possible centers of palindromes and expands outwards to find the longest palindrome substring.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Expanding around each center to check palindrome substrings.
- How many times: For each character (n times), two expansions happen (odd and even length), each expanding up to n steps in worst case.
As the string length grows, the number of expansions grows roughly with the square of the length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 expansions |
| 100 | About 10,000 expansions |
| 1000 | About 1,000,000 expansions |
Pattern observation: Doubling the input size roughly quadruples the work, showing a square growth pattern.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the input length, so longer strings take much more time.
[X] Wrong: "Since we only check around each character, the time is O(n)."
[OK] Correct: Each center can expand up to n steps, so the total checks add up to about n times n, not just n.
Understanding this time complexity helps you explain why some palindrome solutions are slower and shows your grasp of nested loops and their costs.
"What if we used dynamic programming to store palindrome results? How would the time complexity change?"
Practice
Longest Palindromic Substring problem?Solution
Step 1: Understand the problem statement
The problem asks to find the longest continuous part of the string that reads the same forwards and backwards.Step 2: Differentiate from related problems
Counting palindromic substrings or checking the whole string is different from finding the longest palindromic substring.Final Answer:
Find the longest substring that reads the same forwards and backwards -> Option DQuick Check:
Longest palindromic substring = Find longest palindrome [OK]
- Confusing substring with subsequence
- Counting all palindromes instead of longest
- Checking whole string palindrome only
Solution
Step 1: Understand variable roles
We need to track the start index and maximum length of the palindrome found. Starting with 0 and 1 is common because a single character is a palindrome.Step 2: Check initialization correctness
start, max_len = 0, 1 sets start=0 and max_len=1, which is correct. start, max_len = 1, 0 reverses values incorrectly. Options A, B, and C do not set max_len properly.Final Answer:
start, max_len = 0, 1 -> Option AQuick Check:
Initialize start=0 and max_len=1 for single char palindrome [OK]
- Setting max_len to 0 initially
- Using None instead of integers
- Swapping start and max_len values
def expand_around_center(s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right - left - 1
s = "babad"
length = expand_around_center(s, 1, 1)
print(length)Solution
Step 1: Understand the function behavior
The function expands around the center indices (left and right) while characters match, then returns the length of the palindrome found.Step 2: Trace the expansion for s='babad' at center (1,1)
Center at index 1 ('a'). Expand left=1, right=1: 'a'=='a' true, expand to left=0, right=2: 'b'=='b' true, expand to left=-1 (stop). Length = right - left - 1 = 3 - (-1) - 1 = 3.Final Answer:
3 -> Option CQuick Check:
Expand around center returns palindrome length 3 [OK]
- Not subtracting 1 in length calculation
- Confusing indices after expansion
- Assuming length equals right - left
def longest_palindrome(s):
start, max_len = 0, 1
for i in range(len(s)):
len1 = expand_around_center(s, i, i)
len2 = expand_around_center(s, i, i+1)
length = max(len1, len2)
if length > max_len:
start = i - length // 2
max_len = length
return s[start:start+max_len]Solution
Step 1: Analyze start index update logic
For even length palindromes, start index calculation differs because center is between two characters. Usingi - length // 2works for odd length but not always for even length.Step 2: Identify correct start calculation
For even length, start should bei - (length // 2) + 1to correctly locate the palindrome start.Final Answer:
The start index calculation is incorrect for even length palindromes -> Option BQuick Check:
Start index must adjust differently for even palindromes [OK]
- Using same start formula for odd and even palindromes
- Ignoring even length palindrome cases
- Not updating max_len properly
"forgeeksskeegfor", which substring is the longest palindromic substring?Solution
Step 1: Identify palindromic substrings in the string
Check substrings that read the same forwards and backwards. "geeksskeeg" is a palindrome of length 10 inside the string.Step 2: Compare lengths of candidate substrings
"forgeeksskeegfor" is not a palindrome as a whole. "geeksskeegf" and "eksskeeg" are shorter palindromes.Final Answer:
"geeksskeeg" -> Option AQuick Check:
Longest palindrome in "forgeeksskeegfor" is "geeksskeeg" [OK]
- Assuming whole string is palindrome
- Choosing substring with extra characters
- Ignoring palindrome length
Ready to prove it?
Pass the test and this pattern moves unknown
