🏌🏻‍♂️TreeQuery-HUAWEI-CodingInterview⏯️

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2023-08-14Added By Anonymous
Source: Link
Huawei | Unknown | Coding Interview | Unknown | Unknown

# Topic 22-TreeQuery-HUAWEI-CodingInterview # Key Point & Tag | Key | Value | | :----: | :----: | | Difficulty Assessment | Easy | | Tag | | | Similar Problem | []()| # Code ``` class TreeQuery: # Input Part def GetInput(self)->None: ''' Get Input Data and Preprocess Data ''' self.N = int(input()) mat = [list(map(str, input().split())) for _ in range(self.N)] self.K = input().strip() # Query Key Words # mat = [ ['b', 'a'], # ['c', 'a'], # ['d', 'c'], # ['e', 'c'], # ['f', 'd']] # self.K = 'c' # Query Key Words self.dic = {} # {k1:[v1, v2]} for v, k in mat: self.dic[k] = self.dic.get(k, set()) | {v} # Union Two Set # Algorithm Part def Solution(self)->int: ''' Algorithm Solving Problem ''' # Get data from self K = self.K dic = self.dic res = [x for x in dic[K]] # each elem i = 0 while i < len(res): # res.append(q[i]) if dic.get(res[i], None): res += [x for x in dic[res[i]]] i += 1 res.sort() # ASC Sort by Lexicographical Order return '\n'.join(res) # Execution Part if __name__ == "__main__": # Instantiate obj = TreeQuery() # Get Input obj.GetInput() # Get Result print(obj.Solution()) ``` # Test Cases ``` 5 b a c a d c e c f d c ```
Comments