Created
September 4, 2015 01:44
-
-
Save ejcer/32ebf957ad5790b56fd1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getShortestUniqueSubstring(arr, str): | |
t = 0 | |
result = null | |
uniqueCounter = 0 | |
countMap = new Map() | |
# initialize countMap: | |
for i from 0 to length(arr)-1: | |
countMap.setValueOf(arr[i], 0) | |
# scan str | |
for h from 0 to length(str)-1: | |
# handle the new head | |
head = str.charAt(h) | |
if countMap.keyExists(head) == false: | |
continue | |
headCount = countMap.getValueOf(head) | |
if headCount == 0: | |
uniqueCounter = uniqueCounter + 1 | |
countMap.setValueOf(head, headCount + 1) | |
# push tail forward | |
while uniqueCounter == length(arr): | |
tempLength = h - t + 1 | |
if tempLength == arr.length: | |
return str.substring(t, h) | |
if (!result or tempLength < length(result)): | |
result = str.substring(t, h) | |
tail = str.charAt(t) | |
if countMap.keyExists(tail): | |
tailCount = countMap.getValueOf(tail) - 1 | |
if tailCount == 0: | |
uniqueCounter = uniqueCounter - 1 | |
countMap.setValueFor(tail, tailCount) | |
t = t + 1 | |
return result | |
given arr of unique characters and string str, find the shortest | |
substring that contains all the characters from arr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment