Print all distinct characters of a string in order (3 Methods)
Last Updated :
23 Jul, 2025
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.
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>
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2 (Efficient but requires two traversals: O(n))
- Create an array count[] to store counts of characters.
- Traverse the input string str and do following for every character x = str[i].
Increment count[x]. - Traverse the input string again and do following for every character str[i]
- If count[x] is 1, then print the unique character
- 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).
- Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.
- 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
- 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>
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem