Be the first user to complete this post

  • 0
Add to List

Find the last repeating character in a given string.

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

Example:

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

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

Approach:

Naive approach: This problem can be easily solved using two nested loops from right to left. 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

  • Iterate the string from left to right.
  • Count the occurrence of each character and store it on a map.
  • Iterate the string again from right to left and check if the character has counted more than one in the map created in the previous step, if yes then return that character.
  • If none of the characters has a count > 1 in the map, return null.

Code:


Output:

Last Repeating Character in 'tutorial horizon' is: o



Also Read: