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++
#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string str)
{
int n = str.length();
string res = "" ;
for ( int i = 0; i < n; i++) {
int j;
for (j = i+1; j < n; j++)
if (str[i] == str[j])
break ;
if (j == n)
res = res + str[i];
}
return res;
}
int main()
{
string str = "geeksforgeeks" ;
cout << removeDuplicates(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static String removeDuplicates(String str)
{
int n = str.length();
String res = "" ;
for ( int i = 0 ; i < n; i++)
{
int j;
for (j = i + 1 ; j < n; j++)
if (str.charAt(i) == str.charAt(j))
break ;
if (j == n)
res = res + str.charAt(i);
}
return res;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.print(removeDuplicates(str));
}
}
|
Python3
def removeDuplicates( str ):
n = len ( str )
res = ""
for i in range (n):
j = i + 1
while j < n:
if ( str [i] = = str [j]):
break
j + = 1
if (j = = n):
res = res + str [i]
return res
if __name__ = = '__main__' :
str = "geeksforgeeks"
print (removeDuplicates( str ))
|
C#
using System;
class GFG{
static String removeDuplicates(String str)
{
int n = str.Length;
String res = "" ;
for ( int i = 0; i < n; i++)
{
int j;
for (j = i + 1; j < n; j++)
if (str[i] == str[j])
break ;
if (j == n)
res = res + str[i];
}
return res;
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
Console.Write(removeDuplicates(str));
}
}
|
Javascript
<script>
function removeDuplicates(str)
{
let n = str.length;
let res = "" ;
for (let i = 0; i < n; i++)
{
let j;
for (j = i + 1; j < n; j++)
if (str[i] == str[j])
break ;
if (j == n)
res = res + str[i];
}
return res;
}
let str = "geeksforgeeks" ;
document.write(removeDuplicates(str));
</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++
#include <bits/stdc++.h>
using namespace std;
string removeDuplicates(string str)
{
int n = str.length();
unordered_set< char > s;
string res = "" ;
for ( int i = n-1; i >= 0; i--) {
if (s.find(str[i]) == s.end())
{
res = res + str[i];
s.insert(str[i]);
}
}
reverse(res.begin(), res.end());
return res;
}
int main()
{
string str = "geeksforgeeks" ;
cout << removeDuplicates(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static String removeDuplicates(String str)
{
int n = str.length();
HashSet<Character> s = new HashSet<Character>();
String res = "" ;
for ( int i = n - 1 ; i >= 0 ; i--)
{
if (!s.contains(str.charAt(i)))
{
res = res + str.charAt(i);
s.add(str.charAt(i));
}
}
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);
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.print(removeDuplicates(str));
}
}
|
Python3
def removeDuplicates( str ):
n = len ( str )
s = set ()
res = ""
for i in range (n - 1 , - 1 , - 1 ):
if ( str [i] not in s):
res = res + str [i]
s.add( str [i])
res = res[:: - 1 ]
return res
str = "geeksforgeeks"
print (removeDuplicates( str ))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static String removeDuplicates(String str)
{
int n = str.Length;
HashSet< char > s = new HashSet< char >();
String res = "" ;
for ( int i = n - 1; i >= 0; i--)
{
if (!s.Contains(str[i]))
{
res = res + str[i];
s.Add(str[i]);
}
}
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);
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
Console.Write(removeDuplicates(str));
}
}
|
Javascript
<script>
function removeDuplicates(str)
{
var n = str.length;
var s = new Set();
var res = "" ;
for ( var i = n-1; i >= 0; i--) {
if (!s.has(str[i]))
{
res = res + str[i];
s.add(str[i]);
}
}
res = res.split( '' ).reverse().join( '' );
return res;
}
var str = "geeksforgeeks" ;
document.write( removeDuplicates(str));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...