This post is completed by 1 user

  • 0
Add to List
Beginner

211. 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 the rest of the string using the inner loop and return the first character which is repeating.  Time complexity is O(N^2).

Better approach: Using extra space

  1. Iterate the string from left to right.
  2. Count the occurrence of each character and store it on a map.
  3. Iterate the string again from left to right and check if the character has counted more than one in the map created in the previous step, if yes then return that character.
  4. If none of the characters has count > 1 in the map, return null.
  5. Time complexity is O(N) and Space Complexity is O(N).
First Repeating Character in 'horizon' is: o