The Myth of “One Pass = Faster”: Python Performance 101
Is a single loop always faster than two?
Not necessarily.
Consider checking if two strings are anagrams — a classic O(n) problem.
Two popular solutions exist, but their real-world performance isn’t the same.
Option A: Fixed-Size Array (26 slots)
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
count[ord(t[i]) - ord('a')] -= 1
for v in count:
if v != 0:
return False
return True
Option B: Dictionary Comparison
countS, countT = {}, {}
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
return countS == countT
At first glance, this looks elegant:
One pass to build the dictionaries
One simple equality check at the end
However, this simplicity hides important runtime details.
The Hidden Cost
That final line:
Comments
Post a Comment