Skip to main content

Top 20 String Programming and Coding Interview Questions in Java

Here are the top 20 string programming and coding interview questions, along with their answers in Java, designed for experienced Java developers:

1. Reverse a String

Question: Write a Java program to reverse a string without using the StringBuilder or StringBuffer classes.

Answer:

java
public static String reverseString(String input) { char[] chars = input.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); }

2. Check for Palindrome

Question: Write a Java function to check if a string is a palindrome (reads the same forwards and backwards).

Answer:

java
public static boolean isPalindrome(String str) { str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); int left = 0, right = str.length() - 1; while (left < right) { if (str.charAt(left) != str.charAt(right)) { return false; } left++; right--; } return true; }

3. Count Occurrences of a Character

Question: How would you count the number of occurrences of a specific character in a string in Java?

Answer:

java
public static int countOccurrences(String str, char target) { int count = 0; for (char c : str.toCharArray()) { if (c == target) { count++; } } return count; }

4. Anagram Check

Question: Write a Java program to check if two strings are anagrams of each other.

Answer:

java
public static boolean areAnagrams(String str1, String str2) { if (str1.length() != str2.length()) { return false; } char[] chars1 = str1.toCharArray(); char[] chars2 = str2.toCharArray(); Arrays.sort(chars1); Arrays.sort(chars2); return Arrays.equals(chars1, chars2); }

5. Check for Unique Characters

Question: Write a Java program to determine if a string has all unique characters.

Answer:

java
public static boolean hasUniqueCharacters(String str) { Set<Character> seen = new HashSet<>(); for (char c : str.toCharArray()) { if (seen.contains(c)) { return false; } seen.add(c); } return true; }

6. Longest Substring Without Repeating Characters

Question: Find the length of the longest substring without repeating characters in a given string.

Answer:

java
public static int lengthOfLongestSubstring(String s) { int maxLength = 0; int start = 0; Map<Character, Integer> charIndexMap = new HashMap<>(); for (int end = 0; end < s.length(); end++) { if (charIndexMap.containsKey(s.charAt(end))) { start = Math.max(start, charIndexMap.get(s.charAt(end) + 1)); } charIndexMap.put(s.charAt(end), end); maxLength = Math.max(maxLength, end - start + 1); } return maxLength; }

7. Reverse Words in a String

Question: Write a Java program to reverse the words in a given string.

Answer:

java
public static String reverseWords(String s) { String[] words = s.trim().split("\\s+"); StringBuilder reversed = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { reversed.append(words[i]).append(" "); } return reversed.toString().trim(); }

8. String to Integer (atoi)

Question: Implement the atoi function, which converts a string to an integer.

Answer:

java
public static int atoi(String str) { str = str.trim(); if (str.isEmpty()) { return 0; } int sign = 1; int index = 0; if (str.charAt(0) == '-' || str.charAt(0) == '+') { sign = str.charAt(0) == '-' ? -1 : 1; index++; } long result = 0; while (index < str.length() && Character.isDigit(str.charAt(index))) { result = result * 10 + (str.charAt(index) - '0'); if (result * sign > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (result * sign < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } index++; } return (int) (result * sign); }

9. Implement strStr()

Question: Implement the strStr() function, which finds the first occurrence of a substring in a string.

Answer:

java
public static int strStr(String haystack, String needle) { if (needle.isEmpty()) { return 0; } for (int i = 0; i <= haystack.length() - needle.length(); i++) { if (haystack.substring(i, i + needle.length()).equals(needle)) { return i; } } return -1; }

10. Valid Palindrome II

Question: Given a non-empty string, write a function to check if it can be made a palindrome by removing at most one character.

Answer:

java
public static boolean validPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); } left++; right--; } return true; } private static boolean isPalindrome(String s, int left, int right) { while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; }

11. Longest Common Prefix

Question: Write a function to find the longest common prefix among an array of strings.

Answer:

java
public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } 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); if (prefix.isEmpty()) { return ""; } } } return prefix; }

12. Valid Parentheses

Question: Write a Java function to determine if a string of parentheses is valid.

Answer:

