Longest Palindromic Substring in DSA Rust - Time & Space Complexity
We want to understand how the time needed to find the longest palindromic substring changes as the input string gets longer.
How does the number of steps grow when the string size increases?
Analyze the time complexity of the following code snippet.
fn longest_palindrome(s: &str) -> String {
let chars: Vec = s.chars().collect();
let n = chars.len();
let mut start = 0;
let mut max_len = 1;
for i in 0..n {
// Check odd length palindrome
let (l1, r1) = expand_around_center(&chars, i, i);
// Check even length palindrome
let (l2, r2) = expand_around_center(&chars, i, i + 1);
let len1 = r1 - l1 + 1;
let len2 = r2 - l2 + 1;
if len1 > max_len {
start = l1;
max_len = len1;
}
if len2 > max_len {
start = l2;
max_len = len2;
}
}
chars[start..start + max_len].iter().collect()
}
fn expand_around_center(chars: &[char], mut left: usize, mut right: usize) -> (usize, usize) {
while left <= right && right < chars.len() && chars[left] == chars[right] {
if left == 0 { break; }
left -= 1;
right += 1;
}
(left + 1, right - 1)
}
This code finds the longest palindrome by expanding around each character and its neighbor to check odd and even length palindromes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs once for each character in the string.
- How many times: For each character, the expand_around_center function expands outwards checking characters until mismatch or ends.
As the string length grows, the outer loop runs more times, and each expansion can check many characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 checks |
| 100 | About 10,000 checks |
| 1000 | About 1,000,000 checks |
Pattern observation: The number of checks grows roughly with the square of the input size.
Time Complexity: O(n²)
This means if the input string doubles in length, the time to find the longest palindrome roughly quadruples.
[X] Wrong: "Since we only expand around centers, the time is O(n)."
[OK] Correct: Each expansion can check many characters, so the total work adds 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 string processing.
"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 palindrome definition
A palindrome reads the same forwards and backwards, like 'madam' or 'racecar'.Step 2: Identify problem goal
The problem asks to find the longest continuous part of a string that is a palindrome.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
- Looking for unique characters instead of palindrome
- Ignoring continuous substring requirement
s?Solution
Step 1: Understand Rust string types
Rust uses&strfor string slices andStringfor owned strings.Step 2: Choose correct function signature
Function should take a string slice&strand return a string slice&strfor substring references.Final Answer:
fn longest_palindrome(s: &str) -> &str { } -> Option AQuick Check:
Use &str for slices in function signature [OK]
- Using owned String when slice is better
- Returning owned String unnecessarily
- Incorrect parameter types like str without &
fn main() {
let s = "babad";
let result = longest_palindrome(s);
println!("{}", result);
}
fn longest_palindrome(s: &str) -> &str {
let chars: Vec<char> = s.chars().collect();
let mut start = 0;
let mut max_len = 1;
for i in 0..chars.len() {
let mut left = i as i32;
let mut right = i as i32;
while left >= 0 && right < chars.len() as i32 && chars[left as usize] == chars[right as usize] {
if (right - left + 1) > max_len {
start = left as usize;
max_len = (right - left + 1) as usize;
}
left -= 1;
right += 1;
}
}
&s[start..start + max_len]
}Solution
Step 1: Understand the code logic
The code expands around each character to find odd-length palindromes and tracks the longest.Step 2: Trace the input "babad"
At index 0: palindrome "b" (length 1), index 1: "bab" (length 3), index 2: "aba" (length 3). The first longest palindrome found is "bab".Final Answer:
bab -> Option CQuick Check:
Longest palindrome substring = bab [OK]
- Assuming palindrome must be unique
- Returning entire string instead of substring
- Confusing substring indices
fn longest_palindrome(s: &str) -> &str {
let chars: Vec<char> = s.chars().collect();
let mut start = 0;
let mut max_len = 1;
for i in 0..chars.len() {
let mut left = i as i32;
let mut right = i as i32 + 1;
while left >= 0 && right < chars.len() as i32 && chars[left as usize] == chars[right as usize] {
if (right - left + 1) > max_len {
start = left as usize;
max_len = (right - left + 1) as usize;
}
left -= 1;
right += 1;
}
}
&s[start..start + max_len]
}Solution
Step 1: Analyze pointer initialization
Right pointer starts at i + 1, which only checks even-length palindromes, missing odd-length ones.Step 2: Correct pointer for odd-length palindromes
To check odd-length palindromes, right pointer should start at i, same as left pointer.Final Answer:
The initial right pointer should be equal to i, not i + 1 -> Option BQuick Check:
Right pointer = i for odd-length palindrome check [OK]
- Only checking even-length palindromes
- Wrong loop range causing index errors
- Returning wrong type causing borrow issues
"forgeeksskeegfor", which approach correctly finds the longest palindromic substring and what is that substring?Solution
Step 1: Understand approaches to find longest palindrome
Expand around center and dynamic programming are common methods; brute force is slow but correct.Step 2: Identify longest palindrome in given string
"forgeeksskeegfor" contains "geeksskeeg" as the longest palindrome substring, not the entire string.Step 3: Match approach and answer
Expand around center method efficiently finds "geeksskeeg"; dynamic programming would too but not the full string.Final Answer:
Expand around center method; longest palindrome is "geeksskeeg" -> Option AQuick Check:
Longest palindrome = geeksskeeg by center expansion [OK]
- Assuming entire string is palindrome
- Using character counts instead of substring checks
- Confusing brute force with efficient methods
Ready to prove it?
Pass the test and this pattern moves unknown
