Skip to content

Instantly share code, notes, and snippets.

@pyrofolium
Created June 22, 2020 20:55
Show Gist options
  • Save pyrofolium/bcfe80586496b53ebdc8ae3594f71a1a to your computer and use it in GitHub Desktop.
Save pyrofolium/bcfe80586496b53ebdc8ae3594f71a1a to your computer and use it in GitHub Desktop.
"""
lastIndexWhereLetterWasSeen
{
A: 8
C: 11
D: 10
}
"""
# source: "ABCODEBANC"
# match: "ABC"
# O(mn)
def minWindow(source: str, match: str) -> str:
letters = set([i for i in match])
lastIndexWhereLetterWasSeen = {}
minLength = float("inf")
acc_startingIndex = None
acc_endingIndex = None
for index, c in enumerate(source):
if c in letters:
lastIndexWhereLetterWasSeen[c] = index
endingLetter = max(lastIndexWhereLetterWasSeen, key = lambda key: lastIndexWhereLetterWasSeen[key])
EndingIndex = lastIndexWhereLetterWasSeen[endingLetter] if endingLetter in lastIndexWhereLetterWasSeen else None
startingLetter = min(lastIndexWhereLetterWasSeen, key = lambda key: lastIndexWhereLetterWasSeen[key])
startingIndex = lastIndexWhereLetterWasSeen[startingLetter] if startingLetter in lastIndexWhereLetterWasSeen else None
length = EndingIndex + 1 - startingIndex
if length < minLength and len(lastIndexWhereLetterWasSeen) == len(match):
minLength = length
acc_startingIndex = startingIndex
acc_endingIndex = EndingIndex
return source[acc_startingIndex: acc_endingIndex + 1]
print(minWindow("ADABCDEBANC", "ADB"))
# def say_hello():
# print('Hello, World')
# for i in range(5):
# say_hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment