Append digits to the end of duplicate strings to make all strings in an array unique - GeeksforGeeks

04 Aug, 2021
Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending ay number such that all the strings in the array are unique.
Examples:
Input: S = {“aa”, “bb”, “cc”, “bb”, “aa”, “aa”, “aa”}Output: {“aa”, “bb”, “cc”, “bb1”, “aa1”, “aa2”, “aa3”}Explanation:The output of the second occurrence of “bb” is “bb1” The output of the second occurrence of “aa” is “aa1” The output of the third occurrence of “aa” is “aa2” The output of the fourth occurrence of “aa” is “aa3”
Input: S = {“aa”, “bb”, “cc”, “aa”}Output: {“aa”, “bb”, “cc”, “aa1”}
Approach: The idea is to traverse the array and store the frequency of each string in arr[] in a Hashmap. While storing the frequency, if the string has no previous occurrences, then leave the string unchanged. Otherwise, append its frequency at the end. Finally, print all the unique strings present in the array arr[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquevoid replaceDuplicates(    vector<string>& names){    // Store the frequency of strings    unordered_map<string, int> hash;     // Iterate over the array    for (int i = 0;         i < names.size(); i++) {         // For the first occurrence,        // update the frequency count        if (hash.count(names[i]) == 0)            hash[names[i]]++;         // Otherwise        else {             int count = hash[names[i]]++;             // Append frequency count            // to end of the string            names[i] += to_string(count);        }    }     // Print the modified array    for (int i = 0;         i < names.size(); i++) {        cout << names[i] << " ";    }} // Driver Codeint main(){    vector<string> str        = { "aa", "bb", "cc", "bb",            "aa", "aa", "aa" };     // Function Call    replaceDuplicates(str);     return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquestatic void replaceDuplicates(String[] names){         // Store the frequency of strings    HashMap<String, Integer> hash = new HashMap<>();     // Iterate over the array    for(int i = 0; i < names.length; i++)    {                 // For the first occurrence,        // update the frequency count        if (!hash.containsKey(names[i]))            hash.put(names[i], 1);         // Otherwise        else        {            int count = hash.get(names[i]);            hash.put(names[i], hash.get(names[i]) + 1);             // Append frequency count            // to end of the string            names[i] += Integer.toString(count);        }    }     // Print the modified array    for(int i = 0; i < names.length; i++)    {        System.out.print(names[i] + ' ');    }} // Driver Codepublic static void main(String[] args){    String[] str = { "aa", "bb", "cc",                     "bb", "aa", "aa", "aa" };     // Function Call    replaceDuplicates(str);}} // This code is contributed by akhilsaini
# Python3 program for the above approach # Function to replace duplicate strings# by alphanumeric strings to make all# strings in the array uniquedef replaceDuplicates(names):         # Store the frequency of strings    hash = {}     # Iterate over the array    for i in range(0, len(names)):                 # For the first occurrence,        # update the frequency count        if names[i] not in hash:            hash[names[i]] = 1         # Otherwise        else:            count = hash[names[i]]            hash[names[i]] += 1             # Append frequency count            # to end of the string            names[i] += str(count)     # Print the modified array    for i in range(0, len(names)):        print(names[i], end = ' ') # Driver Codeif __name__ == '__main__':         str1 = [ "aa", "bb", "cc",             "bb", "aa", "aa", "aa" ]     # Function Call    replaceDuplicates(str1) # This code is contributed by akhilsaini
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquestatic void replaceDuplicates(string[] names){         // Store the frequency of strings    Dictionary<string,               int> hash = new Dictionary<string,                                          int>();                                               // Iterate over the array    for(int i = 0; i < names.Length; i++)    {                 // For the first occurrence,        // update the frequency count        if (!hash.ContainsKey(names[i]))            hash[names[i]] = 1;         // Otherwise        else        {            int count = hash[names[i]];            hash[names[i]] += 1;             // Append frequency count            // to end of the string            names[i] += count.ToString();        }    }     // Print the modified array    for(int i = 0; i < names.Length; i++)    {        Console.Write(names[i] + ' ');    }} // Driver Codepublic static void Main(){    string[] str = { "aa", "bb", "cc",                     "bb", "aa", "aa", "aa" };     // Function Call    replaceDuplicates(str);}} // This code is contributed by akhilsaini
<script> // Javascript program for the above approach // Function to replace duplicate strings// by alphanumeric strings to make all// strings in the array uniquefunction replaceDuplicates( names){    // Store the frequency of strings    var hash = new Map();     // Iterate over the array    for (var i = 0;         i < names.length; i++) {         // For the first occurrence,        // update the frequency count        if (!hash.has(names[i]))            hash.set(names[i],1);         // Otherwise        else {             var count = hash.get(names[i]);            hash.set(names[i],hash.get(names[i])+1);            // Append frequency count            // to end of the string            names[i] += count.toString();        }    }     // Print the modified array    for (var i = 0;         i < names.length; i++) {        document.write( names[i] + " ");    }} // Driver Codevar str    = [ "aa", "bb", "cc", "bb",        "aa", "aa", "aa" ];// Function CallreplaceDuplicates(str); </script>
aa bb cc bb1 aa1 aa2 aa3
 
Time Complexity: O(N)Auxiliary Space: O(N)
akhilsaini
rrrtnx
simmytarika5
arorakashish0911
cpp-unordered_map
frequency-counting
HashTable
Technical Scripter 2020
Arrays
Hash
Searching
Strings
Technical Scripter
Arrays
Searching
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)