Search⌘ K
AI Features

Solution: First Unique Character in a String

Explore how to find the first unique character in a string by tracking character occurrences with a hash map in C#. Learn the step-by-step approach and understand the time and space complexity for efficient coding solutions.

Statement

For a given string of characters, s, your task is to find the first non-repeating character and return its index. Return 1-1 if there’s no unique character in the given string.

Constraints:

  • Only lowercase english letters are accepted.
  • There are no spaces in the string.

Solution

We need to keep track of the number of occurrences of each character in the string. To achieve this, we can use a hash map to store the character as a key and its number of occurrences in the string as its corresponding value.

The algorithm proceeds through the following steps:

  • Create a hash map and start a loop to traverse over the given input string. ...