Toptal | OA | Graph Path Exists
891
  • Find if there is a path from node 1 to N
  • Can only visit next node, for eg: 1 to 2, 2 to 3

Input format

[numberOfNodes, arrayA, arrayB]
(arrayA[i], arrayB[i]) means there is an edge b/w these 2 nodes

Test Cases

[
		{
			input: [4, [1, 2, 4, 4, 3], [2, 3, 1, 3, 1]],
			output: true,
		},
		{
			input: [4, [1, 2, 1, 3], [2, 4, 3, 4]],
			output: false,
		},
		{
			input: [6, [2, 4, 5, 3], [3, 5, 6, 4]],
			output: false,
		},
		{
			input: [3, [1, 3], [2, 2]],
			output: true,
		},
	]

Solution

class Graph {
	constructor() {
		this.adjacencyList = {}
	}

	addVertex(vertex) {
		if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = []
	}

	addEdge(vertex1, vertex2) {
		this.addVertex(vertex1)
		this.addVertex(vertex2)

		this.adjacencyList[vertex1].push(vertex2)
		this.adjacencyList[vertex2].push(vertex1)
	}

	findPath(N) {
		const adjacencyList = this.adjacencyList
		let current = 1
		while (current < N) {
			const edges = adjacencyList[current]
			if (edges && edges.includes(current + 1)) {
				current += 1
			} else {
				break
			}
		}
		return current === N
	}
}

function findGraphPath(N, A, B) {
	const graph = new Graph()
	const length = A.length
	for (let i = 0; i < length; i++) {
		graph.addEdge(A[i], B[i])
	}
	return graph.findPath(N)
}
Comments (1)