LeetCode 1487: Making File Names Unique

ArrayHash TableString

Problem Description

Explanation:

  • We can iterate through the array of names and keep track of the count of each name encountered so far.
  • If a name is encountered for the first time, we add it as it is to the result array.
  • If a name has been encountered before, we append a suffix in the form of (k) to make it unique, where k is the smallest positive integer that makes the name unique.

Time complexity: O(n), where n is the number of names in the input array. Space complexity: O(n) for storing the result array.

Solutions

class Solution {
    public String[] getFolderNames(String[] names) {
        Map<String, Integer> map = new HashMap<>();
        String[] result = new String[names.length];
        
        for (int i = 0; i < names.length; i++) {
            if (!map.containsKey(names[i])) {
                result[i] = names[i];
                map.put(names[i], 1);
            } else {
                int count = map.get(names[i]);
                String newName = names[i] + "(" + count + ")";
                while (map.containsKey(newName)) {
                    count++;
                    newName = names[i] + "(" + count + ")";
                }
                result[i] = newName;
                map.put(names[i], count + 1);
                map.put(newName, 1);
            }
        }
        
        return result;
    }
}

Loading editor...