Find first non-repeating character from a String

Upasana | December 04, 2019 | 1 min read | 273 views


Approach

  1. Use a LinkedHashmap to store frequency map of each character. LinkedHashmap keeps the items in the order of their insertion.

  2. Iterate over all the input String one character at a time.

  3. Filter only those entries that have frequency as 1.

  4. Find the fist entry and get its key. This character has not been repeated from given input.

Traditional approach

String str = "zzzzzbbbccccddehhhhiii";
int[] countingArray = new int[128];
str.chars().forEach(value -> countingArray[value]++);
int nonRepeatingCharAsInt = 0;
for (int i = 0; i < countingArray.length; i++) {
    if (countingArray[i] == 1) {
        nonRepeatingCharAsInt = i;
        break;
    }
}
System.out.println("character = " + Character.valueOf((char) nonRepeatingCharAsInt));

using Java 8 Streams

import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.function.Function.identity;

public class Utils {

    private Optional<Character> findFirstNonRepeatingLetter(String s) {
        final Optional<Character> optionalCharacter = s.chars()
                .mapToObj(i -> (char) i)
                .collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting()))
                .entrySet().stream()
                .filter(entry -> entry.getValue() == 1L)
                .map(entry -> entry.getKey())
                .findFirst();
        return optionalCharacter;
    }
}

Top articles in this category:
  1. Find longest non-repeating substring from a given string in Java
  2. Reverse a string using recursion in Java
  3. Check if the given string is palindrome
  4. Java Coding Problems for SDET Automation Engineer
  5. 50 Java Interview Questions for SDET Automation Engineer
  6. Palindrome checker in Java
  7. Rest Assured API Testing Interview Questions

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.