Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 30 Jun, 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++




// 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 unique
void 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 fist 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 Code
int main()
{
    vector<string> str
        = { "aa", "bb", "cc", "bb",
            "aa", "aa", "aa" };
 
    // Function Call
    replaceDuplicates(str);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to replace duplicate strings
// by alphanumeric strings to make all
// strings in the array unique
static 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 fist 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 Code
public 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




# Python3 program for the above approach
 
# Function to replace duplicate strings
# by alphanumeric strings to make all
# strings in the array unique
def replaceDuplicates(names):
     
    # Store the frequency of strings
    hash = {}
 
    # Iterate over the array
    for i in range(0, len(names)):
         
        # For the fist 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 Code
if __name__ == '__main__':
     
    str1 = [ "aa", "bb", "cc",
             "bb", "aa", "aa", "aa" ]
 
    # Function Call
    replaceDuplicates(str1)
 
# This code is contributed by akhilsaini

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to replace duplicate strings
// by alphanumeric strings to make all
// strings in the array unique
static 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 fist 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 Code
public static void Main()
{
    string[] str = { "aa", "bb", "cc",
                     "bb", "aa", "aa", "aa" };
 
    // Function Call
    replaceDuplicates(str);
}
}
 
// This code is contributed by akhilsaini

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to replace duplicate strings
// by alphanumeric strings to make all
// strings in the array unique
function 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 fist 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 Code
var str
    = [ "aa", "bb", "cc", "bb",
        "aa", "aa", "aa" ];
// Function Call
replaceDuplicates(str);
 
</script>
Output: 
aa bb cc bb1 aa1 aa2 aa3

 

Time Complexity: O(N)
Auxiliary Space: O(N)

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :