Tutorialspoint
Problem
Solution
Submissions

First Unique Character in a String

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to find the first non-repeating character in a string and return its index. If it doesn't exist, return -1. The function should return the index of the first character that appears exactly once in the string.

Example 1
  • Input: s = "Love"
  • Output: 0
  • Explanation: 'l' appears only once in the string and it's the first non-repeating character, so we return its index which is 0.
Example 2
  • Input: s = "Tutorialspoint"
  • Output: 1
  • Explanation: 't' appears twice, 'u' appears once. The first non-repeating character is 'u' at index 1.
Constraints
  • 1 ≤ s.length ≤ 10^5
  • s consists of only lowercase English letters
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(1) since we only need space for a fixed size array of 26 characters
StringsFacebookHCL Technologies
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use an array to count the frequency of each character in the string
  • Traverse the string once to fill the frequency array
  • Traverse the string again to find the first character with a frequency of 1
  • Return the index of that character
  • If no such character exists, return -1

Steps to solve by this approach:

 Step 1: Initialize a frequency array of size 26 to store the count of each lowercase letter.

 Step 2: Traverse the string once and count the frequency of each character.
 Step 3: We subtract 'a' from each character to get its index in the frequency array (e.g., 'a'-'a'=0, 'b'-'a'=1).
 Step 4: Traverse the string again to find the first character with a frequency of 1.
 Step 5: Return the index of the first unique character.
 Step 6: If no unique character is found, return -1.
 Step 7: Time complexity is O(n) because we traverse the string twice, and space complexity is O(1) because the array size is constant.

Submitted Code :