Append Suffix

Last Updated : 16 Jul, 2026

Given an array arr[] of strings containing lowercase English letters. For each string, if it has already appeared earlier in the array, append a suffix equal to the number of its previous occurrences.

Examples:

Input: arr[] = ["aba", "ab", "aba", "aba", "ab"]
Output: ["aba", "ab", "aba1", "aba2", "ab1"]
Explanation:
"aba" appears for the 1st time, so it remains "aba".
"ab" appears for the 1st time, so it remains "ab".
"aba" has appeared once before, so it becomes "aba1".
"aba" has appeared twice before, so it becomes "aba2".
"ab" has appeared once before, so it becomes "ab1".

Input: arr[] = ["geek", "geeks", "geeky", "geeks"]
Output: ["geek", "geeks", "geeky", "geeks1"]
Explanation: Only "geeks" appears more than once, so its second occurrence becomes "geeks1".

[Naive Approach] Count Previous Occurrences by Linear Search

The idea is to process each string one by one. For every string, scan all previously processed strings and count how many times it has already appeared. If the count is 0, keep the string unchanged; otherwise, append the count as a suffix.

Working of Approach:

  • Traverse the array from left to right and process one string at a time.
  • For the current string, scan all previously processed strings and count how many times it has already appeared.
  • If the count is 0, add the string unchanged to the result array.
  • Otherwise, append the count as a suffix (e.g., "geeks" -> "geeks1") and add it to the result.
  • Repeat this process for every string until the entire array is processed.
C++
#include <iostream>
#include <vector>
using namespace std;

vector<string> appendSuffix(vector<string> &arr)
{
    vector<string> res;

    // Process each string
    for (int i = 0; i < arr.size(); i++)
    {

        int cnt = 0;

        // Count previous occurrences
        for (int j = 0; j < i; j++)
        {
            if (arr[j] == arr[i])
                cnt++;
        }

        // Append suffix if required
        if (cnt == 0)
            res.push_back(arr[i]);
        else
            res.push_back(arr[i] + to_string(cnt));
    }

    return res;
}

int main()
{
    vector<string> arr = {"geek", "geeks", "geeky", "geeks"};

    vector<string> res = appendSuffix(arr);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "\"" << res[i] << "\"";
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}
Java
import java.util.*;

class GFG {

    static ArrayList<String> appendSuffix(String[] arr)
    {
        ArrayList<String> res = new ArrayList<>();

        // Process each string
        for (int i = 0; i < arr.length; i++) {

            int cnt = 0;

            // Count previous occurrences
            for (int j = 0; j < i; j++) {
                if (arr[j].equals(arr[i]))
                    cnt++;
            }

            // Append suffix if required
            if (cnt == 0)
                res.add(arr[i]);
            else
                res.add(arr[i] + cnt);
        }

        return res;
    }

    public static void main(String[] args)
    {
        String[] arr
            = { "geek", "geeks", "geeky", "geeks" };

        ArrayList<String> res = appendSuffix(arr);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i != res.size() - 1)
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
def appendSuffix(arr):
    res = []

    # Process each string
    for i in range(len(arr)):

        cnt = 0

        # Count previous occurrences
        for j in range(i):
            if arr[j] == arr[i]:
                cnt += 1

        # Append suffix if required
        if cnt == 0:
            res.append(arr[i])
        else:
            res.append(arr[i] + str(cnt))

    return res


if __name__ == "__main__":
    arr = ["geek", "geeks", "geeky", "geeks"]

    res = appendSuffix(arr)

    print("[", end="")
    for i in range(len(res)):
        print(f'"{res[i]}"', end="")
        if i != len(res) - 1:
            print(", ", end="")
    print("]")
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<string> appendSuffix(string[] arr)
    {
        List<string> res = new List<string>();

        // Process each string
        for (int i = 0; i < arr.Length; i++) {
            int cnt = 0;

            // Count previous occurrences
            for (int j = 0; j < i; j++) {
                if (arr[j] == arr[i])
                    cnt++;
            }

            // Append suffix if required
            if (cnt == 0)
                res.Add(arr[i]);
            else
                res.Add(arr[i] + cnt);
        }

        return res;
    }

    static void Main()
    {
        string[] arr
            = { "geek", "geeks", "geeky", "geeks" };

        List<string> res = appendSuffix(arr);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i != res.Count - 1)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
JavaScript
function appendSuffix(arr)
{
    let res = [];

    // Process each string
    for (let i = 0; i < arr.length; i++) {

        let cnt = 0;

        // Count previous occurrences
        for (let j = 0; j < i; j++) {
            if (arr[j] === arr[i])
                cnt++;
        }

        // Append suffix if required
        if (cnt === 0)
            res.push(arr[i]);
        else
            res.push(arr[i] + cnt);
    }

    return res;
}

// Driver code
const arr = [ "geek", "geeks", "geeky", "geeks" ];

const res = appendSuffix(arr);

process.stdout.write("[");
for (let i = 0; i < res.length; i++) {
    process.stdout.write(`"${res[i]}"`);
    if (i !== res.length - 1)
        process.stdout.write(", ");
}
console.log("]");

Output
["geek", "geeks", "geeky", "geeks1"]

Time Complexity: O(n ^ 2 * L), as each string is compared with all previous strings, and each comparison takes O(L) time.
Auxiliary Space: O(1), excluding the output array.

[Expected Approach] Using Hash Map to Store Frequencies

The idea is to use a hash map to store the number of times each string has already appeared. While traversing the array, if a string appears for the first time, add it unchanged to the result. Otherwise, append its current occurrence count as a suffix and then update its frequency in the hash map.

Working of Approach:

