Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none).
Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none).
def judge(n, trust):
score = [0] * (n + 1)
for a, b in trust:
score[a] -= 1; score[b] += 1
for i in range(1, n + 1):
if score[i] == n - 1: return i
return -1
print(judge(3, [[1, 3], [2, 3]]), judge(3, [[1, 3], [2, 3], [3, 1]]), judge(1, []))What is printed?- A. 3 3 1
- B. 3 -1 -1
- C. 3 -1 1
- D. -1 -1 1
Correct answer: C. 3 -1 1
Score = in-degree − out-degree. The judge has in-degree n − 1 and out-degree 0, so score n − 1, and nobody else can reach it. In the second case 3 trusts 1, so its score is 1. With one person and no trust, that person is the judge (n − 1 = 0). O(n + E).
More Coding Interview Problems questions
- Problem: Find the cheapest network latency to reach all nodes from node k (network delay = max shortest distance). python import heapq def…
- Problem: Clone check – count how many nodes a BFS reaches from node 0 in a directed graph that contains a cycle. python from collections…
- Problem: Print a matrix in spiral order (clockwise from the top-left). cpp vector<int> spiral(vector<vector<int>>& m) { vector<int> out…
- Problem: Rotate an n × n image 90° clockwise in place. python def rotate(m): n = len(m) for i in range(n): for j in range(i + 1, n)…
- Problem: Set the whole row and column to 0 for every 0 in a matrix. python def zeroes(m): R, C = len(m), len(m[0]) rows = {r for r in…
- Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting. java static int majority(int[]…