Palindrome Detection in DSA Java - Time & Space Complexity
We want to know how the time to check if a word or phrase is a palindrome changes as the input gets longer.
How does the number of steps grow when the input size grows?
Analyze the time complexity of the following code snippet.
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
This code checks if a string reads the same forwards and backwards by comparing characters from both ends moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing characters at positions from start and end of the string.
- How many times: Up to half the length of the string (n/2 times).
As the string gets longer, the number of character comparisons grows roughly half as fast.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 comparisons |
| 100 | 50 comparisons |
| 1000 | 500 comparisons |
Pattern observation: The number of steps grows linearly with input size, but only half as many comparisons are needed.
Time Complexity: O(n)
This means the time to check a palindrome grows in a straight line as the input gets longer.
[X] Wrong: "Checking a palindrome takes time proportional to the square of the string length because of nested checks."
[OK] Correct: The code only compares pairs of characters once, moving inward, so it does not repeat work inside nested loops.
Understanding this linear time check helps you explain efficient string processing, a common skill interviewers look for.
"What if we ignored case and spaces when checking the palindrome? How would the time complexity change?"
Practice
Solution
Step 1: Understand palindrome definition
A palindrome is a word or phrase that reads the same forwards and backwards.Step 2: Compare options with definition
Only "a string that reads the same forwards and backwards" matches this definition exactly.Final Answer:
A string that reads the same forwards and backwards -> Option DQuick Check:
Palindrome = Same forwards and backwards [OK]
- Confusing palindrome with unique characters
- Thinking palindrome means sorted string
- Assuming palindrome only has vowels
s is a palindrome?Solution
Step 1: Check loop and character comparison logic
for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } return true;compares characters from start and end moving towards center correctly.Step 2: Identify errors in other options
Adjacent chars comparison is incorrect; equality check instead of inequality is wrong; off-by-one index error.Final Answer:
for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) return false; } return true;-> Option AQuick Check:
Compare chars from ends moving inward [OK]
- Using wrong indices causing index out of bounds
- Comparing adjacent characters instead of mirrored ones
- Incorrect loop range causing incomplete checks
String s = "racecar";
boolean isPalindrome = true;
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
System.out.println(isPalindrome);Solution
Step 1: Analyze the string and loop logic
String "racecar" is a palindrome. Loop compares mirrored characters correctly.Step 2: Check if any mismatch occurs
No mismatch found, so isPalindrome remains true and prints true.Final Answer:
true -> Option CQuick Check:
"racecar" reads same forwards and backwards [OK]
- Assuming palindrome check fails for odd length strings
- Confusing loop range causing missed checks
- Misreading output as string instead of boolean
str is a palindrome:boolean checkPalindrome(String str) {
for (int i = 0; i <= str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - i)) {
return false;
}
}
return true;
}Solution
Step 1: Check index usage in charAt
Indexstr.length() - iis off by one; last valid index isstr.length() - 1.Step 2: Identify error cause
Accessingstr.charAt(str.length() - i)when i=0 causes index out of bounds.Final Answer:
Indexstr.length() - icauses out of bounds error -> Option BQuick Check:
String indices start at 0, max index = length-1 [OK]
- Using <= in loop causing extra iteration
- Confusing comparison operators
- Wrong return type for boolean method
["level", "world", "deed", "java", "noon"], which Java code snippet correctly returns a new list containing only the palindromes?Solution
Step 1: Understand palindrome filtering logic
List<String> palindromes = list.stream().filter(s -> new StringBuilder(s).reverse().toString().equals(s)).collect(Collectors.toList());reverses string and compares to original, correctly identifying palindromes.Step 2: Analyze other options
Checking only first and last char equality; filtering even length strings; checking uppercase equality; all incorrect.Final Answer:
List<String> palindromes = list.stream().filter(s -> new StringBuilder(s).reverse().toString().equals(s)).collect(Collectors.toList());-> Option AQuick Check:
Reverse string equals original means palindrome [OK]
- Checking only first and last characters
- Filtering by string length instead of palindrome
- Confusing uppercase check with palindrome
Ready to prove it?
Pass the test and this pattern moves unknown
