#C14858. Group by Root Directory
Group by Root Directory
Group by Root Directory
You are given a list of file paths and are asked to group them by their root directories. The root directory of a file path is defined as the substring before the first occurrence of the character /
. If the file path does not contain the character /
, then the entire file path is considered its root.
For example, if you have the file paths:
( \texttt{root1/file1.txt} ), ( \texttt{root2/file2.txt} ), and ( \texttt{root1/folder1/file3.txt} ),
the resulting grouping should be
[ {\texttt{"root1" : ["root1/file1.txt", "root1/folder1/file3.txt"], "root2" : ["root2/file2.txt"]} }. ]
Your task is to implement a program that reads an integer ( n ) followed by ( n ) file paths from standard input and prints the grouping result in JSON format. The keys in the output JSON must be in lexicographical order.
inputFormat
The input is provided via standard input (stdin) and has the following format:
- The first line contains an integer ( n ) representing the number of file paths.
- Each of the following ( n ) lines contains a non-empty string that represents a file path.
outputFormat
Print to standard output (stdout) a JSON dictionary where:
- Each key is a root directory (a string).
- The value associated with a key is a list of file paths (strings) that have that root directory.
The keys in the output JSON must be sorted in lexicographical order.## sample
6
root1/file1.txt
root2/file2.txt
root1/folder1/file3.txt
root3/file4.txt
root2/folder2/file5.txt
root1/folder1/folder2/file6.txt
{"root1": ["root1/file1.txt", "root1/folder1/file3.txt", "root1/folder1/folder2/file6.txt"], "root2": ["root2/file2.txt", "root2/folder2/file5.txt"], "root3": ["root3/file4.txt"]}