Remove duplicates from string keeping the order according to last occurrences
Last Updated :
29 Dec, 2022
Given a string, remove duplicate characters from the string, retaining the last occurrence of the duplicate characters. Assume the characters are case-sensitive.
Examples:
Input : geeksforgeeks
Output : forgeks
Explanation : Please note that we keep only last occurrences of repeating characters in same order as they appear in input. If we see result from right side, we can notice that we keep last 's', then last 'k' , and so on.
Input : hi this is sample test
Output : hiampl est
Explanation : Here, the output contains last occurrence of every character, even " "(spaces), and removing the duplicates. Like in this example, there are 4 spaces count, so we have only the last occurrence of space in it removing the others. And there is only last occurrence of each character without repetition.
Input : Abcda
Output : Abcda
Naive Solution: Traverse the given string from left to right. For every character check if it appears on right side also. If it does, then do not include in output, otherwise include it.
C++
// C++ program to remove duplicate character
// from character array and print in sorted
// order
#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string str)
{
// Used as index in the modified string
int n = str.length();
// Traverse through all characters
string res = "";
for (int i = 0; i < n; i++) {
// Check if str[i] is present before it
int j;
for (j = i+1; j < n; j++)
if (str[i] == str[j])
break;
// If not present, then add it to
// result.
if (j == n)
res = res + str[i];
}
return res;
}
// Driver code
int main()
{
string str = "geeksforgeeks";
cout << removeDuplicates(str);
return 0;
}
Java
// Java program to remove duplicate character
// from character array and print in sorted
// order
import java.util.*;
class GFG{
static String removeDuplicates(String str)
{
// Used as index in the modified String
int n = str.length();
// Traverse through all characters
String res = "";
for (int i = 0; i < n; i++)
{
// Check if str[i] is present before it
int j;
for (j = i + 1; j < n; j++)
if (str.charAt(i) == str.charAt(j))
break;
// If not present, then add it to
// result.
if (j == n)
res = res + str.charAt(i);
}
return res;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.print(removeDuplicates(str));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to remove duplicate character
# from character array and print sorted
# order
def removeDuplicates(str):
# Used as index in the modified string
n = len(str)
# Traverse through all characters
res = ""
for i in range(n):
# Check if str[i] is present before it
j = i + 1
while j < n:
if (str[i] == str[j]):
break
j += 1
# If not present, then add it to
# result.
if (j == n):
res = res + str[i]
return res
# Driver code
if __name__ == '__main__':
str = "geeksforgeeks"
print(removeDuplicates(str))
# This code is contributed by mohit kumar 29
C#
// C# program to remove duplicate character
// from character array and print in sorted
// order
using System;
class GFG{
static String removeDuplicates(String str)
{
// Used as index in the modified String
int n = str.Length;
// Traverse through all characters
String res = "";
for(int i = 0; i < n; i++)
{
// Check if str[i] is present before it
int j;
for(j = i + 1; j < n; j++)
if (str[i] == str[j])
break;
// If not present, then add it to
// result.
if (j == n)
res = res + str[i];
}
return res;
}
// Driver code
public static void Main(String[] args)
{
String str = "geeksforgeeks";
Console.Write(removeDuplicates(str));
}
}
// This code is contributed by sapnasingh4991
JavaScript
<script>
// Javascript program to remove duplicate character
// from character array and print in sorted
// order
function removeDuplicates(str)
{
// Used as index in the modified String
let n = str.length;
// Traverse through all characters
let res = "";
for (let i = 0; i < n; i++)
{
// Check if str[i] is present before it
let j;
for (j = i + 1; j < n; j++)
if (str[i] == str[j])
break;
// If not present, then add it to
// result.
if (j == n)
res = res + str[i];
}
return res;
}
// Driver code
let str = "geeksforgeeks";
document.write(removeDuplicates(str));
// This code is contributed by code_hunt.
</script>
Time Complexity: O(n*n)
Auxiliary Space: O(n), where n is the length of the given string.
Efficient Solution: The idea is to use hashing.
1) Initialize an empty hash table and res = ""
2) Traverse input string from right to left. If the current character is not present in the hash table, append it to res and insert it in the hash table. Else ignore it.
C++
// C++ program to remove duplicate character
// from character array and print in sorted
// order
#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string str)
{
// Used as index in the modified string
int n = str.length();
// Create an empty hash table
unordered_set<char> s;
// Traverse through all characters from
// right to left
string res = "";
for (int i = n-1; i >= 0; i--) {
// If current character is not in
if (s.find(str[i]) == s.end())
{
res = res + str[i];
s.insert(str[i]);
}
}
// Reverse the result string
reverse(res.begin(), res.end());
return res;
}
// Driver code
int main()
{
string str = "geeksforgeeks";
cout << removeDuplicates(str);
return 0;
}
Java
// Java program to remove duplicate character
// from character array and print in sorted
// order
import java.util.*;
class GFG{
static String removeDuplicates(String str)
{
// Used as index in the modified String
int n = str.length();
// Create an empty hash table
HashSet<Character> s = new HashSet<Character>();
// Traverse through all characters from
// right to left
String res = "";
for(int i = n - 1; i >= 0; i--)
{
// If current character is not in
if (!s.contains(str.charAt(i)))
{
res = res + str.charAt(i);
s.add(str.charAt(i));
}
}
// Reverse the result String
res = reverse(res);
return res;
}
static String reverse(String input)
{
char[] a = input.toCharArray();
int l, r = a.length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.print(removeDuplicates(str));
}
}
// This code is contributed by sapnasingh4991
Python3
# Python3 program to remove duplicate character
# from character array and print sorted order
def removeDuplicates(str):
# Used as index in the modified string
n = len(str)
# Create an empty hash table
s = set()
# Traverse through all characters from
# right to left
res = ""
for i in range(n - 1, -1, -1):
# If current character is not in
if (str[i] not in s):
res = res + str[i]
s.add(str[i])
# Reverse the result string
res = res[::-1]
return res
# Driver code
str = "geeksforgeeks"
print(removeDuplicates(str))
# This code is contributed by ShubhamCoder
C#
// C# program to remove duplicate character
// from character array and print in sorted
// order
using System;
using System.Collections.Generic;
class GFG{
static String removeDuplicates(String str)
{
// Used as index in the modified String
int n = str.Length;
// Create an empty hash table
HashSet<char> s = new HashSet<char>();
// Traverse through all characters
// from right to left
String res = "";
for(int i = n - 1; i >= 0; i--)
{
// If current character is not in
if (!s.Contains(str[i]))
{
res = res + str[i];
s.Add(str[i]);
}
}
// Reverse the result String
res = reverse(res);
return res;
}
static String reverse(String input)
{
char[] a = input.ToCharArray();
int l, r = a.Length - 1;
for(l = 0; l < r; l++, r--)
{
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.Join("", a);
}
// Driver code
public static void Main(String[] args)
{
String str = "geeksforgeeks";
Console.Write(removeDuplicates(str));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to remove duplicate character
// from character array and print in sorted
// order
function removeDuplicates(str)
{
// Used as index in the modified string
var n = str.length;
// Create an empty hash table
var s = new Set();
// Traverse through all characters from
// right to left
var res = "";
for (var i = n-1; i >= 0; i--) {
// If current character is not in
if (!s.has(str[i]))
{
res = res + str[i];
s.add(str[i]);
}
}
// Reverse the result string
res = res.split('').reverse().join('');
return res;
}
// Driver code
var str = "geeksforgeeks";
document.write( removeDuplicates(str));
// This code is contributed by rrrtnx.
</script>
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given string.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read