  • Create a hash map to store the number of times each string has appeared so far.
  • Traverse the array one string at a time from left to right.
  • If the current string is appearing for the first time, add it unchanged to the result array.
  • Otherwise, append its current occurrence count as a suffix (e.g., "geeks" -> "geeks1") and add it to the result.
  • Increment the frequency of the current string in the hash map and continue until all strings are processed.

Let us understand with an example:
Input: arr[] = ["geek", "geeks", "geeky", "geeks"]

  • Start: m = {}, res = []
  • Process "geek" -> first occurrence, add "geek" -> res = ["geek"], m["geek"] = 1
  • Process "geeks" -> first occurrence, add "geeks" -> res = ["geek", "geeks"], m["geeks"] = 1
  • Process "geeky" -> first occurrence, add "geeky" -> res = ["geek", "geeks", "geeky"], m["geeky"] = 1
  • Process "geeks" again -> already appeared once, add "geeks1" -> res = ["geek", "geeks", "geeky", "geeks1"], then update m["geeks"] = 2
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

vector<string> appendSuffix(vector<string> &arr)
{
    unordered_map<string, int> m;
    vector<string> res;

    // Process each string
    for (string &s : arr)
    {

        // First occurrence
        if (m[s] == 0)
        {
            res.push_back(s);
        }

        // Append occurrence count as suffix
        else
        {
            res.push_back(s + to_string(m[s]));
        }

        // Update occurrence count
        m[s]++;
    }

    return res;
}

int main()
{
    vector<string> arr = {"geek", "geeks", "geeky", "geeks"};

    vector<string> res = appendSuffix(arr);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "\"" << res[i] << "\"";
        if (i != res.size() - 1)
            cout << ", ";
    }
    cout << "]";

    return 0;
}
Java
import java.util.*;

class GFG {

    static ArrayList<String> appendSuffix(String[] arr)
    {
        HashMap<String, Integer> map = new HashMap<>();
        ArrayList<String> res = new ArrayList<>();

        // Process each string
        for (String s : arr) {

            // First occurrence
            if (map.getOrDefault(s, 0) == 0) {
                res.add(s);
            }

            // Append occurrence count as suffix
            else {
                res.add(s + map.get(s));
            }

            // Update occurrence count
            map.put(s, map.getOrDefault(s, 0) + 1);
        }

        return res;
    }

    public static void main(String[] args)
    {
        String[] arr
            = { "geek", "geeks", "geeky", "geeks" };

        ArrayList<String> res = appendSuffix(arr);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i != res.size() - 1)
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
def appendSuffix(arr):
    mp = {}
    res = []

    # Process each string
    for s in arr:

        # First occurrence
        if mp.get(s, 0) == 0:
            res.append(s)

        # Append occurrence count as suffix
        else:
            res.append(s + str(mp[s]))

        # Update occurrence count
        mp[s] = mp.get(s, 0) + 1

    return res


if __name__ == "__main__":
    arr = ["geek", "geeks", "geeky", "geeks"]

    res = appendSuffix(arr)

    print("[", end="")
    for i in range(len(res)):
        print(f'"{res[i]}"', end="")
        if i != len(res) - 1:
            print(", ", end="")
    print("]")
C#
using System;
using System.Collections.Generic;

class GFG {
    static List<string> appendSuffix(string[] arr)
    {
        Dictionary<string, int> map
            = new Dictionary<string, int>();
        List<string> res = new List<string>();

        // Process each string
        foreach(string s in arr)
        {
            // First occurrence
            if (!map.ContainsKey(s) || map[s] == 0) {
                res.Add(s);
            }

            // Append occurrence count as suffix
            else {
                res.Add(s + map[s]);
            }

            // Update occurrence count
            if (map.ContainsKey(s))
                map[s]++;
            else
                map[s] = 1;
        }

        return res;
    }

    static void Main()
    {
        string[] arr
            = { "geek", "geeks", "geeky", "geeks" };

        List<string> res = appendSuffix(arr);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i != res.Count - 1)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
JavaScript
function appendSuffix(arr)
{
    const map = new Map();
    const res = [];

    // Process each string
    for (const s of arr) {

        // First occurrence
        if (!map.has(s) || map.get(s) === 0) {
            res.push(s);
        }

        // Append occurrence count as suffix
        else {
            res.push(s + map.get(s));
        }

        // Update occurrence count
        map.set(s, (map.get(s) || 0) + 1);
    }

    return res;
}

// Driver code
const arr = [ "geek", "geeks", "geeky", "geeks" ];

const res = appendSuffix(arr);

process.stdout.write("[");
for (let i = 0; i < res.length; i++) {
    process.stdout.write(`"${res[i]}"`);
    if (i !== res.length - 1)
        process.stdout.write(", ");
}
console.log("]");

Output
["geek", "geeks", "geeky", "geeks1"]

Time Complexity: O(n * L), as each string is processed once, and each hash map operation takes O(L) time on average.
Auxiliary Space: O(n * L), for storing the frequencies of all distinct strings in the hash map.

Comment