0% found this document useful (0 votes)
6 views16 pages

Graphs Leetcode Problems

The document outlines four algorithmic problems related to graph theory: finding a path in a bi-directional graph, identifying the center of a star graph, counting the number of provinces in a city connection matrix, and determining the town judge based on trust relationships. Each problem is accompanied by example inputs and outputs, as well as Python code solutions using BFS or DFS approaches. Constraints for each problem are also provided to guide the implementation.

Uploaded by

jashtiyamini72
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Graphs Leetcode Problems

The document outlines four algorithmic problems related to graph theory: finding a path in a bi-directional graph, identifying the center of a star graph, counting the number of provinces in a city connection matrix, and determining the town judge based on trust relationships. Each problem is accompanied by example inputs and outputs, as well as Python code solutions using BFS or DFS approaches. Constraints for each problem are also provided to guide the implementation.

Uploaded by

jashtiyamini72
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Q1.

Find if Path Exists in Graph:


There is a bi-directional graph with n
vertices, where each vertex is labeled from 0
to n - 1 (inclusive). The edges in the graph are
represented as a 2D integer array edges,
where each edges[i] = [ui, vi] denotes a bi-
directional edge between vertex ui and
vertex vi. Every vertex pair is connected by at
most one edge, and no vertex has an edge to
itself.

You want to determine if there is a valid path


that exists from vertex source to vertex
destination.

Given edges and the integers n, source, and


destination, return true if there is a valid
path from source to destination, or false
otherwise.
Example 1:

Input: n = 3, edges = [[0,1],[1,2],[2,0]],


source = 0, destination = 2
Output: true
Explanation:
There are two paths from vertex 0 to vertex
2:
-0→1→2
-0→2

Example 2:
Input: n = 6, edges =
[[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0,
destination = 5
Output: false
Explanation: There is no path from vertex 0
to vertex 5.

Constraints:
 1 <= n <= 2 * 105
 0 <= edges.length <= 2 * 105
 edges[i].length == 2
 0 <= ui, vi <= n - 1
 ui != vi
 0 <= source, destination <= n - 1
 There are no duplicate edges.
 There are no self edges.
#BFS(Breadth First Search) - Queue
from collections import deque
class Solution:
def validPath(self, n, edges, source,
destination):
graph = {node: [] for node in range(n)}

for u, v in edges:
graph[u].append(v)
graph[v].append(u)

visited = [False] * n
queue = deque([source])
visited[source] = True

while queue:
node = queue.popleft()

if node == destination:
return True

for neighbor in graph[node]:


if not visited[neighbor]:
visited[neighbor] = True
queue.append(neighbor)

return False
#DFS(Depth First Search) - Stack
class Solution:
def validPath(self, n, edges, source, destination):
graph = {node: [] for node in range(0, n, +1)}

for u, v in edges:
graph[u].append(v)
graph[v].append(u)

visited = [False] * n
stack = [source]
visited[source] = True

while stack:
node = stack.pop()

if node == destination:
return True

for neighbor in graph[node]:


if not visited[neighbor]:
visited[neighbor] = True
stack.append(neighbor)

return False
Q2. Find Center of Star Graph
There is an undirected star graph consisting of n
nodes labeled from 1 to n. A star graph is a graph
where there is one center node and exactly n - 1
edges that connect the center node with every
other node.
You are given a 2D integer array edges where each
edges[i] = [ui, vi] indicates that there is an edge
between the nodes ui and vi. Return the center of
the given star graph.

Example 1:
Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
Explanation: As shown in the figure above, node 2
is connected to every other node, so 2 is the
center.

Example 2:
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1

Constraints:
3 <= n <= 105
edges.length == n - 1
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
The given edges represent a valid star graph.
class Solution:
def findCenter(self, edges):
if edges[0][0] in edges[1]:
return edges[0][0]
else:
return edges[0][1]
Q3. Number of Provinces
There are n cities. Some of them are connected,
while some are not. If city a is connected directly
with city b, and city b is connected directly
with city c, then city a is connected indirectly
with city c.

A province is a group of directly or indirectly


connected cities and no other cities outside of the
group.

You are given an n x n matrix isConnected


where isConnected[i][j] = 1 if the ith city and
the jth city are directly connected, and
isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
Example 1:

Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]


Output: 2

Example 2:

Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]


Output: 3

Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j] is 1 or 0.
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]

#BFS
from collections import deque
class Solution:
def bfs(self, city, isConnected, visited):
queue = deque([city])
while queue:
current = queue.popleft()
# Visit all connected cities
for neighbor in
range(len(isConnected)):
if isConnected[current][neighbor]
== 1 and not visited[neighbor]:
visited[neighbor] = True
queue.append(neighbor)

def findCircleNum(self, isConnected):


n = len(isConnected) # Number of cities
visited = [False] * n # Track cities
provinces = 0
for city in range(n):
if not visited[city]:
# If the city is not visited, it's a new province
visited[city] = True
self.bfs(city, isConnected,
visited)
provinces += 1

return provinces
Q4. Find the Town Judge
In a town, there are n people labeled from 1
to n. There is a rumor that one of these
people is secretly the town judge.

If the town judge exists, then:

1.The town judge trusts nobody.


2.Everybody (except for the town judge)
trusts the town judge.
3.There is exactly one person that satisfies
properties 1 and 2.

You are given an array trust where trust[i] =


[ai, bi] representing that the person labeled
ai trusts the person labeled bi. If a trust
relationship does not exist in trust array,
then such a trust relationship
does not exist.

Return the label of the town judge if the


town judge exists and can be identified, or
return -1 otherwise.
Example 1:

Input: n = 2, trust = [[1,2]]


Output: 2

Example 2:
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3

Example 3:
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1

Constraints:
1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
All the pairs of trust are unique.
ai != bi
1 <= ai, bi <= n
class Solution:
def findJudge(self, n, trust):
if len(trust) == 0 and n == 1:
return 1
count = [0] * (n + 1)
for person in trust:
count[person[0]] -= 1
count[person[1]] += 1

for person in range(len(count)):


if count[person] == n - 1:
return person
return -1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy