'Python program using python class improves speed?
I'm doing another Leetcode "1202. Smallest String With Swaps". The code below managed 35/36 cases but exceeded time for one.
from collections import defaultdict
class Solution:
def smallestStringWithSwaps(self, s, pairs):
nofNode = len(s)
parents = list(range(nofNode))
def findParent(child):
if child == parents[child]: return child
else:
return findParent(parents[child])
def union(a, b):
parents[findParent(a)] = findParent(b)
for a, b in pairs:
union(a, b)
for i in range(nofNode):
parents[i] = findParent(parents[i])
dic = defaultdict(list)
for i in range(nofNode):
dic[findParent(i)].append(s[i])
for key in dic.keys():
dic[key].sort(reverse=True)
res = []
for i in range(nofNode):
res.append(dic[findParent(i)].pop())
return ''.join(res)
The way to resolve this is to create a class and move the functions into a class. Also move the parents (python list) into the class.
from collections import defaultdict
class Solution:
def smallestStringWithSwaps(self, s, pairs):
class UF:
def __init__(self, n): self.p = list(range(n))
def union(self, x, y): self.p[self.findParent(x)] = self.findParent(y)
def findParent(self, x):
if x != self.p[x]: self.p[x] = self.findParent(self.p[x])
return self.p[x]
uf = UF(len(s))
for a, b in pairs:
uf.union(a, b)
for i in range(len(s)):
uf.p[i] = uf.findParent(uf.p[i])
dic = defaultdict(list)
for i in range(len(s)):
dic[uf.findParent(i)].append(s[i])
for key in dic.keys():
dic[key].sort(reverse=True)
res = []
for i in range(len(s)):
res.append(dic[uf.findParent(i)].pop())
return ''.join(res)
Why does using a class solves improve the timing ?
Thanks !
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
