Understand what the interviewer is asking for by using test cases and questions about the problem.
(k)
if a requested nickname is already taken.nicknames
.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
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