Valid Palindrome Two Pointer in DSA Java - Time & Space Complexity
We want to know how the time needed to check if a string is a palindrome grows as the string gets longer.
Specifically, how many steps does the two-pointer method take as input size increases?
Analyze the time complexity of the following code snippet.
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) return false;
left++;
right--;
}
return true;
}
This code checks if a string is a palindrome by moving two pointers from both ends towards the center, skipping non-alphanumeric characters.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that moves two pointers from the start and end towards the middle.
- How many times: Each character is visited at most once by either pointer, so up to n times total, where n is the string length.
As the string length grows, the number of steps grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The steps increase linearly as the input size increases.
Time Complexity: O(n)
This means the time to check grows in a straight line with the string length.
[X] Wrong: "Because there are nested while loops, the time complexity is O(n²)."
[OK] Correct: Each character is visited only once by either pointer, so the total steps add up to n, not n times n.
Understanding this linear time approach shows you can efficiently process strings with two pointers, a common and useful skill in coding challenges.
"What if we changed the code to check only letters and ignored digits? How would the time complexity change?"
Practice
Solution
Step 1: Understand the two-pointer approach
Two pointers start at the beginning and end of the string and move inward.Step 2: Compare characters at pointers
If characters at both pointers match, move pointers closer; if not, string is not palindrome.Final Answer:
Use two pointers starting from both ends and move towards the center comparing characters -> Option BQuick Check:
Two-pointer technique = Compare ends inward [OK]
- Trying to reverse the string instead of using pointers
- Checking only half the string without comparing both ends
- Ignoring case or non-alphanumeric characters
s?Solution
Step 1: Identify valid pointer initialization
String indices start at 0 and end at length - 1, so right pointer must be s.length() - 1.Step 2: Check each option
int left = 0, right = s.length() - 1; correctly sets left to 0 and right to s.length() - 1; others are off by one or invalid.Final Answer:
int left = 0, right = s.length() - 1; -> Option AQuick Check:
Right pointer = last index = length - 1 [OK]
- Setting right pointer to s.length() causing out-of-bounds
- Starting left pointer at 1 instead of 0
- Using length + 1 causing errors
String s = "A man, a plan, a canal: Panama";
boolean isPalindrome = true;
int left = 0, right = s.length() - 1;
while (left < right) {
char leftChar = Character.toLowerCase(s.charAt(left));
char rightChar = Character.toLowerCase(s.charAt(right));
if (!Character.isLetterOrDigit(leftChar)) {
left++;
} else if (!Character.isLetterOrDigit(rightChar)) {
right--;
} else {
if (leftChar != rightChar) {
isPalindrome = false;
break;
}
left++;
right--;
}
}
System.out.println(isPalindrome);Solution
Step 1: Understand the code logic
The code skips non-alphanumeric characters and compares lowercase letters from both ends moving inward.Step 2: Trace the string "A man, a plan, a canal: Panama"
Ignoring spaces and punctuation, the cleaned string is "amanaplanacanalpanama" which reads the same forward and backward.Final Answer:
true -> Option CQuick Check:
Ignoring non-alphanumeric, palindrome check = true [OK]
- Not skipping non-alphanumeric characters
- Not converting characters to lowercase
- Breaking loop too early without full check
String s = "racecar";
int left = 0, right = s.length() - 1;
boolean isPalindrome = true;
while (left <= right) {
if (s.charAt(left) != s.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
System.out.println(isPalindrome);Solution
Step 1: Analyze loop condition
Using left <= right causes the middle character to be compared with itself unnecessarily, but it does not cause wrong result here.Step 2: Check correctness of condition
The main issue is that the code does not convert characters to lowercase, so it fails for case-insensitive palindrome checks.Final Answer:
The code does not convert characters to lowercase -> Option DQuick Check:
Case sensitivity causes incorrect palindrome detection [OK]
- Using <= causes unnecessary middle char check
- Ignoring case sensitivity
- Not handling non-alphanumeric characters
s = "No lemon, no melon", which modification to the two-pointer palindrome check is necessary to correctly identify it as a palindrome?Solution
Step 1: Understand the string content
The string contains spaces and uppercase letters which should be ignored or normalized for palindrome check.Step 2: Modify two-pointer approach
Convert characters to lowercase and skip non-alphanumeric characters to compare only valid letters.Final Answer:
Convert characters to lowercase and skip non-alphanumeric characters during comparison -> Option AQuick Check:
Normalize case and skip invalid chars for correct palindrome [OK]
- Not ignoring spaces and punctuation
- Not converting uppercase to lowercase
- Assuming direct comparison without cleaning works
Ready to prove it?
Pass the test and this pattern moves unknown
