Find the first repeating character in a given string

Objective: Given a string, write an algorithm to find the first repeating character in it.


String input = "horizon tutorials"
Output: 'o'

String input = "algorithms"
Output: No repeating character found.


Naive approach: This problem can be easily solved using two nested loops. Take each character from the outer loop and check the character in rest of the string using inner loop and return the first character which is repeating.  Time complexity is O(N^2).

Better approach: Using extra space

  • Iterate the string from left to right.
  • Count the occurrence of each character and store it in a map.
  • Iterate the string again from left to right and check if the character has count more than one in the map created in the previous step, if yes then return that character.
  • If none of the character has count > 1 in map, return null.
  • Time complexity is O(N) and Space Complexity is O(N).

Complete Code:

import java.util.HashMap;
public class FirstRepeatingCharacter {
public static Character getCharacter(String input){
//remove all the spaces
input = input.replaceAll(" ", "");
Character rptChar = null;
//Will store each character and it's count
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i <input.length(); i++) {
Character chr = input.charAt(i);
map.put(chr, 1);
//Iterate the string and return the character for which the count is > 1 in map
for (int i = 0; i <input.length() ; i++) {
rptChar = input.charAt(i);
return rptChar;
public static void main(String[] args) {
String input = "horizon";
Character result = getCharacter(input);
System.out.println("First Repeating Character in '"+input+"' is: " + result);
System.out.println("No Repeating Character found");


First Repeating Character in 'horizon' is: o