The Wayback Machine - https://web.archive.org/web/20240707120728/https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/
Open In App

Find first non-repeating character of given String

Last Updated : 05 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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));

Output
5

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));

Output
5

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));

Output
-1

Time Complexity: O(n)
Auxiliary Space: O(1)

Related Problem:



Similar Reads

Queries to find the last non-repeating character in the sub-string of a given string
Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}, {0, 12}} Output: G k r Sub-string for the querie
11 min read
First non-repeating character using one traversal of string | Set 2
Given a string, find the first non-repeating character in it. For example, if the input string is "GeeksforGeeks", then output should be 'f' and if input string is "GeeksQuiz", then output should be 'G'. Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed two solutions in Given a string, find its f
15+ min read
Find the first non-repeating character from a stream of characters
Given a stream of characters, find the first non-repeating character from the stream. You need to tell the first non-repeating character in O(1) time at any moment. If we follow the first approach discussed here, then we need to store the stream so that we can traverse it one more time to find the first non-repeating character at any moment. If we
15+ min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Queue based approach for first non-repeating character in a stream
Given a stream of characters and we have to find first non repeating character each time a character is inserted to the stream. Examples: Input : a a b c Output : a -1 b b Input : a a c Output : a -1 cRecommended PracticeFirst non-repeating character in a streamTry It! We have already discussed a Doubly linked list based approach in the previous po
5 min read
Find the last non repeating character in string
Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks" Output: r 'r' is the firs
5 min read
Find first non-repeating element in a given Array of integers
Given an array of integers of size N, the task is to find the first non-repeating element in this array. Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat is : 2 Input: {9, 4, 9, 6, 7, 4}Output: 6 Recommended ProblemNon-Repeating ElementSolve Problem Simple Solution is to use two loops. The outer loop pic
9 min read
Length of String formed by repeating each character in range [L, R] of given string its lexicographic value times
Given a string S of length N, and a range [L, R] (1 &lt;= L, R &lt;= N). The task is to find the length of string formed by repeating each character in the range [L, R], to its lexicographical value times. Examples: Input: s = "cbbde", l = 2, r = 5Output: 13Explanation: Resultant String is formed after repeating each character in range [2, 5] as sh
9 min read
Find the Suffix Array of given String with no repeating character
Given a string str of size N, the task is to find the suffix array of the given string. Note: A suffix array is a sorted array of all suffixes of a given string. Examples: Input: str = "prince"Output: 4 5 2 3 0 1Explanation: The suffixes are0 prince 4 ce1 rince Sort the suffixes 5 e 2 ince ----------------&gt; 2 ince 3 nce alphabetically 3 nce 4 ce
6 min read
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
three90RightbarBannerImg