26/06/2021

[Java] Shortest unique substring

Given an array of unique characters and a string, find the shortest substring containing all the characters in the array.

Example: 

['a','b','c'] and "lol" is empty string

['a','b','c'] and "abc" is empty "abc"
['a','b','c'] and "abbbbca" is empty "bca"

We add all characters in the array to a set and use a sliding window technique where we keep increasing our end range until we have found all missing characters. If we encounter a character that is not valid (was not in the input array), we restart from the next (jump window start to end + 1 to skip this invalid character).

For each character we find, we track the last known position in a map.

When we have found all missing characters, we update best minimum so far, then we try to decrease substring by advancing window start and checking if we still have a valid string.

The character to evict (pointed at by window start range) must appear after the new window start, we continue until possible. 

We get a O(N) time and space solution.

You can check my implementation of getShortestUniqueSubstring on my Gist along with some tests in GetShortestUniqueSubstringJTests.

No comments:

Post a Comment

With great power comes great responsibility