Find first non-repeating character from a String

Carvia Tech | December 04, 2019 | 1 min read | 250 views


  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;
System.out.println("character = " + Character.valueOf((char) nonRepeatingCharAsInt));

using Java 8 Streams

import java.util.LinkedHashMap;
import java.util.Optional;

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()))
                .filter(entry -> entry.getValue() == 1L)
                .map(entry -> entry.getKey())
        return optionalCharacter;

Top articles in this category:
  1. SDET Java Coding Challenges
  2. 50 SDET Java Interview Questions & Answers
  3. SDET: JUnit interview questions for automation engineer
  4. Rest Assured API Testing Interview Questions
  5. Find longest non-repeating substring from a given string in Java
  6. Write a program to reverse a string using recursion in Java
  7. Anagrams string checker in Java

Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info