Find the first repeating character in a given string

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

Example:

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

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

Approach:

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:

Output:

First Repeating Character in 'horizon' is: o

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: