Skip to content

File Naming

You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.

Return an array of names that will be given to the files.

Example

For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be

file_naming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]

Input/Output

  • [input] array.string names

    Guaranteed constraints:5 ≤ names.length ≤ 1000, 1 ≤ names[i].length ≤ 15.

Solution

py
def file_naming(names):
    new_names = []

    for name in names:
        if name in new_names:
            index = 1
            while f'{name}({index})' in new_names:
                index += 1
            name = f'{name}({index})'
        new_names.append(name)

    return new_names


print(file_naming(["doc", "doc", "image", "doc(1)", "doc"]))
js
// def file_naming(names):
//     new_names = []

//     for name in names:
//         if name in new_names:
//             index = 1
//             while f'{name}({index})' in new_names:
//                 index += 1
//             name = f'{name}({index})'
//         new_names.append(name)

//     return new_names

// print(file_naming(["doc", "doc", "image", "doc(1)", "doc"]))

function fileNaming(names) {
  const newNames = [];

  for (let name of names) {
    if (newNames.includes(name)) {
      let index = 1;
      while (newNames.includes(`${name}(${index})`)) {
        index++;
      }
      name = `${name}(${index})`;
    }
    newNames.push(name);
  }

  return newNames;
}

console.log(fileNaming(['doc', 'doc', 'image', 'doc(1)', 'doc']));

my thoughts are neither my employer's nor my wife's