Skip to content
Related Articles

Related Articles

Improve Article

Remove duplicates from string keeping the order according to last occurrences

  • Difficulty Level : Easy
  • Last Updated : 08 Jun, 2021

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

 



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 prin 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>
Output: 
forgeks

 

Time Complexity: O(n*n)
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 prin 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>
Output: 
forgeks

 

Time Complexity: O(n)
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :