Kings
INTRODUCTION: A tournament is a directed graph in which there is a single edge that connects every two vertices. If we consider any two vertices, A and B. in a tournament, there exists an edge from A to B or from B to A. To state it in math jargon, a tournament is a complete. directed graph.
In a tournament, you may have vertices that are designated as "Kings". Kings are vertices that can reach any other vertex m. the graph in two or less steps. In this case. a step is a movement from one vertex to another along an edge that connects them.
PROBLEM: Given the vertices and edges of a graph, return a string array containing the names of all "king" vertices. The vertices are described as an array of strings of the names of the vertices. The edges are described by two input string arrays, the "edgesFrom" array and the "edgesTo" array. The edge is directed from the ith element of the "edgesFrom" input array to the ith element of the "edgesTo" input array. Take the elements of these two arrays pairwise to get the edge set. Return the king vertices in alphabetical order.
The idea:
I mapped all the information into a standard adjacency list.
Then I iterated through each list, removing all the elements that correspond inside the adjacency list, and the elements within that adjacency list. In the end, if the hash set was empty (one edge also pointed to itself), or the hash set is of size one where it is not itself, it then points to all elements by a least a 2 edges.
Last updated