Program to find minimum number of people to teach in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, an array called 'languages', and an array called 'friendships', so there are n languages numbered from 1 through n, languages[i] represents a set of languages the ith user knows, and friendships[i] holds a pair [ui, vi] denotes a friendship between the users ui and vi. We can select one language and teach it to some users so that all friends can communicate with each other. We have to find the minimum number of users required to teach. (One thing we have to keep in mind that friendships are not transitive, so if x is a friend of y and y is a friend of z, this doesn't mean that x is a friend of z).

So, if the input is like n = 3 languages = [[2],[1,3],[1,2],[3]] friendships = [[1,4],[1,2],[3,4],[2,3]], then the output will be 2 because we need to train language 3 to users 1 and 3, as there are two users to teach, so output is 2.

To solve this, we will follow these steps −

  • lang := a list of all distinct set of languages known by users
  • not_comm := a new set
  • for each pair a, b in friendships, do
    • a := a - 1
    • b := b - 1
    • if lang[a] and lang[b] are disjoint, then
      • insert a into not_comm
      • insert b into not_comm
  • if not_comm is empty, then
    • return 0
  • cnt := an empty map
  • for each person in not_comm, do
    • store frequency of lang[person] and store it to cnt
  • temp := maximum of list of all values of cnt
  • return size of not_comm - temp


Let us see the following implementation to get better understanding −

from collections import Counter
def solve(n, languages, friendships):
   lang = [set(L) for L in languages]

   not_comm = set()
   for a,b in friendships:
      a -= 1
      b -= 1
      if lang[a].isdisjoint(lang[b]):
   if not not_comm:
      return 0

   cnt = Counter()
   for person in not_comm:
   temp = max(cnt.values())
   return len(not_comm) - temp

n = 3
languages = [[2],[1,3],[1,2],[3]]
friendships = [[1,4],[1,2],[3,4],[2,3]]
print(solve(n, languages, friendships))


3, [[2],[1,3],[1,2],[3]], [[1,4],[1,2],[3,4],[2,3]]


Updated on 07-Oct-2021 11:01:44