Skip to content

Instantly share code, notes, and snippets.

@pyrofolium
Created June 22, 2020 21:55
Show Gist options
  • Save pyrofolium/400ded2f682b70e231177635f55a0558 to your computer and use it in GitHub Desktop.
Save pyrofolium/400ded2f682b70e231177635f55a0558 to your computer and use it in GitHub Desktop.
from collection import deque
def minWindow3(source, match):
counts = {}
for c in match:
counts[c] = counts[c] + 1 if c in counts else 1
lastIndexSeen = {c: deque(maxsize=counts[c]) for c in counts}
minLength = float("inf")
accMaxIndex = None
accMinIndex = None
for i, c in enumerate(lastIndexSeen):
if c in lastIndexSeen:
lastIndexSeen[c].append(i)
maxIndex = lastIndexSeen[max(lastIndexSeen, lambda key: viewTop(lastIndexSeen[c]))]
minIndex = lastIndexSeen[min(lastIndexSeen, lambda key: viewEnd(lastIndexSeen[c]))]
length = maxIndex + 1 - maxIndex
if length < minLength:
minLength = length
accMaxIndex = maxIndex
accMinIndex = minIndex
return source[accMinIndex:accMaxIndex + 1]
def viewTop(queue):
value = queue.popright()
queue.append(value)
return value
def viewEnd(queue):
value = queue.pop()
queue.appendleft(value)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment