hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

First Unique Character in a String


  • Approach:

    1. Count the frequency of the characters in the given string.

    2. Now for each ith character, check the frequency of appearance.

    3. If the frequency of a character is 1, then return the ith character/ith index.

    4. If there is no character whose frequency is greater than 1, then return # / -1.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(1)


Code [C++]

#include <bits/stdc++.h>

char findNonRepeating(string str) {

vector<int>freq(26, 0);

int n = str.size();

for(int i=0; i<n; i++){

freq[str[i]-'a']++;

}

for(int i=0; i<n; i++){

if(freq[str[i]-'a'] == 1) return str[i];

}

return '#';

}