-
Notifications
You must be signed in to change notification settings - Fork 266
Assigning Unique Nicknames to Contestants
LeWiz24 edited this page Aug 13, 2024
·
1 revision
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.
- To assign unique nicknames by adding a suffix
- What input is provided?
- An array of strings
nicknames.
- An array of strings
- What is the desired outcome?
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`.- Not handling the case where multiple suffixes are needed.
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