I implemented two solutions to Leetcode problem 988: one that creates a list of strings and sorts it to return the smallest (lexicographically) and another that just keeps track of the smallest throughout the generation process.
My analysis of the runtimes of the two would be O(nlogn) and O(n) respectively, so why is LeetCode telling me that the second implementation is 5ms slower overall?
Fist Solution:
class Solution: def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: d = dict(enumerate(string.ascii_lowercase)) words = [] def dfs(node, string): if not node.left and not node.right: words.append((string + d[node.val])[::-1]) if node.left: dfs(node.left, string + d[node.val]) if node.right: dfs(node.right, string + d[node.val]) dfs(root, '') return sorted(words)[0]
Second Solution:
class Solution:def smallestFromLeaf(self, root: Optional[TreeNode]) -> str: d = dict(enumerate(string.ascii_lowercase)) shortest = None def dfs(node, string): if not node.left and not node.right: nonlocal shortest if not shortest: shortest = (string + d[node.val])[::-1] else: shortest = min(shortest, (string + d[node.val])[::-1]) if node.left: dfs(node.left, string + d[node.val]) if node.right: dfs(node.right, string + d[node.val]) dfs(root, '') return shortest