← Home

997. Find the Town Judge

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
997

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 997. Find the Town Judge, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findJudge, in, indegrees, outdegrees.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02In a town, there are N people labelled from 1 to N.  There is a rumor that one of these people is secretly the town judge.
03
04If the town judge exists, then:
05
06The town judge trusts nobody.
07Everybody (except for the town judge) trusts the town judge.
08There is exactly one person that satisfies properties 1 and 2.
09You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
10
11If the town judge exists and can be identified, return the label of the town judge.  Otherwise, return -1.
12
13 
14
15Example 1:
16
17Input: N = 2, trust = [[1,2]]
18Output: 2
19Example 2:
20
21Input: N = 3, trust = [[1,3],[2,3]]
22Output: 3
23Example 3:
24
25Input: N = 3, trust = [[1,3],[2,3],[3,1]]
26Output: -1
27Example 4:
28
29Input: N = 3, trust = [[1,2],[2,3]]
30Output: -1
31Example 5:
32
33Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
34Output: 3
35 
36
37Note:
38
391 <= N <= 1000
40trust.length <= 10000
41trust[i] are all different
42trust[i][0] != trust[i][1]
431 <= trust[i][0], trust[i][1] <= N
44**/
45
46//better
47//Runtime: 196 ms, faster than 49.32% of C++ online submissions for Find the Town Judge.
48//Memory Usage: 50.5 MB, less than 100.00% of C++ online submissions for Find the Town Judge.
49
50class Solution {
51public:
52    int findJudge(int N, vector<vector<int>>& trust) {
53        //directed graph
54        //find a node whose in-degree is N-1 and out-degree is 0
55        
56        vector<int> in(N), out(N);
57        
58        for(vector<int> edge : trust){
59            //1-based -> 0-based
60            int from = edge[0]-1, to = edge[1]-1;
61            out[from]++;
62            in[to]++;
63        }
64        
65        for(int i = 0; i < N; i++){
66            if(in[i] == N-1 && out[i] == 0){
67                //0-based -> 1-based
68                return i+1;
69            }
70        }
71        
72        return -1;
73    }
74};
75
76//Runtime: 356 ms, faster than 23.27% of C++ online submissions for Find the Town Judge.
77//Memory Usage: 60.9 MB, less than 12.50% of C++ online submissions for Find the Town Judge.
78class Solution {
79public:
80    int findJudge(int N, vector<vector<int>>& trust) {
81        if(trust.size() == 0) return (N == 1) ? 1 : -1;
82        //index 0 for padding
83        vector<int> indegrees(N+1, 0);
84        vector<int> outdegrees(N+1, 0);
85        //assume judge candidate not work!
86        // int judge = trust[0][1]; //candidate judge
87        
88        for(vector<int>& v : trust){
89            //judge doesn't trust anyone
90            // if(v[0] == judge) return -1;
91            outdegrees[v[0]]++;
92            indegrees[v[1]]++;
93        }
94        
95        set<int> cands;
96        
97        for(int i = 1; i <= N; i++){
98            //there is a person trusted by N-1 person and not judge
99            if(indegrees[i] == N-1 && outdegrees[i] == 0){
100                cands.insert(i);
101                if(cands.size() > 1) return -1;
102            }
103        }
104        
105        return cands.empty() ? -1 : *cands.begin();
106    }
107};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.