12 classic String-based Java interview questions with simple explanations and code.

 

1️⃣ Check if a String is a Palindrome

Problem
Given a string, check if it reads the same forward and backward. Example: "madam" → palindrome, "hello" → not palindrome.

Idea
Use two pointers: one at the beginning, one at the end, and compare characters.

public class PalindromeString { public static void main(String[] args) { String str = "Madam"; if (isPalindrome(str)) { System.out.println(str + " is a palindrome"); } else { System.out.println(str + " is not a palindrome"); } } public static boolean isPalindrome(String s) { if (s == null) return false; s = s.toLowerCase(); int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; } }

2️⃣ Reverse a String (Without Using Library Reverse)

Problem
Reverse a given string: input "hello" → output "olleh".

Idea
Convert to char array and swap from both ends.

public class ReverseString { public static void main(String[] args) { String str = "hello"; System.out.println("Original: " + str); System.out.println("Reversed: " + reverse(str)); } public static String reverse(String s) { if (s == null) return null; char[] chars = s.toCharArray(); int left = 0, right = chars.length - 1; while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } return new String(chars); } }

3️⃣ Reverse Words in a Sentence

Problem
Given "Java is awesome", output "awesome is Java" (reverse word order, not characters inside each word).

Idea
Split on spaces, reverse the array of words, then join back.

public class ReverseWordsInSentence { public static void main(String[] args) { String sentence = "Java is awesome"; System.out.println(reverseWords(sentence)); } public static String reverseWords(String s) { if (s == null || s.trim().isEmpty()) return s; String[] words = s.trim().split("\\s+"); int left = 0, right = words.length - 1; while (left < right) { String tmp = words[left]; words[left] = words[right]; words[right] = tmp; left++; right--; } return String.join(" ", words); } }

4️⃣ Check if Two Strings are Anagrams

Problem
Two strings are anagrams if they contain the same characters with the same frequency (order doesn’t matter).
Example: "listen" and "silent" → anagrams.

Idea
Either sort both strings and compare, or count character frequencies. Here we sort.

import java.util.Arrays; public class AnagramCheck { public static void main(String[] args) { String s1 = "listen"; String s2 = "silent"; if (areAnagrams(s1, s2)) { System.out.println(s1 + " and " + s2 + " are anagrams"); } else { System.out.println(s1 + " and " + s2 + " are not anagrams"); } } public static boolean areAnagrams(String a, String b) { if (a == null || b == null) return false; a = a.replaceAll("\\s+", "").toLowerCase(); b = b.replaceAll("\\s+", "").toLowerCase(); if (a.length() != b.length()) return false; char[] ca = a.toCharArray(); char[] cb = b.toCharArray(); Arrays.sort(ca); Arrays.sort(cb); return Arrays.equals(ca, cb); } }

5️⃣ Find the First Non-Repeating Character

Problem
Given a string, find the first character that does not repeat. Example: "swiss" → first non-repeating is 'w'.

Idea
First pass: count frequencies. Second pass: return first char with count 1.

