Program to make file names unique using Python


Suppose we have an array of n strings called names. We have to make n directories in the file system such that, at the ith minute, we will create a directory with the name names[i]. Two files cannot have the same name, if we enter a duplicate directory name the system will have a suffix addition to its name in the form of (k), here, k is the smallest positive integer such that the obtained name remains unique. We have to find an array of strings of length n where ans[i] is the actual name that will be assign to the ith directory when we create it.

So, if the input is like names = ["my_dir","my_dir(1)","my_new_dir","my_new_dir","abc"], then the output will be ['my_dir', 'my_dir(1)', 'my_new_dir', 'my_new_dir(1)', 'abc'] because "my_new_dir" is already present once, then one (1) is added after the first one.

To solve this, we will follow these steps −

  • dic := a new map, if some key is not present then return 0

  • res := a new list

  • for each name in names, do

    • if name is not in dic, then

      • dic[name] := dic[name] + 1

      • insert name at the end of res

    • otherwise,

      • newname := name concatenate '(' concatenate dic[name] concatenate ')'

      • while newname is present in dic, do

        • dic[name] := dic[name] + 1

        • newname := name concatenate '(' concatenate dic[name] concatenate ')'

      • dic[newname] := 1

      • insert newname at the end of res

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import defaultdict
def solve(names):
   dic = defaultdict(int)
   res = []
   for name in names:
      if name not in dic:
         dic[name] += 1
         res.append(name)
      else:
         newname = name +'(' + str(dic[name]) + ')'
         while newname in dic:
            dic[name] += 1
            newname = name +'(' + str(dic[name]) + ')'
         dic[newname] = 1
         res.append(newname)
   return res
names = ["my_dir","my_dir(1)","my_new_dir","my_new_dir","abc"]
print(solve(names))

Input

["my_dir","my_dir(1)","my_new_dir","my_new_dir","abc"]

Output

['my_dir', 'my_dir(1)', 'my_new_dir', 'my_new_dir(1)', 'abc']

Updated on: 29-May-2021

884 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements