Find First Repeating Character in String using Java

[3522 views]




Given an input string, find the first repeated character in the String. Basically, we need to find a character that occurs more than once and whose index of second occurrence is the smallest.

Input: ch = "atechdaily"
Output: a
a is the first element that repeats

Input: str = "hello world"
Output: l
l is the first element that repeats

There is one simple solution to find first repeating character in String where we use 2 nested loops. Algorithm starts by traversing characters from left to right, for each character, check if it repeats or not, if the character repeats, just print the repeated character. Although this algorithm looks simpler, its time Complexity is O(n2)

So, we are going to use "Hashing" to find first Repeating Character in String.

import java.util.HashSet; import java.util.Set; public class FirstRepeatingCharacter { public static void main(String[] args) { String str="iasojs sksuxnl"; Set<Character> characterSet=new HashSet<>(); for(int i=0;i<str.length();i++) { if(characterSet.contains(str.charAt(i))) { System.out.println("First Repeating character is "+str.charAt(i)); break; }else { characterSet.add(str.charAt(i)); } } } }

Explanation

In above algorithm, we have first created an empty HashSet. Then we are traversing the String from 0 to length of string. Then for each character in string, we check if the character is present in HashSet or not. If its not present, we simply add the character as an element in HashSet. But if the character is present, then we simply print the character as it's a repeated character.

Time Complexity for Above Algorithm is O(N).

                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?



Comments










Best Search Engine:

Sponsored Deals ends in



Thinking of Buying Products Online??

Use Below Search to get Best Discounts Online

Interesting Technical Quizzes:

Online Browser Games:
     



Search Tags