Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Print all distinct characters of a string in order (3 Methods)
Next article icon

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

Last Updated : 25 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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


 

Recommended Practice
Queries on Strings
Try It!


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.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     string str = "GeeksforGeeks";      for (int i = 0; i < str.size(); i++)     {         int flag = 0;         for (int j = 0; j < str.size(); j++)         {             // checking if two characters are equal             if (str[i] == str[j] and i != j)              {                 flag = 1;                 break;             }         }         if (flag == 0)             cout << str[i];     }      return 0; }  // This code is contributed by umadevi9616 
Java
import java.util.*;  class GFG{  public static void main(String[] args) {     String str = "GeeksforGeeks";      for (int i = 0; i < str.length(); i++)     {         int flag = 0;         for (int j = 0; j < str.length(); j++)         {             // checking if two characters are equal             if (str.charAt(i) == str.charAt(j) && i != j)              {                 flag = 1;                 break;             }         }         if (flag == 0)             System.out.print(str.charAt(i));     } } }  // This code is contributed by gauravrajput1 
Python3
string="GeeksforGeeks"  for i in range(0,len(string)):     flag=0     for j in range(0,len(string)):         #checking if two characters are equal         if(string[i]==string[j] and i!=j):             flag=1             break     if(flag==0):         print(string[i],end="") 
C#
using System;  public class GFG{  public static void Main(String[] args) {     String str = "GeeksforGeeks";      for (int i = 0; i < str.Length; i++)     {         int flag = 0;         for (int j = 0; j < str.Length; j++)         {             // checking if two characters are equal             if (str[i] == str[j] && i != j)              {                 flag = 1;                 break;             }         }         if (flag == 0)             Console.Write(str[i]);     } } }  // This code is contributed by gauravrajput1 
JavaScript
<script>         var str = "GeeksforGeeks";          for (var i = 0; i < str.length; i++) {             var flag = 0;             for (j = 0; j < str.length; j++) {                 // checking if two characters are equal                 if (str.charAt(i) == str.charAt(j) && i != j) {                     flag = 1;                     break;                 }             }             if (flag == 0)                 document.write(str.charAt(i));         }  // This code is contributed by gauravrajput1  </script> 

Output
for

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


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 
Python3
# Python3 program to print distinct  # characters of a string. NO_OF_CHARS = 256  # Print duplicates present in the  # passed string  def printDistinct(str):      # Create an array of size 256 and      # count of every character in it     count = [0] * NO_OF_CHARS      # Count array with frequency of      # characters      for i in range (len(str)):         if(str[i] != ' '):             count[ord(str[i])] += 1     n = i      # Print characters having count      # more than 0     for i in range(n):         if (count[ord(str[i])] == 1):             print (str[i], end = "")  # Driver Code if __name__ == "__main__":      str = "GeeksforGeeks"     printDistinct(str)      # This code is contributed by ita_c 
C#
// C# program to print distinct characters // of a string. using System;  public class GFG {          static 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[i]!=' ')                 count[(int)str[i]]++;                          int n = i;              // Print characters having count         // more than 0         for (i = 0; i < n; i++)             if (count[(int)str[i]] == 1)                 Console.Write(str[i]);     }          /* Driver program*/     public static void Main()     {         String str = "GeeksforGeeks";                  printDistinct(str);     } }  // This code is contributed by parashar. 
JavaScript
<script> // Javascript program to print distinct characters of a // string.      let NO_OF_CHARS = 256;          /* Print duplicates present in the passed string */     function printDistinct(str)     {         // Create an array of size 256 and count of         // every character in it         let count = new Array(NO_OF_CHARS);         for(let i=0;i<NO_OF_CHARS;i++)         {             count[i]=0;         }                 /* Count array with frequency of characters */         let i;         for (i = 0; i < str.length; i++)             if(str[i]!=' ')                 count[str[i].charCodeAt(0)]++;         let n = i;                  // Print characters having count more than 0         for (i = 0; i < n; i++)             if (count[str[i].charCodeAt(0)] == 1)                 document.write(str[i]);     }          /* Driver program*/     let str = "GeeksforGeeks";     printDistinct(str);          // This code is contributed by rag2127 </script> 

Output: 
 

for

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


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 
Python
# Python3 program to find all distinct characters # in a String  MAX_CHAR = 256  # Function to print distinct characters in # given Str[] def printDistinct(Str):      n = len(Str)      # count[x] is going to store count of     # character 'x' in Str. If x is not present,     # then it is going to store 0.     count = [0 for i in range(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[]     index = [n for i in range(MAX_CHAR)]       # Traverse the input String     for i in range(n):                  # Find current character and increment its         # count         x = ord(Str[i])         count[x] += 1          # If this is first occurrence, then set value         # in index as index of it.         if (count[x] == 1 and 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.     index=sorted(index)      for i in range(MAX_CHAR):         if index[i] == n:             break         print(Str[index[i]],end="")  # Driver code  Str = "GeeksforGeeks" printDistinct(Str)  # This code is contributed by mohit kumar 29 
C#
// C# program to print distinct characters of  // a string. using System;  public class GFG {          static 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;                          // A value more than any index             // in str[]             index[i] = n;                                  }              // 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.         Array.Sort(index);                  for (int i = 0; i < MAX_CHAR &&                                index[i] != n; i++)         Console.Write(str[index[i]]);     }          // Driver code     public static void Main()     {         string str = "GeeksforGeeks";         printDistinct(str);     } }  // This code is contributed by nitin mittal. 
JavaScript
<script> // Javascript program to print distinct characters of // a string.          let MAX_CHAR = 256;          // Function to print distinct characters in     // given string str[]     function printDistinct(str)     {         let 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.         let count = new Array(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[]         let index = new Array(MAX_CHAR);                // Initialize counts of all characters and         // indexes of distinct characters.         for (let 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 (let i = 0; i < n; i++)         {             // Find current character and increment             // its count             let x = str[i].charCodeAt(0);             ++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.         index.sort(function(a,b){return a-b});                   for (let i = 0; i < MAX_CHAR && index[i] != n;                                                   i++)            document.write(str[index[i]]);     }          // Driver code     let str = "GeeksforGeeks";     printDistinct(str);               // This code is contributed by avanitrachhadiya2155 </script> 

Output
for

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

 


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

K

kartik
Improve
Article Tags :
  • Strings
  • Dynamic Programming
  • DSA
Practice Tags :
  • Dynamic Programming
  • Strings

Similar Reads

    Print all distinct circular strings of length M in lexicographical order
    Given a string and an integer M, print all distinct circular strings of length M in lexicographical order. Examples: Input: str = "baaaa", M = 3 Output: aaa aab aba baa All possible circular substrings of length 3 are "baa" "aaa" "aaa" "aab" "aba" Out of the 6, 4 are distinct, and the lexicographica
    5 min read
    Print all the duplicate characters in a string
    Given a string s, the task is to identify all characters that appear more than once and print each as a list containing the character and its count. Examples:Input: s = "geeksforgeeks"Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]Explanation: Characters e, g, k, and s appear more than once. Their co
    8 min read
    Sort an array of strings based on count of distinct characters
    Given a string array arr[] as input, the task is to print the words sorted by number of distinct characters that occur in the word, followed by length of word. Note: If two words have same number of distinct characters, the word with more total characters comes first. If two words have same number o
    6 min read
    Count the sum of count of distinct characters present in all Substrings
    Given a string S consisting of lowercase English letters of size N where (1 <= N <= 105), the task is to print the sum of the count of distinct characters N where (1 <= N <= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings o
    8 min read
    Count of substrings having all distinct characters
    Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: Input: Str = "gffg" Output: 6 Explanation: All possible substrings from the given string are, ( "g", "gf", "gff",
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences