Problem solution · Java

Minimum Number of People to Teach

Minimum Number of People to Teach: a Java solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Hash-based lookup
Source
walkccc LeetCode Solutions
Length
41 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Hash-based lookup

For Minimum Number of People to Teach, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 41 lines of Java from the credited upstream file 1733.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 6 loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Number of People to Teach · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int minimumTeachings(int n, int[][] languages, int[][] friendships) {    List<Set<Integer>> languageSets = new ArrayList<>();    Set<Integer> needTeach = new HashSet<>();    Map<Integer, Integer> languageCount = new HashMap<>();     for (int[] language : languages)      languageSets.add(new HashSet<>(Arrays.stream(language).boxed().toList()));     // Find friends that can't communicate.    for (int[] friendship : friendships) {      final int u = friendship[0] - 1;      final int v = friendship[1] - 1;      if (cantTalk(languageSets, u, v)) {        needTeach.add(u);        needTeach.add(v);      }    }     // Find the most popular language.    for (int u : needTeach)      for (final int language : languageSets.get(u))        languageCount.merge(language, 1, Integer::sum);     // Teach the most popular language to people who don't understand.    int maxCount = 0;    for (int freq : languageCount.values())      maxCount = Math.max(maxCount, freq);     return needTeach.size() - maxCount;  }   // Returns true if u can't talk with v.  private boolean cantTalk(List<Set<Integer>> languageSets, int u, int v) {    for (int language : languageSets.get(u))      if (languageSets.get(v).contains(language))        return false;    return true;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