Similar Problems

Similar Problems not available

Making File Names Unique - Leetcode Solution

Companies:

LeetCode:  Making File Names Unique Leetcode Solution

Difficulty: Medium

Topics: string hash-table array  

Problem Statement:

Given an array of strings files, where each file[i] is formatted as " {unique_id} {name}.txt", generate a list of all the files that share the same name and their corresponding paths. For each group of files that share the same name, you must generate a list of their absolute file paths. You may return the answer in any order.

A path is a string that represents the directory tree where a file is located. The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string "" and "/" are not.

Example:

Input: files = ["1.txt","2.txt","3.txt","4.txt","5.txt"] Output: ["1.txt","2.txt","3.txt","4.txt","5.txt"] Explanation: No two files share the same name in the given input files.

Approach:

The given problem can be solved using a hash table. We can use the dictionary to store the file names as keys and the list of corresponding file paths as values. While iterating through the file names, we can split them into unique_id and name. Then, we can check if there are any files with the same name already stored in the dictionary. If yes, we can append the current file path to the corresponding key. If no, we can add a new key-value pair to the dictionary with the name as the key and the current file path as the value.

After iterating through all the files, we can traverse through the dictionary and convert the dictionary values into a list of file paths for each key. Finally, we can return the list of file paths.

Code:

def findDuplicate(paths): d = {} for path in paths: split_list = path.split() path_str = split_list[0] for s in split_list[1:]: name, content = s.split("(") if name not in d: d[name] = [] d[name].append(path_str + "/" + content[:-1]) return [d[key] for key in d if len(d[key]) > 1]

Making File Names Unique Solution Code

1