Print all distinct characters of a string in order (3 Methods)

2.3

Given a string, find the all distinct (or non-repeating characters) in it. For example, if the input string is “Geeks for Geeks”, then output should be ‘for’ and if input string is “Geeks Quiz”, then output should be ‘GksQuiz’.

The distinct characters should be printed in same order as they appear in input string.

Examples:

Input  : Geeks for Geeks
Output : for

Input  : Hello Geeks
Output : HoGks

Method 1 (Simple : O(n2))
A Simple Solution is to run two loops. Start traversing from left side. For every character, check if it repeats or not. If the character doesn’t repeat, increment count of non-repeating characters. When the count becomes 1, return each character.

Method 2 (Efficient but requires two traversals: O(n))

  1. Create an array count[] to store counts of characters.
  2. Traverse the input string str and do following for every character x = str[i].
    Increment count[x].
  3. Traverse the input string again and do following for every character str[i]
    1. If count[x] is 1, then print the unique character
    2. If count[x] is greater than 1, then ignore the repeated character.

Below is the implementation of above idea.

C++

// C++ program to print distinct characters of a
// string.
# include <iostream>
using namespace std;
# define NO_OF_CHARS 256

/* Print duplicates present in the passed string */
void printDistinct(char *str)
{
    // Create an array of size 256 and count of
    // every character in it
    int count[NO_OF_CHARS];

    /* Count array with frequency of characters */
    int i;
    for (i = 0; *(str+i); i++)
        if(*(str+i)!=' ')
            count[*(str+i)]++;
    int n = i;

    // Print characters having count more than 0
    for (i = 0; i < n; i++)
        if (count[*(str+i)] == 1)
            cout<< str[i];
}

/* Driver program*/
int main()
{
    char str[] = "GeeksforGeeks";
    printDistinct((str);
    return 0;
}

Java

// Java program to print distinct characters of a
// string.
public class GFG {
    static final int NO_OF_CHARS = 256;
     
    /* Print duplicates present in the passed string */
    static void printDistinct(String str)
    {
        // Create an array of size 256 and count of
        // every character in it
        int[] count = new int[NO_OF_CHARS];
     
        /* Count array with frequency of characters */
        int i;
        for (i = 0; i < str.length(); i++)
            if(str.charAt(i)!=' ')
                count[(int)str.charAt(i)]++;
        int n = i;
     
        // Print characters having count more than 0
        for (i = 0; i < n; i++)
            if (count[(int)str.charAt(i)] == 1)
                System.out.print(str.charAt(i));
    }
     
    /* Driver program*/
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);
    }
}
// This code is contributed by Sumit Ghosh


Output:

for

 

Method 3 (O(n) and requires one traversal)
The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored using 8 bits).

  1. Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.
  2. Traverse the input string str and do following for every character c = str[i].
    • Increment count[x].
    • If count[x] is 1, then store index of x in index[x], i.e., index[x] = i
    • If count[x] is 2, then remove x from index[], i.e., index[x] = n
  3. Now index[] has indexes of all distinct characters. Sort indexes and print characters using it. Note that this step takes O(1) time assuming number of characters are fixed (typically 256)

Below is the implementation of above idea.

C++

// C++ program to find all distinct characters
// in a string
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;

// Function to print distinct characters in
// given string str[]
void printDistinct(string str)
{
    int n = str.length();

    // count[x] is going to store count of
    // character 'x' in str. If x is not present,
    // then it is going to store 0.
    int count[MAX_CHAR];

    // index[x] is going to store index of character
    // 'x' in str. If x is not present or x is
    // more than once, then it is going to store a value
    // (for example, length of string) that cannot be
    // a valid index in str[]
    int index[MAX_CHAR];

    // Initialize counts of all characters and indexes
    // of distinct characters.
    for (int i = 0; i < MAX_CHAR; i++)
    {
        count[i] = 0;
        index[i] = n; // A value more than any index
                      // in str[]
    }

    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        // Find current character and increment its
        // count
        char x = str[i];
        ++count[x];

        // If this is first occurrence, then set value
        // in index as index of it.
        if (count[x] == 1 && x !=' ')
            index[x] = i;

        // If character repeats, then remove it from
        // index[]
        if (count[x] == 2)
            index[x] = n;
    }

    // Since size of index is constant, below operations
    // take constant time.
    sort(index, index+MAX_CHAR);
    for (int i=0; i<MAX_CHAR && index[i] != n; i++)
       cout << str[index[i]];
}

// Driver code
int main()
{
    string str = "GeeksforGeeks";
    printDistinct(str);
    return 0;
}

Java

// Java program to print distinct characters of 
// a string.
import java.util.Arrays;

public class GFG {
    
    static final int MAX_CHAR = 256;
     
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(String str)
    {
        int n = str.length();
     
        // count[x] is going to store count of
        // character 'x' in str. If x is not present,
        // then it is going to store 0.
        int[] count = new int[MAX_CHAR];
     
        // index[x] is going to store index of character
        // 'x' in str. If x is not present or x is
        // more than once, then it is going to store a 
        // value (for example, length of string) that 
        // cannot be a valid index in str[]
        int[] index = new int[MAX_CHAR];
     
        // Initialize counts of all characters and 
        // indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
            index[i] = n; // A value more than any 
                          // index in str[]
        }
     
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and increment 
            // its count
            char x = str.charAt(i);
            ++count[x];
     
            // If this is first occurrence, then set 
            // value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
     
            // If character repeats, then remove it 
            // from index[]
            if (count[x] == 2)
                index[x] = n;
        }
     
        // Since size of index is constant, below 
        // operations take constant time.
        Arrays.sort(index);
        
        for (int i = 0; i < MAX_CHAR && index[i] != n;
                                                  i++)
           System.out.print(str.charAt(index[i]));
    }
     
    // Driver code
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);
    }
}
// This code is contributed by Sumit Ghosh


Output:

for

This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.3 Average Difficulty : 2.3/5.0
Based on 13 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.