LeetCode Entry

997. Find the Town Judge

23.01.2023 easy 2023 kotlin

fun findJudge(n: Int, trust: Array): Int {

997. Find the Town Judge easy

https://t.me/leetcode_daily_unstoppable/95

blog post

    fun findJudge(n: Int, trust: Array<IntArray>): Int {
        val judges = mutableMapOf<Int, MutableSet<Int>>()
        for (i in 1..n) judges[i] = mutableSetOf()
        val notJudges = mutableSetOf<Int>()
        trust.forEach { (from, judge) ->
            judges[judge]!! += from
            notJudges += from
        }
        judges.forEach { (judge, people) ->
            if (people.size == n - 1
                && !people.contains(judge)
                && !notJudges.contains(judge))
                return judge
        }
        return -1
    }

We need to count how much trust have each judge and also exclude all judges that have trust in someone.

  • use map and set
  • there is a better solution with just counting of trust, but it is not that clear to understand and prove

Space: O(max(N, T)), Time: O(max(N, T))