Tech Interview RoomStudy guides

Java Streams

Java 8 Streams interview problems on strings and numbers.

Intermediate · 2 min read · Lesson 2 of 4 in Java Streams

Problem

Solve the frequently asked string and number puzzles with streams: character frequency, first non-repeated character, duplicates, reversing words, second largest number, and so on.

java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class StringStreams {
    public static void main(String[] args) {
        String s = "programming in java";

        // 1. Character frequency (ignoring spaces), in order of first appearance
        Map<Character, Long> freq = s.chars().filter(c -> c != ' ')
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));

        // 2. First non-repeated character
        Character firstUnique = freq.entrySet().stream()
            .filter(e -> e.getValue() == 1).map(Map.Entry::getKey).findFirst().orElse(null);

        // 3. First repeated character
        Character firstRepeated = freq.entrySet().stream()
            .filter(e -> e.getValue() > 1).map(Map.Entry::getKey).findFirst().orElse(null);

        // 4. Duplicate elements in a list
        List<Integer> nums = List.of(5, 3, 8, 3, 7, 5, 2);
        Set<Integer> seen = new java.util.HashSet<>();
        Set<Integer> duplicates = nums.stream().filter(n -> !seen.add(n)).collect(Collectors.toCollection(java.util.TreeSet::new));

        // 5. Second largest number
        int secondLargest = nums.stream().distinct().sorted(Collections.reverseOrder()).skip(1).findFirst().orElseThrow();

        // 6. Reverse each word, keeping word order
        String reversedWords = Arrays.stream(s.split(" "))
            .map(w -> new StringBuilder(w).reverse().toString())
            .collect(Collectors.joining(" "));

        // 7. Reverse the word order
        List<String> words = Arrays.asList(s.split(" "));
        String reversedOrder = IntStream.range(0, words.size())
            .mapToObj(i -> words.get(words.size() - 1 - i)).collect(Collectors.joining(" "));

        // 8. Is the string a palindrome? (ignore case and non-letters)
        String p = "A man, a plan, a canal: Panama".toLowerCase().replaceAll("[^a-z]", "");
        boolean palindrome = IntStream.range(0, p.length() / 2).allMatch(i -> p.charAt(i) == p.charAt(p.length() - 1 - i));

        // 9. Longest word
        String longest = Arrays.stream(s.split(" ")).max(java.util.Comparator.comparingInt(String::length)).orElse("");

        // 10. Sum of squares of even numbers
        int sumSquaresEven = nums.stream().filter(n -> n % 2 == 0).mapToInt(n -> n * n).sum();

        System.out.println(freq);             // {p=1, r=2, o=1, g=2, a=3, m=2, i=2, n=2, j=1, v=1}
        System.out.println(firstUnique);      // p
        System.out.println(firstRepeated);    // r
        System.out.println(duplicates);       // [3, 5]
        System.out.println(secondLargest);    // 7 (distinct values 8, 7, ...)
        System.out.println(reversedWords);    // gnimmargorp ni avaj
        System.out.println(reversedOrder);    // java in programming
        System.out.println(palindrome);       // true
        System.out.println(longest);          // programming
        System.out.println(sumSquaresEven);   // 68 (8*8 + 2*2)
    }
}

Key points to mention

  • String.chars() returns an IntStream; box with mapToObj(c -> (char) c).
  • A LinkedHashMap map factory preserves first-appearance order, which "first non-repeated" depends on.
  • The seen.add trick for duplicates uses a side effect; it is fine for sequential streams but not thread-safe for parallel ones. A side-effect-free alternative is grouping by identity with counting and filtering counts above 1.
  • For hot paths, a plain loop with an int[] counter is faster than boxing every character.

Follow-up questions interviewers ask

Try answering each one before you open it.

Find the first non-repeated character without streams in O(n).

Count occurrences in an int[256] (or a HashMap for Unicode) in one pass, then scan the string again and return the first character with count 1. Two linear passes, O(1) extra space for a fixed alphabet.

How would you handle Unicode characters outside the Basic Multilingual Plane (emoji)?

chars() iterates UTF-16 code units, so an emoji becomes two surrogate halves. Use codePoints() and work with int code points (new String(Character.toChars(cp))), or for user-perceived characters (grapheme clusters, such as flags or skin-tone emoji) use BreakIterator.getCharacterInstance().