java
public static boolean isValidParentheses(String s) { Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (c == '(' || c == '{' || c == '[') { stack.push(c); } else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') { stack.pop(); } else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') { stack.pop(); } else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') { stack.pop(); } else { return false; } } return stack.isEmpty(); }

13. Implement Regular Expression Matching

Question: Implement regular expression matching with support for '.' and '*'.

Answer:

java
public static boolean isMatch(String s, String p) { if (p.isEmpty()) { return s.isEmpty(); } boolean firstMatch = !s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'); if (p.length() >= 2 && p.charAt(1) == '*') { return (isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p))); } else { return firstMatch && isMatch(s.substring(1), p.substring(1)); } }

14. Find All Anagrams in a String

Question: Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Answer:

java
public static List<Integer> findAnagrams(String s, String p) { List<Integer> result = new ArrayList<>(); int[] pCount = new int[26]; int[] sCount = new int[26]; for (char c : p.toCharArray()) { pCount[c - 'a']++; } for (int i = 0; i < s.length(); i++) { sCount[s.charAt(i) - 'a']++; if (i >= p.length()) { sCount[s.charAt(i - p.length()) - 'a']--; } if (Arrays.equals(pCount, sCount)) { result.add(i - p.length() + 1); } } return result; }

15. Implement strStr() with KMP Algorithm

Question: Implement strStr() using the Knuth-Morris-Pratt (KMP) string-searching algorithm.

Answer:

java
public static int strStrKMP(String haystack, String needle) { if (needle.isEmpty()) { return 0; } int[] prefixArray = buildPrefixArray(needle); int i = 0, j = 0; while (i < haystack.length()) { if (haystack.charAt(i) == needle.charAt(j)) { i++; j++; } if (j == needle.length()) { return i - j; } if (i < haystack.length() && haystack.charAt(i) != needle.charAt(j)) { if (j != 0) { j = prefixArray[j - 1]; } else { i++; } } } return -1; } private static int[] buildPrefixArray(String pattern) { int[] prefixArray = new int[pattern.length()]; int length = 0; int i = 1; while (i < pattern.length()) { if (pattern.charAt(i) == pattern.charAt(length)) { length++; prefixArray[i] = length; i++; } else { if (length != 0) { length = prefixArray[length - 1]; } else { prefixArray[i] = 0; i++; } } } return prefixArray; }

16. Generate All Subsets of a String

Question: Write a Java function to generate all subsets of a string.

Answer:

java
public static List<String> generateSubsets(String s) { List<String> subsets = new ArrayList<>(); generateSubsetsHelper(s, 0, "", subsets); return subsets; } private static void generateSubsetsHelper(String s, int index, String current, List<String> subsets) { if (index == s.length()) { subsets.add(current); return; } generateSubsetsHelper(s, index + 1, current, subsets); // Exclude current character generateSubsetsHelper(s, index + 1, current + s.charAt(index), subsets); // Include current character }

17. Minimum Window Substring

Question: Given two strings s and t, return the minimum window in s that contains all characters from t.

Answer:

java
public static String minWindow(String s, String t) { int[] tCount = new int[128]; for (char c : t.toCharArray()) { tCount[c]++; } int left = 0, minLen = Integer.MAX_VALUE, minStart = 0, count = t.length(); for (int right = 0; right < s.length(); right++) { if (tCount[s.charAt(right)] > 0) { count--; } tCount[s.charAt(right)]--; while (count == 0) { if (right - left + 1 < minLen) { minLen = right - left + 1; minStart = left; } tCount[s.charAt(left)]++; if (tCount[s.charAt(left)] > 0) { count++; } left++; } } return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen); }

18. Group Anagrams

Question: Given an array of strings, group anagrams together.

Answer:

java
public static List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> anagramGroups = new HashMap<>(); for (String str : strs) { char[] charArray = str.toCharArray(); Arrays.sort(charArray); String sortedStr = new String(charArray); anagramGroups.computeIfAbsent(sortedStr, k -> new ArrayList<>()).add(str); } return new ArrayList<>(anagramGroups.values()); }

19. Count and Say

Question: The count-and-say sequence is a series of strings where each string is the result of "saying" the previous string. Write a function to generate the nth string in the count-and-say sequence.

