Common Words Across Files
Problem statement
Given parallel arrays fileNames and contents, find every word that appears in at least two distinct files and identify all files containing it. The string contents[i] is the complete text of the file named fileNames[i].
A word is a maximal nonempty sequence of characters separated by ASCII whitespace: space, horizontal tab, line feed, vertical tab, form feed, or carriage return. Words are case-sensitive, and punctuation remains part of a word. Repeating a word within one file counts that file only once.
Return a two-dimensional string array. Each row contains the word followed by the names of all files containing that word. Sort rows by word in ascending ASCII lexicographic order, and sort the file names within each row in the same order. Return an empty array if no word occurs in at least two distinct files.
Interview context
The interview report describes reading multiple files and printing common words together with the files they belong to. This practice task receives each file's text directly; opening files and handling filesystem errors are outside the judged function.
Function
commonWordsAcrossFiles(fileNames: String[], contents: String[]) → String[][]Examples
Example 1
fileNames = ["b.txt","a.txt","c.txt"]contents = ["cat dog cat","cat bird","dog fish"]return = [["cat","a.txt","b.txt"],["dog","b.txt","c.txt"]]cat appears in a.txt and b.txt; its repeated occurrence in b.txt adds no extra membership. dog appears in b.txt and c.txt. Neither word needs to appear in all three files.
Example 2
fileNames = ["left","right"]contents = ["Cat cat, cat","cat, Cat"]return = [["Cat","left","right"],["cat,","left","right"]]Cat and cat, occur in both files. The different token cat occurs only in left. Uppercase C sorts before lowercase c.
Example 3
fileNames = ["solo"]contents = ["echo echo echo"]return = []Only one distinct file contains echo, so repetition alone does not make it a common word.
Example 4
fileNames = ["z","a","m"]contents = ["red\tblue\n","blue\rred"," \f "]return = [["blue","a","z"],["red","a","z"]]Tabs, line feeds, and carriage returns separate tokens. File m contains only whitespace and contributes no words.
Constraints
0 <= fileNames.length = contents.length <= 1000.- File names are unique. Each has length from
1to80and contains only ASCII letters, digits,_,-,., or/. - The sum of all
contents[i].lengthvalues is at most10^5. - File contents contain only printable ASCII characters or the six ASCII whitespace characters listed above. Each word has length at most
80. - A file may be empty or contain only whitespace.