Open In App

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

Last Updated : 21 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N strings, the task is to modify the array by replacing the duplicate strings by appending any 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 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 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 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 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 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 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 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 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 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 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) 



Similar Reads

Append X digits to the end of N to make it divisible by M
Given three positive integers N, M, and X, the task is to generate a number by appending X digits on the right side of N such that the number is divisible by M. If multiple solutions exist, then print any of them. Otherwise, print -1. Examples: Input: N = 10, M = 5, X = 4 Output: 105555 Explanation: One of possible values of N (= 10) by appending X
6 min read
Minimum digits to be removed to make either all digits or alternating digits same
Given a numeric string str, the task is to find the minimum number of digits to be removed from the string such that it satisfies either of the below conditions: All the elements of the string are the same.All the elements at even position are same and all the elements at the odd position are same, which means the string is alternating with the equ
7 min read
Append a digit in the end to make the number equal to the length of the remaining string
Given a string str in which an integer is appended in the end (with or without leading zeroes). The task is to find a single digit from the range [0, 9] that must be appended in the end of the integer so that the number becomes equal to the length of remaining string. Print -1 if its not possible.Examples: Input: str = "geeksforgeeks1" Output: 3 Le
8 min read
Print all unique digits present in concatenation of all array elements in the order of their occurrence
Given an array arr[] consisting of N integers, the task is to print all unique digits of the number formed by concatenating all array elements in the order of their occurrence after excluding leading zeroes. Examples: Input: arr[] = {122, 474, 612, 932}Output: 7 6 9 3Explanation:The number formed by concatenating array elements is “122474612932”.Un
10 min read
Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULL Output : 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; 4 -&gt; 2 -&gt; NULL Input : 1
11 min read
Given a linked list, reverse alternate nodes and append at the end
Given a linked list, reverse alternate nodes and append them to the end of the list. Extra allowed space is O(1) Examples: Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6 Output: 1-&gt;3-&gt;5-&gt;6-&gt;4-&gt;2 Explanation: Two lists are 1-&gt;3-&gt;5 and 2-&gt;4-&gt;6, reverse the 2nd list: 6-&gt;4-&gt;2. Merge the lists Input: 12-&gt;14-&gt;16-&gt;18-&gt;
11 min read
Find the average of k digits from the beginning and l digits from the end of the given number
Given three integers N, K and L. The task is to find the average of the first K digits and the last L digits of the given number N without any digit overlapping.Examples: Input: N = 123456, K = 2, L = 3 Output: 3.0 Sum of first K digits will be 1 + 2 = 3 Sum of last L digits will be 4 + 5 + 6 = 15 Average = (3 + 15) / (2 + 3) = 18 / 5 = 3Input: N =
13 min read
Minimize deletion or append to make consecutive occurrence of all elements equal
Given an array arr[] of size N having positive elements, the task is to find the minimum number of deletion or append operations to make consecutive occurrences of all elements equal. Examples: Input: N = 4, arr[] = {1, 1, 2, 2}Output: 0Explanation: All the consecutive elements have the same value and same frequency already. Therefore, no operation
15 min read
C++ Program for Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second cha
3 min read
Java Program for Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second cha
3 min read