Find First Non-Repeating Character in a String

Find first non-repeating character in a string

Find first non-repeating character in a string

Given an input string, Write a code to find first Non-repeating character in a string. Suppose an input string is webrewrite, the first non-repeated character in this string is b.

In this tutorial, we will write a code in multiple programming languages to solve this problem.

How to Find First Non-Repeating Character in a String

Method 1 – Naive Approach

Subscribe Our Tutorials

Get Latest Updates on Facebook

Use two for loops and compare each character with every character of a string.  But the time complexity using this approach is  O(n2).

Method 2 – Create key and value pairs for character and it’s count

We can create a key and value pairs for character and it’s count. This approach is much better as compared to first one. Let’s implement this method.

PHP Code to Find First Non-Repeating Character in a String

Let’s try to solve this problem in a single traversal.

Method 2:

How to sort string in PHP.

C++ Program Find First Non-Repeating Character in a String

In this code, I am using C++ map library to make a hash (key and value pair).

Question on Linked List.

 

Java Program to Find First Non-repeating character in a String

 

Conclusion

If you know some other efficient way to solve this problem then let us know through your comments.

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.
  • Guest

    That’s my method :

    char str[] = "ilkerburaknet";
    int N = strlen(str);

    int i,j,found = 0;
    char firstnonrep = NULL;
    for(i=0;i<N;i++){
    found = 0;

    for(j=0;j<N;j++){
    if(str[i]==str[j]){
    found++;
    }
    }
    if(found==1) {
    firstnonrep = str[i];
    printf("%c",firstnonrep);
    break;
    }
    }

  • Guest

    [sourcecode language=”c”]
    char str[] = “ilkerburaknet”;
    int N = strlen(str);

    int i,j,found = 0;
    char firstnonrep = NULL;
    for(i=0;i<N;i++){
    found = 0;

    for(j=0;j<N;j++){
    if(str[i]==str[j]){
    found++;
    }
    }
    if(found==1) {
    firstnonrep = str[i];
    printf("%c",firstnonrep);
    break;
    }
    }
    [/sourcecode]

  • Guest