
String questions are everywhere in coding interviews.
And most of them are built on a few simple patterns:
- Two pointers
- Character arrays
- StringBuilder
Master these, and many problems become easy.
1. Reverse a String
The easiest way:
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
Manual Reverse
public static String reverseManual(String str) {
char[] arr = str.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return new String(arr);
}
Core Idea
Use two pointers:
- one from start
- one from end
Swap characters until middle.
2. Check Palindrome
A palindrome reads the same forwards and backwards.
Example:
- madam
-
level
public static boolean isPalindrome(String str) {int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) return false; left++; right--;}
return true;
}
Why Two Pointers Work
Compare:
- first ↔ last
- second ↔ second-last
If all match:
- palindrome confirmed.
3. Remove Duplicate Characters
public static String removeDuplicates(String str) {
Set<Character> seen = new LinkedHashSet<>();
for (char c : str.toCharArray()) {
seen.add(c);
}
StringBuilder sb = new StringBuilder();
for (char c : seen)
sb.append(c);
return sb.toString();
}
Why LinkedHashSet?
Because it:
- removes duplicates
- preserves insertion order
Most string problems involve:
- traversing characters
- comparing from both ends
building new strings efficiently
Strings are immutable
StringBuilder improves efficiency
Two-pointer technique is powerful for strings
For More Learning: https://www.quipoin.com/tutorial/data-structure-with-java/string-manipulation
Top comments (0)