379. Most Common Lab Tool Pair
Most Common Lab Tool Pair
A school records the laboratory tools used during science experiments. The experiment records are grouped by class.
Each experiment is represented by a comma-separated string of tool names. Find the pair of different tools used together in the greatest number of experiments.
Implement the following method:
List<String> mostCommonToolPair( List<List<String>> experimentLogs )
  • experimentLogs.get(i) contains the experiments conducted by the ith class.
  • Each experiment is a comma-separated string such as "beaker,dropper,flask".
  • The method returns the two tool names in lexicographical order.

Rules

  • A pair must contain two different tools.
  • The pairs ("beaker", "flask") and ("flask", "beaker") are considered the same.
  • A repeated tool within the same experiment is considered only once.
  • One experiment may contribute several different tool pairs.
  • A pair's frequency is the number of experiments containing both tools.
  • If several pairs have the highest frequency, return the lexicographically smallest pair.
  • Compare pairs by their first tool name and then by their second tool name.

Constraints

  • 1 ≤ experimentLogs.size() ≤ 1,000
  • 1 ≤ experimentLogs.get(i).size() ≤ 1,000
  • The total number of experiments does not exceed 100,000.
  • Each experiment contains between 1 and 50 tool entries.
  • 1 ≤ toolName.length() ≤ 30
  • Tool names contain lowercase English letters only.
  • At least one experiment contains two different tools.

Examples

Example 1

mostCommonToolPair( experimentLogs = List.of( List.of( "microscope,slide,stain", "beaker,stirrer" ), List.of("slide,stain"), List.of("stain,slide,pipette"), List.of("microscope,slide") ) )
Output: List.of("slide", "stain")
The tools "slide" and "stain" occur together in three experiments, more than any other pair.

Example 2

mostCommonToolPair( experimentLogs = List.of( List.of("clamp,clamp,stand,burner"), List.of("stand,burner"), List.of("clamp,stand") ) )
Output: List.of("burner", "stand")
Both ("burner", "stand") and ("clamp", "stand") occur twice. The first pair is lexicographically smaller. The repeated "clamp" in the first experiment does not increase any pair's frequency.

Example 3

mostCommonToolPair( experimentLogs = List.of( List.of("funnel,spatula"), List.of("goggles,tripod"), List.of("tripod,goggles"), List.of("spatula,funnel") ) )
Output: List.of("funnel", "spatula")
The pairs ("funnel", "spatula") and ("goggles", "tripod") each occur twice. The pair beginning with "funnel" is lexicographically smaller.


Please use Laptop/Desktop or any other large screen to add/edit code.