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
Remove last occurrence of a word from a given sentence string
Given two strings S and W of sizes N and M respectively, the task is to remove the last occurrence of W from S. If there is no occurrence of W in S, print S as it is. Examples: Input: S = âThis is GeeksForGeeksâ, W="Geeks"Output: This is GeeksForExplanation:The last occurrence of âGeeksâ in the stri
11 min read
Remove All Duplicates from a Given String in Python
The task of removing all duplicates from a given string in Python involves retaining only the first occurrence of each character while preserving the original order. Given an input string, the goal is to eliminate repeated characters and return a new string with unique characters. For example, with
2 min read
Remove all consecutive duplicates from the string
Given a string s , The task is to remove all the consecutive duplicate characters of the string and return the resultant string. Examples: Input: s = "aaaaabbbbbb"Output: abExplanation: Remove consecutive duplicate characters from a string s such as 5 a's are at consecative so only write a and same
10 min read
Remove three consecutive duplicates from string
Given a string, you have to remove the three consecutive duplicates from the string. If no three are consecutive then output the string as it is. Examples: Input : aabbbaccddddcOutput :ccdcInput :aabbaccddcOutput :aabbaccddcRecommended PracticeThree consecutive duplicatesTry It!Explanation : We inse
12 min read
Reorder the given string to form a K-concatenated string
Given a string S and an integer K. The task is to form a string T such that the string T is a reordering of the string S in a way that it is a K-Concatenated-String. A string is said to be a K-Concatenated-String if it contains exactly K copies of some string.For example, the string "geekgeek" is a
8 min read
Rearrange a String According to the Given Indices
Given a string and a list of indices, the task is to rearrange the characters of the string based on the given indices. For example, if the string is "code" and the indices are [3, 1, 0, 2], the rearranged string should be "edoc". Let's explore various ways in which we can do this in Python.Using li
3 min read
Remove duplicates from a string using STL in C++
Given a string S, remove duplicates in this string using STL in C++ Examples: Input: Geeks for geeks Output: Gefgkors Input: aaaaabbbbbb Output: ab Approach: The consecutive duplicates of the string can be removed using the unique() function provided in STL. Below is the implementation of the above
1 min read
Sort a string according to the order defined by another string
Given two strings (of lowercase letters), a pattern, and a string. The task is to sort strings according to the order defined by the pattern. It may be assumed that the pattern has all characters of the string and all characters in the pattern appear only once. Examples: Input : pat = "bca", str = "
9 min read
Remove all occurrences of string t in string s using KMP Algorithm
Given two strings s and t, the task is to remove all occurrences of t in s and return the modified string s, and you have to use the KMP algorithm to solve this. Examples: Input: s = "abcdefgabcabcabdefghabc", t = "abc"Output: "defgdefgh" Input: s = "aaabbbccc", t = "bbb"Output: "aaaccc" Approach: T
8 min read
Remove all occurrences of a character from a string using STL
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string. Examples: Input:vS = "GFG IS FUN", C = 'F' Output:GG IS UN Explanation: Removing all occurrences of the character 'F' modifies S to "GG IS UN". Therefore, the required output is GG
2 min read