Longest Palindromic Substring in DSA Java - 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.
public String longestPalindrome(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
String res = "";
for (int len = 0; len < n; len++) {
for (int start = 0; start + len < n; start++) {
int end = start + len;
dp[start][end] = (s.charAt(start) == s.charAt(end))
&& (len < 2 || dp[start + 1][end - 1]);
if (dp[start][end] && len + 1 > res.length()) {
res = s.substring(start, end + 1);
}
}
}
return res;
}
This code finds the longest palindromic substring using dynamic programming by checking all possible substrings.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops checking all substrings of the input string.
- How many times: Outer loop runs n times, inner loop runs up to n times for each outer loop, so roughly n x n = n² times.
As the string length grows, the number of substring checks grows roughly with the square of the length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 checks |
| 100 | About 10,000 checks |
| 1000 | About 1,000,000 checks |
Pattern observation: Doubling the input size roughly quadruples the work because of the nested loops.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the input string length.
[X] Wrong: "Since we only check pairs of characters, the time is O(n)."
[OK] Correct: We check all substrings, not just pairs, so the number of checks grows much faster than the string length.
Understanding this time complexity helps you explain how your solution scales and shows you can analyze nested loops clearly.
"What if we used a center expansion method instead of dynamic programming? How would the time complexity change?"
Practice
Longest Palindromic Substring problem?Solution
Step 1: Understand the problem definition
The problem asks to find a substring that is a palindrome, meaning it reads the same forwards and backwards.Step 2: Identify the goal
Among all palindromic substrings, we want the one with the maximum length.Final Answer:
Find the longest substring that reads the same forwards and backwards -> Option CQuick Check:
Longest Palindromic Substring = Find palindrome substring [OK]
- Confusing palindrome with unique characters
- Looking for longest substring without repeats
- Thinking about character order increasing
s?Solution
Step 1: Analyze the return type
The function should return the longest palindromic substring, which is a String.Step 2: Check parameter type
The input is a string, so the parameter should be of type String.Final Answer:
public String longestPalindrome(String s) -> Option AQuick Check:
Return type String and parameter String = public String longestPalindrome(String s) [OK]
- Using void return type when output is needed
- Using int parameter instead of String
- Returning int instead of String
public class Test {
public static String longestPalindrome(String s) {
int start = 0, maxLen = 1;
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
String sub = s.substring(i, j + 1);
if (isPalindrome(sub) && sub.length() > maxLen) {
start = i;
maxLen = sub.length();
}
}
}
return s.substring(start, start + maxLen);
}
private static boolean isPalindrome(String str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left++) != str.charAt(right--)) return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(longestPalindrome("babad"));
}
}Solution
Step 1: Understand the code logic
The code checks all substrings and updates the longest palindrome found.Step 2: Trace the input "babad"
Palindromic substrings include "bab" and "aba" both length 3. The code picks the first found longest palindrome, which is "bab".Final Answer:
"bab" -> Option DQuick Check:
First longest palindrome found = "bab" [OK]
- Assuming "aba" is returned instead of "bab"
- Thinking entire string is palindrome
- Ignoring substring length comparison
public String longestPalindrome(String s) {
int maxLen = 0, start = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
String sub = s.substring(i, j);
if (isPalindrome(sub) && sub.length() > maxLen) {
maxLen = sub.length();
start = i;
}
}
}
return s.substring(start, start + maxLen);
}Solution
Step 1: Check substring usage
Java substring method excludes the end index, so substring(i, j) misses character at j.Step 2: Correct substring end index
It should be substring(i, j + 1) to include character at position j.Final Answer:
The substring end index should be j + 1, not j -> Option BQuick Check:
substring(i, j + 1) includes full substring [OK]
- Using substring(i, j) which excludes last char
- Not updating maxLen correctly
- Ignoring substring indexing rules
"forgeeksskeegfor", which approach will efficiently find the longest palindromic substring and what is the substring?Solution
Step 1: Identify efficient methods
Dynamic programming and expand around center are efficient for this problem; brute force is slow.Step 2: Check longest palindrome in given string
"geeksskeeg" is the longest palindromic substring inside "forgeeksskeegfor".Step 3: Match approach and answer
Dynamic programming with memoization is a common efficient approach returning "geeksskeeg".Final Answer:
Dynamic programming with memoization; longest palindrome is "geeksskeeg" -> Option AQuick Check:
DP approach finds "geeksskeeg" efficiently [OK]
- Assuming entire string is palindrome
- Using brute force for large strings
- Sorting characters loses substring order
Ready to prove it?
Pass the test and this pattern moves unknown
