Google Add


Program to Print First Non Repeating Character of a String - C, C++ Code

Write a C, C++ program to print first non repeating character of a string.  Given an input string, write a code to print only first non-repeating character of a string.

Programming questions on string.

Let's take an example. Suppose an input string is HELLO.  In this word, H is a first non-repeating character.

Method 1 - Using two for loops to compare each character of a string with other characters. The time complexity of this approach is O(n2).

C Program to Find First Non Repeating Character of a String

#include <stdio.h>
#include <string.h>

int main(void) {
 char str[100] = "cprogrammingcode";
 int len  = strlen(str);
 int flag;
 /* Two loops to compare each
    character with other character
 for(int i = 0; i < len; i++) {
     flag = 0; 
     for(int j = 0; j < len; j++) {
        /* If it's equal and indexes
           is not same */
        if((str[i] == str[j]) && (i != j)) {
             flag = 1;
      if (flag == 0) {
          printf("First non-repeating character is %c",str[i]);
 if (flag == 1) {
     printf("Didn't find any non-repeating character");
  return 0;

Now let's optimize this solution .

Method 2 - Using hash map library in C++.

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

#include <iostream>
#include <map>
#include <string.h>
using namespace std;

int main() {
    char str[100] = "cprogrammingcode";
    int i,len;

    /* Declare hash */
    map<char,int> hash;
    len = strlen(str);
   /* Make key and value pair
      key denotes character
      value is the count of a character
   for(i = 0; i < len; i++){

      hash[str[i]]= hash[str[i]] + 1;
    /* Check the count
      if count is 1 then print the element 
       if (hash[str[j]]==1){
          cout<<"First non-repeated character is "<<str[j];

   return 0;

Programming question on Arrays

Programming question on Linked List

Sorting algorithm and their time complexity

Stack implementation

Programming questions using Recursion

C, C++ interview questions

Programming Books

No comments:

Post a Comment