import java.util.LinkedHashMap; import java.util.Map; public class FirstNonRepeatingChar { public static void main(String[] args) { String str = "swiss"; Character result = firstNonRepeating(str); System.out.println("First non-repeating character: " + result); } public static Character firstNonRepeating(String s) { if (s == null) return null; Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } for (Map.Entry<Character, Integer> e : freq.entrySet()) { if (e.getValue() == 1) { return e.getKey(); } } return null; // no unique char } }

6️⃣ Count Vowels and Consonants

Problem
Given a string, count how many vowels and consonants are present (alphabet letters only).

Idea
Loop through characters, check if alphabet, then check if it’s in 'aeiou'.

public class VowelConsonantCount { public static void main(String[] args) { String str = "Hello Java 123"; int vowels = 0; int consonants = 0; String lower = str.toLowerCase(); for (int i = 0; i < lower.length(); i++) { char ch = lower.charAt(i); if (ch >= 'a' && ch <= 'z') { if ("aeiou".indexOf(ch) != -1) { vowels++; } else { consonants++; } } } System.out.println("Vowels: " + vowels); System.out.println("Consonants: " + consonants); } }

7️⃣ Remove All Duplicates Characters (Keep First Occurrence)

Problem
Input: "programming" → Output: "progamin" (remove repeated chars, keep the first time they appear).

Idea
Use a boolean array or Set to track already seen characters.

import java.util.HashSet; import java.util.Set; public class RemoveDuplicateChars { public static void main(String[] args) { String str = "programming"; System.out.println(removeDuplicates(str)); } public static String removeDuplicates(String s) { if (s == null) return null; Set<Character> seen = new HashSet<>(); StringBuilder result = new StringBuilder(); for (char c : s.toCharArray()) { if (!seen.contains(c)) { seen.add(c); result.append(c); } } return result.toString(); } }

8️⃣ Check if One String is a Rotation of Another

Problem
Check if s2 is a rotation of s1.
Example: s1 = "waterbottle", s2 = "erbottlewat" → rotation.

Idea
If lengths are same, check if s2 is a substring of s1 + s1.

public class StringRotationCheck { public static void main(String[] args) { String s1 = "waterbottle"; String s2 = "erbottlewat"; if (isRotation(s1, s2)) { System.out.println(s2 + " is a rotation of " + s1); } else { System.out.println(s2 + " is NOT a rotation of " + s1); } } public static boolean isRotation(String s1, String s2) { if (s1 == null || s2 == null) return false; if (s1.length() != s2.length()) return false; if (s1.isEmpty()) return true; // both empty String doubled = s1 + s1; return doubled.contains(s2); } }

9️⃣ Longest Substring Without Repeating Characters

Problem
Given a string, find the length of the longest substring without repeating characters.
Example: "abcabcbb" → longest is "abc" → length 3.

Idea
Use sliding window with a map that stores last index of each character.

import java.util.HashMap; import java.util.Map; public class LongestUniqueSubstring { public static void main(String[] args) { String s = "abcabcbb"; System.out.println("Length: " + lengthOfLongestSubstring(s)); } public static int lengthOfLongestSubstring(String s) { if (s == null) return 0; Map<Character, Integer> lastIndex = new HashMap<>(); int start = 0; int maxLen = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (lastIndex.containsKey(c) && lastIndex.get(c) >= start) { // move start to one position after the last occurrence start = lastIndex.get(c) + 1; } lastIndex.put(c, i); maxLen = Math.max(maxLen, i - start + 1); } return maxLen; } }

🔟 Character Frequency Count

Problem
Print how many times each character appears in a string.
Example: "banana"b:1, a:3, n:2.

Idea
Use a Map<Character, Integer> and count all characters.

import java.util.LinkedHashMap; import java.util.Map; public class CharacterFrequency { public static void main(String[] args) { String str = "banana"; printCharFrequency(str); } public static void printCharFrequency(String s) { if (s == null) return; Map<Character, Integer> freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } for (Map.Entry<Character, Integer> e : freq.entrySet()) { System.out.println(e.getKey() + " -> " + e.getValue()); } } }

1️⃣1️⃣ Count Occurrences of a Substring

Problem
Given a string text and a string pattern, count how many times pattern appears in text (non-overlapping).

Example: text = "aaaa", pattern = "aa" → result = 2.

Idea
Scan using indexOf in a loop and move index by pattern length.

public class SubstringOccurrences { public static void main(String[] args) { String text = "aaaa"; String pattern = "aa"; System.out.println("Count: " + countOccurrences(text, pattern)); } public static int countOccurrences(String text, String pattern) { if (text == null || pattern == null || pattern.isEmpty()) return 0; int count = 0; int index = 0; while ((index = text.indexOf(pattern, index)) != -1) { count++; index += pattern.length(); // move past this occurrence } return count; } }

1️⃣2️⃣ Simple String Compression (Run-Length Encoding Style)

Problem
Compress a string by replacing consecutive repeating characters with the character followed by the count.
Example: "aaabbc""a3b2c1".
If compressed string is not smaller, return original.

Idea
Loop through string and count runs.

public class StringCompression { public static void main(String[] args) { String s = "aaabbc"; System.out.println("Original: " + s); System.out.println("Compressed: " + compress(s)); } public static String compress(String s) { if (s == null || s.isEmpty()) return s; StringBuilder sb = new StringBuilder(); int count = 1; for (int i = 1; i <= s.length(); i++) { if (i < s.length() && s.charAt(i) == s.charAt(i - 1)) { count++; } else { sb.append(s.charAt(i - 1)).append(count); count = 1; } } String compressed = sb.toString(); return compressed.length() < s.length() ? compressed : s; } }


No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts