The minimum window substring problem from leetcode.com asks:
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity \$O(n)\$.
For example,
S =
"ADOBECODEBANC"
T ="ABC"
Minimum window is
"BANC"
.
I post two versions of code. The differences between two versions of code is, the first one will move the start index when there is a match, the 2nd version will not move the start index when there is a move.
Wondering if logics are both correct? If both have the correct logic, which one do you think has better performance? I have did basic testing and post my test cases below. Using Python 2.7.
from collections import defaultdict
import sys
def minWindow(source, pattern):
targetCount = defaultdict(int)
currentCount = defaultdict(int)
for ch in pattern:
targetCount[ch] += 1
start = 0
validCount = 0
minSize = sys.maxint
for index in range(len(source)):
if source[index] not in targetCount:
continue
if currentCount[source[index]] < targetCount[source[index]]:
validCount += 1
currentCount[source[index]] += 1
while validCount == len(targetCount):
if source[start] not in targetCount:
start += 1
elif currentCount[source[start]] > targetCount[source[start]]:
currentCount[source[start]] -= 1
start += 1
else:
minSize = min(minSize, index-start+1)
currentCount[source[start]] -= 1
validCount -= 1
start += 1
return (minSize, start-1)
def minWindowv2(source, pattern):
targetCount = defaultdict(int)
currentCount = defaultdict(int)
for ch in pattern:
targetCount[ch] += 1
start = 0
validCount = 0
minSize = sys.maxint
for index in range(len(source)):
if source[index] not in targetCount:
continue
if currentCount[source[index]] < targetCount[source[index]]:
validCount += 1
currentCount[source[index]] += 1
while validCount == len(targetCount):
if source[start] not in targetCount:
start += 1
elif currentCount[source[start]] > targetCount[source[start]]:
currentCount[source[start]] -= 1
start += 1
else:
minSize = min(minSize, index-start+1)
break
return (minSize, start)
if __name__ == "__main__":
print minWindow("ADOBECODEBANC","ABC")
print minWindowv2("ADOBECODEBANC", "ABC")