I was solving a question today on Leetcode named Lexicographically Smallest Equivalent String
(link) and I came up with a solution of DFS with some customization to solve the problem and here's is my code.
#!/usr/bin/python3
from collections import defaultdict, OrderedDict
class Solution:
def DFSMap(self, node, map, adj, visited):
if node not in visited:
visited.add(node)
for i in adj[node]:
map[node]=min(map[node] or "z", node, self.DFSMap(i, map, adj, visited))
return map[node]
else:
return map[node] or node
def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:
referenceMap = defaultdict(set)
d=OrderedDict()
n=len(s1)
for i in range(n):
referenceMap[s2[i]].add(s1[i])
referenceMap[s1[i]].add(s2[i])
for j in sorted(referenceMap.items(),key=lambda x:x[0]):
d[j[0]]=j[1]
m=defaultdict(lambda:None)
visited=set()
for i in d:
if i not in visited:
self.DFSMap(i,m,d,visited)
res=""
print(m)
for i in baseStr:
res+=(m[i] or i)
return res
if __name__ == "__main__":
s1=input()
s2=input()
baseStr=input()
s=Solution().smallestEquivalentString(s1, s2, baseStr)
print(s)
The issue I'm facing is, for every run of the same code, I get a different output of hashmap without usage of random
functionalities in my code. Here are few snippets of the outputs.
On other run I get,
Is it the issue with recursion or any logical error?
Could someone help me figure out the reason for this with an explanation?
The output for the input s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
was supposed to be "aauaaaaada"
but that isn't happening certainly and consistently.