Answer:

java
public static String countAndSay(int n) { if (n == 1) { return "1"; } String previous = countAndSay(n - 1); StringBuilder result = new StringBuilder(); char currentChar = previous.charAt(0); int count = 1; for (int i = 1; i < previous.length(); i++) { if (previous.charAt(i) == currentChar) { count++; } else { result.append(count).append(currentChar); currentChar = previous.charAt(i); count = 1; } } result.append(count).append(currentChar); return result.toString(); }

20. Regular Expression Matching (Dynamic Programming)

Question: Implement regular expression matching with support for '.' and '*'. Use dynamic programming to optimize the solution.

Answer:

java
public static boolean isMatchDP(String s, String p) { int m = s.length(), n = p.length(); boolean[][] dp = new boolean[m + 1][n + 1]; dp[0][0] = true; for (int i = 1; i <= n; i++) { if (p.charAt(i - 1) == '*') { dp[0][i] = dp[0][i - 2]; } } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (p.charAt(j - 1) == s.charAt(i - 1) || p.charAt(j - 1) == '.') { dp[i][j] = dp[i - 1][j - 1]; } else if (p.charAt(j - 1) == '*') { dp[i][j] = dp[i][j - 2] || (dp[i - 1][j] && (s.charAt(i - 1) == p.charAt(j - 2) || p.charAt(j - 2) == '.')); } } } return dp[m][n]; }

These string-related interview questions and answers cover a range of topics and challenges that experienced Java developers might encounter during technical interviews. Make sure to understand the underlying concepts, practice coding, and adapt your solutions to different scenarios to excel in coding interviews.

Comments

Popular posts from this blog

Using Java 8 Streams to Find the Second-Highest Salary in an Employee List

To find the second-highest salary from a list of employees using Java 8 streams, you can follow these steps: Create a list of employees with their salaries. Use Java 8 streams to sort the employees by salary in descending order. Skip the first element (which is the employee with the highest salary). Get the first element of the remaining stream (which is the employee with the second-highest salary). Example code: java import java.util.ArrayList; import java.util.List; class Employee { private String name; private double salary; public Employee (String name, double salary) { this .name = name; this .salary = salary; } public double getSalary () { return salary; } } public class SecondHighestSalary { public static void main (String[] args) { List<Employee> employees = new ArrayList <>(); employees.add( new Employee ( "John" , 60000.0 )); employees.add( new Employe...

Top 20 Exception Handling Interview Questions and Answers for Experienced Java Developers

Introduction: Exception handling is a crucial aspect of Java development, ensuring robust and error-tolerant code. Experienced Java developers are expected to have a deep understanding of exception handling mechanisms. In this blog post, we'll explore the top 20 interview questions related to exception handling, accompanied by detailed answers and sample code snippets to help you prepare for your next Java interview. 1. What is an exception in Java? An exception is an event that disrupts the normal flow of a program. In Java, exceptions are objects that represent errors or abnormal situations during runtime. java try { // Code that may throw an exception } catch (ExceptionType e) { // Code to handle the exception } 2. Differentiate between checked and unchecked exceptions. Checked exceptions are checked at compile-time, and the programmer is forced to either catch them or declare that the method throws them. Unchecked exceptions, on the other hand, are not checked at ...

A Deeper Look into the Java 8 Date and Time API with Q&A

  Understanding Java 8 Date and Time API: The Date and Time API introduced in Java 8 is part of the java.time package, providing classes to represent dates, times, durations, and intervals. This new API addresses many issues found in the old java.util.Date and java.util.Calendar classes, such as immutability, thread safety, and improved functionality. Benefits of Java 8 Date and Time API: Immutability : Date and time objects in the java.time package are immutable, making them thread-safe and eliminating issues related to mutability. Clarity and Readability : The API introduces clear and intuitive classes like LocalDate , LocalTime , and LocalDateTime , making code more readable and maintainable. Extensibility : It offers extensibility through the Temporal and TemporalAccessor interfaces, allowing developers to create custom date and time types. Comprehensive Functionality : The API provides comprehensive functionality for date and time manipulation, formatting, parsing, and a...

Subscribe to get new posts

Name

Email *

Message *