Just failed a coding challenge for an interview and now im scratching my head. How can one accomplish this task?
Given a string s of length n, the task is to find the length of the shortest substring, which, upon deletion, makes the resultant string consist only of distinct characters.
Here is my total failure of code that I ran out of time on... Was I at least going down the right path?
from collections import Counterdef findShortestSubstring(s):char_freq = Counter(s)targets = {char for char, idx in char_freq.items() if idx > 1}if not targets:return 0min_len = float('inf')left = 0window_counts = Counter()for right, char in enumerate(s):if char in targets:window_counts[char] += 1while all(window_counts[char] > 0 for char in targets):min_len = min(min_len, right - left + 1)if s[left] in targets:window_counts[s[left]] -= 1left += 1return min_lenoptimized_test_results = {"aabbcc": findShortestSubstring("aabbcc"),"abcabc": findShortestSubstring("abcabc"),"abcd": findShortestSubstring("abcd"),"abba": findShortestSubstring("abba"),"aaaabbbbcccc": findShortestSubstring("aaaabbbbcccc"),"abcabcabc": findShortestSubstring("abcabcabc"),"aabacbebebe": findShortestSubstring("aabacbebebe"),"aabc": findShortestSubstring("aabc"),"abcdefghijklmnopqrstuvwxyz": findShortestSubstring("abcdefghijklmnopqrstuvwxyz"),"aaaaaaaaaaaaaaaaaaaaaaaa": findShortestSubstring("aaaaaaaaaaaaaaaaaaaaaaaa")}