min_window.py 1.1 KB

123456789101112131415161718192021222324252627
  1. # Given a string S and a string T,
  2. # find the minimum window in S which will contain all the characters in T in complexity O(n).
  3. # https://leetcode.com/problems/minimum-window-substring/description/
  4. def minWindow(self, s, t):
  5. # initialize a hash table to store chars and their occurances
  6. t_table = {i_t: 0 for i_t in t}
  7. for i_t in t:
  8. t_table[i_t] += 1
  9. # two pointers and the window
  10. begin, end, head = 0, 0, 0
  11. dist = float('inf')
  12. len_s = len(s)
  13. for end in range(len_s):
  14. # if the char is found in the substring, decrement by 1
  15. if s[end] in t_table:
  16. t_table[s[end]] -= 1
  17. # if all chars are found, start moving the begin pointer
  18. while all([v <= 0 for v in t_table.values()]):
  19. if s[begin] in t_table:
  20. # increment by 1 so that we can check next potential substring
  21. t_table[s[begin]] += 1
  22. # store the window if the length is min so far
  23. if end - begin < dist:
  24. head = begin
  25. dist = end - head
  26. begin += 1
  27. return s[head:(head+dist+1)] if dist < float('inf') else ''