Many important techniques, such as Two Pointers, Sliding Window, Hashing, and Pattern Matching, are applied to string problems. In this article, we will explore ten popular string interview questions along with Java solutions, outputs, explanations, and time complexity analysis.
Table of Contents
Reverse a String
Given a string, reverse all of its characters.Example:
Input: Java
Output: avaJ
// Java program to reverse a string
public class ReverseString
{
public static void main(String[] args)
{
String str = "Java";
String reversed = "";
for(int i = str.length() - 1; i = 0; i--)
{
reversed += str.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
Output:
Explanation:Reversed String: avaJ
The loop starts from the last character and appends each character to a new string until the original string is completely reversed.
Time Complexity: O(n)
Check Whether a String is a Palindrome
Check whether a string reads the same forward and backward.Example:
Input: madam
Output: Palindrome
// Java program to check whether a string
// is palindrome or not
public class PalindromeString
{
public static void main(String[] args)
{
String str = "madam";
String reversed = "";
for(int i = str.length() - 1; i = 0; i--)
{
reversed += str.charAt(i);
}
if(str.equals(reversed))
{
System.out.println("Palindrome");
}
else
{
System.out.println("Not Palindrome");
}
}
}
Output:
Explanation:Palindrome
The string is reversed and compared with the original string. If both are equal, the string is a palindrome.
Time Complexity: O(n)
Check Whether Two Strings are Anagrams
Check whether two strings contain the same characters in a different order.Example:
Input: listen, silent
Output: Anagram
// Java program to check whether two strings
// are anagrams
import java.util.Arrays;
public class AnagramCheck
{
public static void main(String[] args)
{
String str1 = "listen";
String str2 = "silent";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
if(Arrays.equals(arr1, arr2))
{
System.out.println("Anagram");
}
else
{
System.out.println("Not Anagram");
}
}
}
Output:
Explanation:Anagram
Both strings are converted into character arrays and sorted. If the sorted arrays are identical, the strings are anagrams.
Time Complexity: O(n log n)
Count Character Frequency
Count the number of times each character appears in a string.Example:
Input: programming
Output:
p = 1
r = 2
g = 2
…
// Java program to count character frequency
import java.util.HashMap;
public class CharacterFrequency
{
public static void main(String[] args)
{
String str = "programming";
HashMapCharacter, Integer map = new HashMap();
for(char ch : str.toCharArray())
{
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
System.out.println(map);
}
}
Output:
Explanation:{p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}
A HashMap stores each character as a key and its frequency as a value.
Time Complexity: O(n)
Find the First Non-Repeating Character
Find the first character that appears only once in a string.Example:
Input: swiss
Output: w
// Java program to find first non-
// repeating character
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeating
{
public static void main(String[] args)
{
String str = "swiss";
LinkedHashMapCharacter, Integer map = new LinkedHashMap();
for(char ch : str.toCharArray())
{
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for(Map.EntryCharacter, Integer entry : map.entrySet())
{
if(entry.getValue() == 1)
{
System.out.println("First Non-Repeating Character: " + entry.getKey());
break;
}
}
}
}
Output:
Explanation:First Non-Repeating Character: w
The LinkedHashMap preserves insertion order, making it easy to find the first character with a frequency of one.
Time Complexity: O(n)
Remove Duplicate Characters from a String
Remove duplicate characters while preserving the original order.Example:
Input: programming
Output: progamin
// Java program to remove duplicate
// characters from a string
import java.util.LinkedHashSet;
public class RemoveDuplicates
{
public static void main(String[] args)
{
String str = "programming";
LinkedHashSetCharacter set = new LinkedHashSet();
for(char ch : str.toCharArray())
{
set.add(ch);
}
String result = "";
for(char ch : set)
{
result += ch;
}
System.out.println(result);
}
}
Output:
Explanation:progamin
A LinkedHashSet automatically removes duplicates while maintaining insertion order.
Time Complexity: O(n)
Check Whether a String Contains Only Digits
Determine whether a string contains only numeric characters.Example:
Input: 12345
Output: True
// Java program to check whether a string
// contains only digits
public class DigitsOnly
{
public static void main(String[] args)
{
String str = "12345";
boolean digitsOnly = true;
for(char ch : str.toCharArray())
{
if(!Character.isDigit(ch))
{
digitsOnly = false;
break;
}
}
System.out.println(digitsOnly);
}
}
Output:
Explanation:true
Each character is checked using the Character.isDigit() method.
Time Complexity: O(n)
Find the Longest Common Prefix
Find the longest common prefix among multiple strings.Example:
Input:
flower
flow
flight
Output: fl
// Java program to find longest common prefix
public class LongestCommonPrefix
{
public static void main(String[] args)
{
String[] strs = {"flower", "flow", "flight"};
String prefix = strs[0];
for(int i = 1; i strs.length; i++)
{
while(strs[i].indexOf(prefix) != 0)
{
prefix = prefix.substring(0, prefix.length() - 1);
}
}
System.out.println("Longest Common Prefix: " + prefix);
}
}
Output:
Explanation:Longest Common Prefix: fl
The prefix is gradually reduced until it matches the beginning of every string.
Time Complexity: O(n × m)
String Compression
Compress a string by replacing repeated characters with their counts.Example:
Input: aaabbcc
Output: a3b2c2
// Java program to implement string compression
Java Program
public class StringCompression
{
public static void main(String[] args)
{
String str = "aaabbcc";
String compressed = "";
int count = 1;
for(int i = 0; i str.length() - 1; i++)
{
if(str.charAt(i) == str.charAt(i + 1))
{
count++;
}
else
{
compressed += str.charAt(i) + String.valueOf(count);
count = 1;
}
}
compressed += str.charAt(str.length() - 1) + String.valueOf(count);
System.out.println(compressed);
}
}
Output:
Explanation:a3b2c2
Consecutive repeating characters are counted and stored with their frequency.
Time Complexity: O(n)
Longest Substring Without Repeating Characters
Find the length of the longest substring containing unique characters.Example:
Input: abcabcbb
Output: 3
// Java program to find longest substring
// without repeating characters
import java.util.HashSet;
public class LongestUniqueSubstring
{
public static void main(String[] args)
{
String str = "abcabcbb";
HashSetCharacter set = new HashSet();
int left = 0;
int maxLength = 0;
for(int right = 0; right str.length(); right++)
{
while(set.contains(str.charAt(right)))
{
set.remove(str.charAt(left));
left++;
}
set.add(str.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
System.out.println("Length: " + maxLength);
}
}
Output:
Explanation:Length: 3
A Sliding Window technique is used to maintain a substring with unique characters and track the maximum length.
Time Complexity: O(n)
Common Mistakes While Solving String Questions
- Using == Instead of equals(): The == operator compares references, while equals() compares string content.
- Ignoring Case Sensitivity: Many string operations treat uppercase and lowercase letters differently.
- Not Handling Empty Strings: Programs should account for empty or null strings.
- Incorrect Index Handling: Wrong indexes can lead to StringIndexOutOfBoundsException.
- Forgetting String Immutability: String methods often return a new string instead of modifying the original one.
Tips for Cracking String Interviews
- Learn Common String Methods: Understand methods such as substring(), charAt(), contains(), equals(), and replace().
- Practice Sliding Window Problems: Many advanced string questions use the Sliding Window technique.
- Understand Hashing: HashMaps and HashSets are frequently used in string problems.
- Focus on Pattern Recognition: Many interview questions are variations of common patterns.
- Analyze Complexity: Always consider the efficiency of your solution.
Conclusion
String interview questions are essential for building strong problem-solving skills and preparing for technical interviews. By practicing these ten popular questions, you can strengthen your understanding of string manipulation, pattern matching, hashing, and sliding window techniques. Consistent practice will help you solve string problems confidently and efficiently.Frequently Asked Questions
1. Which string interview questions are asked most frequently?2. What techniques are useful for solving string problems?String reversal, palindrome checking, anagrams, character frequency counting, and longest substring problems are among the most common.
3. Why are strings important in coding interviews?Sliding Window, Two Pointers, Hashing, Sorting, and Pattern Matching are widely used techniques.
4. How can I improve my string problem-solving skills?Strings help interviewers evaluate logical thinking, text processing skills, and algorithmic problem-solving ability.
5. What should I learn after strings?Practice regularly, understand common patterns, and analyze the complexity of every solution.
6. Is the Sliding Window technique important for string questions?After strings, you can move on to linked lists, stacks, queues, trees, graphs, and dynamic programming.
Yes. Sliding Window is one of the most important techniques for solving substring and character-based problems efficiently.
0 Comments