Find first non-repeating character of given String
Last Updated :
05 Jul, 2024
Given a string S of lowercase English letters, the task is to find the index of the first non-repeating character. If there is no such character, return -1.
Examples:
Input: S = “geeksforgeeks”
Output: 5
Explanation: ‘f’ is the first character in the string which does not repeat.
Input: “aabbccc”
Output: -1
Explanation: All the characters in the given string are repeating
Approaches to find first non-repeating character of given String:
[Naive Approach] Using Two Nested Loops – O(n^2) time and O(1) auxiliary space
The very basic idea is to use two nested loops, the outer loop for picking an element and the inner loop for checking the repeating character for picked element. If no repeating character found for any characters then return the index of currently picked element, otherwise return -1;
Code Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the index of the first non-repeating
// character
int firstUniqChar(string s)
{
int n = s.length();
// Step 1: Iterate over each character in the string
for (int i = 0; i < n; ++i) {
bool found = true;
// Step 2: Check if the character repeats in the
// rest of the string
for (int j = 0; j < n; ++j) {
if (i != j && s[i] == s[j]) {
found = false;
break;
}
}
// Step 3: If character does not repeat, return its
// index
if (found) {
return i;
}
}
// Step 4: If no such character is found, return -1
return -1;
}
// Driver code
int main()
{
string s = "geeksforgeeks";
cout << firstUniqChar(s);
return 0;
}
Java
public class FirstUniqueCharacter {
// Function to find the index of the first non-repeating
// character
public static int firstUniqChar(String s)
{
int n = s.length();
// Step 1: Iterate over each character in the string
for (int i = 0; i < n; ++i) {
boolean found = true;
// Step 2: Check if the character repeats in the
// rest of the string
for (int j = 0; j < n; ++j) {
if (i != j && s.charAt(i) == s.charAt(j)) {
found = false;
break;
}
}
// Step 3: If character does not repeat, return
// its index
if (found) {
return i;
}
}
// Step 4: If no such character is found, return -1
return -1;
}
// Driver code
public static void main(String[] args)
{
String s = "geeksforgeeks";
System.out.println(firstUniqChar(s));
}
}
Python
def firstUniqChar(s):
n = len(s)
# Step 1: Iterate over each character in the string
for i in range(n):
found = True
# Step 2: Check if the character repeats in the rest of the string
for j in range(n):
if i != j and s[i] == s[j]:
found = False
break
# Step 3: If character does not repeat, return its index
if found:
return i
# Step 4: If no such character is found, return -1
return -1
# Driver code
s = "geeksforgeeks"
print(firstUniqChar(s))
C#
using System;
class FirstUniqueCharacter {
// Function to find the index of the first non-repeating
// character
public static int FirstUniqChar(string s)
{
int n = s.Length;
// Step 1: Iterate over each character in the string
for (int i = 0; i < n; ++i) {
bool found = true;
// Step 2: Check if the character repeats in the
// rest of the string
for (int j = 0; j < n; ++j) {
if (i != j && s[i] == s[j]) {
found = false;
break;
}
}
// Step 3: If character does not repeat, return
// its index
if (found) {
return i;
}
}
// Step 4: If no such character is found, return -1
return -1;
}
// Driver code
public static void Main(string[] args)
{
string s = "geeksforgeeks";
Console.WriteLine(FirstUniqChar(s));
}
}
JavaScript
function firstUniqChar(s) {
let n = s.length;
// Step 1: Iterate over each character in the string
for (let i = 0; i < n; ++i) {
let found = true;
// Step 2: Check if the character repeats in the rest of the string
for (let j = 0; j < n; ++j) {
if (i !== j && s[i] === s[j]) {
found = false;
break;
}
}
// Step 3: If character does not repeat, return its index
if (found) {
return i;
}
}
// Step 4: If no such character is found, return -1
return -1;
}
// Driver code
let s = "geeksforgeeks";
console.log(firstUniqChar(s));
Time Complexity: O(n2)
Auxiliary Space: O(1)
[Efficient Approach-1] Using Frequency Counting (Two Traversal) – O(n) time and O(1) auxiliary space
The efficient approach is to either use a hash map or an array of size 26 to store the frequencies of each character. After choosing either of data structure for frequency counting, traversing the string twice: once to populate the frequency into chosen data structure and other to find the first character with a frequency of one.
Code Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the index of the first non-repeating
// character
int firstUniqChar(string s)
{
// Step 1: Initialize frequency array for 26 lowercase
// letters
int freq[26] = { 0 };
// Step 2: Populate the frequency array
for (char c : s) {
freq[c - 'a']++;
}
// Step 3: Find the first character with frequency 1
for (int i = 0; i < s.length(); ++i) {
if (freq[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
// Driver code
int main()
{
string s = "geeksforgeeks";
cout << firstUniqChar(s);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to find the index of the first non-repeating
// character
public static int firstUniqChar(String s)
{
// Step 1: Initialize frequency array for 26
// lowercase letters
int[] freq = new int[26];
// Step 2: Populate the frequency array
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
// Step 3: Find the first character with frequency 1
for (int i = 0; i < s.length(); ++i) {
if (freq[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
// Driver code
public static void main(String[] args)
{
String s = "geeksforgeeks";
System.out.println(firstUniqChar(s));
}
}
Python
def firstUniqChar(s):
# Step 1: Initialize frequency array for 26 lowercase letters
freq = [0] * 26
# Step 2: Populate the frequency array
for c in s:
freq[ord(c) - ord('a')] += 1
# Step 3: Find the first character with frequency 1
for i in range(len(s)):
if freq[ord(s[i]) - ord('a')] == 1:
return i
return -1
# Driver code
if __name__ == "__main__":
s = "geeksforgeeks"
print(firstUniqChar(s))
C#
using System;
public class Program {
// Function to find the index of the first non-repeating
// character
public static int FirstUniqChar(string s)
{
// Step 1: Initialize frequency array for 26
// lowercase letters
int[] freq = new int[26];
// Step 2: Populate the frequency array
foreach(char c in s) { freq[c - 'a']++; }
// Step 3: Find the first character with frequency 1
for (int i = 0; i < s.Length; ++i) {
if (freq[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
// Driver code
public static void Main()
{
string s = "geeksforgeeks";
Console.WriteLine(FirstUniqChar(s));
}
}
JavaScript
// Function to find the index of the first non-repeating character
function firstUniqChar(s) {
// Step 1: Initialize frequency array for 26 lowercase letters
let freq = new Array(26).fill(0);
// Step 2: Populate the frequency array
for (let c of s) {
freq[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
// Step 3: Find the first character with frequency 1
for (let i = 0; i < s.length; ++i) {
if (freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] == 1) {
return i;
}
}
return -1;
}
// Driver code
let s = "geeksforgeeks";
console.log(firstUniqChar(s));
Time Complexity: O(n), where n is the length of given string
Auxiliary Space: O(1)
[Efficient Approach-2] By Hashing for Single Traversal – O(n) time and O(1) auxiliary space
The above approach can be optimized using a single traversal of the string. The idea is to maintain a frequency array of size 26 initialized to -1, indicating no characters have been seen yet.
Now, we iterate through the string:
- if a character is seen for the first time, its index is stored in the array.
- If the character is found again then its array value is set to -2 to represent this character is now repeating.
- After the string traversal, traverse the frequency array and check if value in the array is not equal to -1 or -2 (means, this character is not repeating)
- then we’ll minimize the array value with stored index of non-repeating character.
- If no such index is found, the function returns -1.
Code Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the index of the first non-repeating
// character
int firstUniqChar(string s)
{
// Vector to store the first occurrence index of each
// character Initialized to -1, indicating the character
// has not been seen yet
vector<int> freq(26, -1);
// Iterate through the string
for (int i = 0; i < s.size(); i++) {
// If the character is seen for the first time,
// store its index
if (freq[s[i] - 'a'] == -1) {
freq[s[i] - 'a'] = i;
}
// If the character is seen again, mark it as -2
else {
freq[s[i] - 'a'] = -2;
}
}
// Initialize idx to maximum integer value
int idx = INT_MAX;
for (int i = 0; i < 26; i++) {
if (freq[i] >= 0) {
idx = min(idx, freq[i]);
}
}
// If no non-repeating character is found, return -1
if (idx == INT_MAX) {
return -1;
}
// Return the index of the first non-repeating character
return idx;
}
// Driver code
int main()
{
// Example string
string s = "geeksforgeeks";
// Output the result of the function call
cout << firstUniqChar(s) << endl;
return 0;
}
Java
import java.util.*;
public class Main {
public static int firstUniqChar(String s)
{
// Array to store the first occurrence index of each
// character
int[] freq = new int[26];
// Initialize with -1
Arrays.fill(freq, -1);
// Iterate through the string
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
// If the character is seen for the first time,
// store its index
if (freq[cur - 'a'] == -1) {
freq[cur - 'a'] = i;
}
else {
// If the character is seen again, mark it
// as -2
freq[cur - 'a'] = -2;
}
}
// Initialize idx to maximum integer value
int idx = Integer.MAX_VALUE;
// Find the smallest index which is not marked as -1
// or -2
for (int i = 0; i < 26; i++) {
if (freq[i] >= 0) {
idx = Math.min(idx, freq[i]);
}
}
// If no non-repeating character is found, return -1
return (idx == Integer.MAX_VALUE) ? -1 : idx;
}
public static void main(String[] args)
{
String s = "geeksforgeeks";
System.out.println(firstUniqChar(s));
}
}
Python
def first_uniq_char(s):
# List to store the first occurrence index of each character
freq = [-1] * 26
# Iterate through the string
for i in range(len(s)):
cur = s[i]
if freq[ord(cur) - ord('a')] == -1:
freq[ord(cur) - ord('a')] = i
else:
freq[ord(cur) - ord('a')] = -2
# Initialize idx to maximum integer value
idx = float('inf')
# Find the smallest index which is not marked as -1 or -2
for i in range(26):
if freq[i] >= 0:
idx = min(idx, freq[i])
# If no non-repeating character is found, return -1
return -1 if idx == float('inf') else idx
# Example usage
s = "geeksforgeeks"
print(first_uniq_char(s))
C#
using System;
public class Solution {
public static int FirstUniqChar(string s)
{
// Array to store the first occurrence index of each
// character
int[] freq = new int[26];
for (int i = 0; i < 26; i++) {
freq[i] = -1; // Initialize with -1
}
// Iterate through the string
for (int i = 0; i < s.Length; i++) {
char cur = s[i];
if (freq[cur - 'a'] == -1) {
freq[cur - 'a'] = i;
}
else {
freq[cur - 'a'] = -2;
}
}
// Initialize idx to maximum integer value
int idx = int.MaxValue;
// Find the smallest index which is not marked as -1
// or -2
for (int i = 0; i < 26; i++) {
if (freq[i] >= 0) {
idx = Math.Min(idx, freq[i]);
}
}
// If no non-repeating character is found, return -1
return (idx == int.MaxValue) ? -1 : idx;
}
public static void Main()
{
string s = "geeksforgeeks";
Console.WriteLine(FirstUniqChar(s));
}
}
JavaScript
function firstUniqChar(s) {
// Array to store the first occurrence index of each character
let freq = new Array(26).fill(-1);
// Iterate through the string
for (let i = 0; i < s.length; i++) {
let cur = s.charCodeAt(i) - 'a'.charCodeAt(0);
if (freq[cur] === -1) {
freq[cur] = i;
} else {
freq[cur] = -2;
}
}
// Initialize idx to maximum integer value
let idx = Number.MAX_SAFE_INTEGER;
// Find the smallest index which is not marked as -1 or -2
for (let i = 0; i < 26; i++) {
if (freq[i] >= 0) {
idx = Math.min(idx, freq[i]);
}
}
// If no non-repeating character is found, return -1
return idx === Number.MAX_SAFE_INTEGER ? -1 : idx;
}
// Example usage
let s = "geeksforgeeks";
console.log(firstUniqChar(s));
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Problem:
Please Login to comment...