Codepath

Assigning Unique Nicknames to Contestants

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
    • To assign unique nicknames by adding a suffix (k) if a requested nickname is already taken.
    • What input is provided?
    • An array of strings nicknames.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use a dictionary to keep track of the count of each nickname and assign unique nicknames by adding the smallest possible suffix.

1) Initialize a dictionary `nickname_count` to store the count of each nickname.
2) Iterate through `nicknames`:
   - If the nickname is not in `nickname_count`, add it to `result`.
   - If the nickname is already taken, find the smallest suffix `(k)` that makes it unique and add it to `result`.
3) Update the counts in `nickname_count` and return `result`.

⚠️ Common Mistakes

  • Not handling the case where multiple suffixes are needed.

I-mplement

def assign_unique_nicknames(nicknames):
    nickname_count = {}
    result = []

    for nickname in nicknames:
        if nickname not in nickname_count:
            result.append(nickname)
            nickname_count[nickname] = 1
        else:
            k = nickname_count[nickname]
            new_nickname = f"{nickname}({k})"
            while new_nickname in nickname_count:
                k += 1
                new_nickname = f"{nickname}({k})"
            result.append(new_nickname)
            nickname_count[nickname] = k + 1
            nickname_count[new_nickname] = 1

    return result
Fork me on GitHub