Wednesday, February 17, 2021

Java Program to Find First Non-Repeated Character in a Given String

A very popular interview question for String is to write a Java program to find first non-repeated character in a given String. For example if given string is “always” then first non-repeated character is ‘l’ as character ‘a’ is repeated. Same way if String is “net” then first non-repeated character is ‘n’.

There are many ways to solve this problem, in this post I am giving 4 solutions to find first non-repeated character in a given String using Java.

  1. If you are asked not to use any inbuilt API or data structure.
  2. Solution using LinkedHashMap.
  3. Solution using indexof() method of the String class.
  4. Java 8 onward you can also use Stream API

Find first non-repeated character in a given String - Java program

  1. Solution without using any data structure or API- If you are specifically asked not to use any Java collection or any library to find first non-repeated character in a given String then you can solve it using outer and inner for loops where outer loop iterates through the string one character at a time and in inner loop you will have to compare each character of the string with the character assigned in the outer loop. In case you find a match that character is not the non-repeated one. Make sure to skip the index of the character which you are comparing otherwise you will always find the match.
    public class FirstOccurence {
    
     public static void main(String[] args) {
      String str = "zanzibar";
      
      boolean found = false;
      for(int i = 0; i < str.length(); i++){
       found = true;
       char c = str.charAt(i);
       //System.out.println("char " + c);
       for(int j = 0; j < str.length(); j++){
        //System.out.println("n-char " + str.charAt(j));
        // if found then set the boolean field as false
        // Also skip the char which is compared 
        if(c == str.charAt(j) && j != i){
         found = false;
         break;
        }
       }
       if(found){
        System.out.println("Character is "  + c);
        break;
       }
      }
      if(!found){
       System.out.println("No single character found");
      }
      
     }
    }
    

    Output

    Character is n
    
  2. Solution using LinkedHashMap- You can use LinkedHashMap to find the first non-repeated character in a String. Here LinkedHashMap is preferred over HashMap as LinkedhashMap maintains insertion order which helps to determine the first non-repeated character.

    Logic here is to iterate over each character of the String and store it in a Map where character is the key and it's count is the value. Once you have all the characters in the Map, loop through the Map and find the first key where value is 1, that key will be the first non-repeated character in the String.

    public class FirstOccurence {
    
     public static void main(String[] args) {
      String str = "always";
      Character ch = findWithLinkedHashMap(str);
      if(ch != null){
       System.out.println("Character is "  + ch);
      }else{
       System.out.println("No non-repeating character found");
      }
     }
    
     /**
      * Method to find non-repeated character using LinkedHashMap
      * @param str
      * @return
      */
     private static Character findWithLinkedHashMap(String str){
      Map<Character, Integer> charMap = new LinkedHashMap<Character, Integer>();
      for(int i = 0; i < str.length(); i++){
       Character c = str.charAt(i);
       // If found in map increment the count
       if(charMap.containsKey(c)){
        charMap.put(c, charMap.get(c) + 1);
       }else{
        charMap.put(c, 1); // First time insertion
       }
      }
      // Find the first character with count 1
      for(Entry<Character, Integer> entry : charMap.entrySet()){
       if(entry.getValue() == 1){
        return entry.getKey();
       }
      }
      return null;
     }
    }
    

    Output

    Character is l
    
  3. Solution using indexOf() method of the String class- Here logic used is; indexOf() method returns the index of the first occurrence of the specified character where as lastIndexOf() method returns the index of the last occurrence of the specified character. If both indexes are equal that means the searched character is there in the string only once.
    public class FirstOccurence {
    
     public static void main(String[] args) {
      String str = "net";
      
      Character ct = findWithIndexComparison(str);
      
      if(ct != null){
       System.out.println("Character is "  + ct);
      }else{
       System.out.println("No non-repeating character found");
      }  
     }
    
     /**
      * 
      * @param str
      * @return
      */
     private static Character findWithIndexComparison(String str){
      for(int i = 0; i < str.length(); i++){
       Character c = str.charAt(i);
       if(str.indexOf(c) == str.lastIndexOf(c)){
        return c;
       }
      }
      return null;
     }
    }
    

    Output

    Character is n
    
  4. Using Stream API to find first non-repeated character - Logic here is similar to using LinkedHashMap directly (Solution 2). Here you will use Collectors.groupingBy() method and group the characters of the String along with their count which is stored in a LinkedHashMap.
    From the Map you get the elements whose count is 1 using filter operation. Note that you get stream on Set view of the Map which returns element of type Map.Entry(). From the stream, you get after filtering, you get the first element using findFirst() which is the first non-repeated character in the String.
    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class FindNonRepeated {
      public static void main(String[] args) {
        String str = "anyway";
        try {
          Character ch = findUsingStream(str);
          System.out.println("First non-repeated character- " + ch);
        } catch(RuntimeException e) {
          System.out.println(e.getMessage());
        }
      }
      
      private static Character findUsingStream(String str){
        Map<Integer, Long> characters = str.chars()
                                           .boxed()
                                           .collect(Collectors.groupingBy(Function.identity(), 
                                              LinkedHashMap::new, 
                                              Collectors.counting()));
         return (char)characters.entrySet()
                                .stream()
                                .filter(entry -> entry.getValue() == 1)
                                .findFirst()
                                .map(entry -> entry.getKey())
                                .orElseThrow(()->new RuntimeException("No non-repeating character found"))
                                .intValue();
      }
    }
    

    Output

    First non-repeated character- n
    

That's all for this topic Java Program to Find First Non-Repeated Character in a Given String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Number of Words in a String Java Program
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Convert String to int in Java
  4. If Given String Sub-Sequence of Another String in Java
  5. Java String substring() Method - Getting Substring

You may also like-

  1. How to Find Common Elements Between Two Arrays Java Program
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. How to run a shell script from Java program
  4. How to read Properties file in Java
  5. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  6. New Date And Time API in Java With Examples
  7. Serialization and Deserialization in Java
  8. this Keyword in Java With Examples

No comments:

Post a Comment