Skip to content

1487. Making File Names Unique 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  vector<string> getFolderNames(vector<string>& names) {
    vector<string> ans;
    unordered_map<string, int> nameToSuffix;

    for (const string& name : names)
      if (const auto it = nameToSuffix.find(name); it != nameToSuffix.cend()) {
        int suffix = it->second;
        string newName = getName(name, ++suffix);
        while (nameToSuffix.contains(newName))
          newName = getName(name, ++suffix);
        nameToSuffix[name] = suffix;
        nameToSuffix[newName] = 0;
        ans.push_back(newName);
      } else {
        nameToSuffix[name] = 0;
        ans.push_back(name);
      }

    return ans;
  }

 private:
  string getName(const string& name, int suffix) {
    return name + "(" + to_string(suffix) + ")";
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public String[] getFolderNames(String[] names) {
    String[] ans = new String[names.length];
    Map<String, Integer> nameToSuffix = new HashMap<>();

    for (int i = 0; i < names.length; ++i) {
      final String name = names[i];
      if (nameToSuffix.containsKey(name)) {
        int suffix = nameToSuffix.get(name);
        String newName = getName(name, ++suffix);
        while (nameToSuffix.containsKey(newName))
          newName = getName(name, ++suffix);
        nameToSuffix.put(name, suffix);
        nameToSuffix.put(newName, 0);
        ans[i] = newName;
      } else {
        nameToSuffix.put(name, 0);
        ans[i] = name;
      }
    }

    return ans;
  }

  private String getName(final String name, int suffix) {
    return name + "(" + String.valueOf(suffix) + ")";
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def getFolderNames(self, names: list[str]) -> list[str]:
    ans = []
    nameToSuffix = {}

    for name in names:
      if name in nameToSuffix:
        suffix = nameToSuffix[name] + 1
        newName = self._getName(name, suffix)
        while newName in nameToSuffix:
          suffix += 1
          newName = self._getName(name, suffix)
        nameToSuffix[name] = suffix
        nameToSuffix[newName] = 0
        ans.append(newName)
      else:
        nameToSuffix[name] = 0
        ans.append(name)

    return ans

  def _getName(self, name: str, suffix: int) -> str:
    return name + '(' + str(suffix) + ')'