Shortest Unique Substrings
Python 3, 124 123 111 96 bytes
f=lambda s,n=1:[x for x in[s[i:i+n]for i in range(len(s)+1)]if s.find(x)==s.rfind(x)]or f(s,n+1)
Looks for strings such that the first occurrence from the left is the same as the first occurrence from the right. The +1
in the range
is to accommodate for the empty string case.
Now if only Python had a .count()
which counted overlapping matches, then this would have been a fair bit shorter.
Mathematica, 95 94 79 bytes
Cases[Tally@StringCases[#,___,Overlaps->All],{s_,1}:>s]~MinimalBy~StringLength&
StringCases
gets me all possible substrings, the Tally
and Cases
filter out those that appear more than once and MinimalBy
finds those that are shortest.
GolfScript, 44 bytes
:S;-1:x{;S,x):x-),{S>x<}%:^1/{^\/,2=},.!}do`
Takes input as a string on stdin and outputs in a double-array syntax: e.g. [["b"] ["c"]]
. Online demo
Dissection
:S; # Store input in S and pop it
-1:x # Store -1 in x
{ # do-while loop
; # Pop x the first time and [] every subsequent time
S,x):x-), # Increment x and build an array [0 1 ... len(S)-x]
{S>x<}% # Map that array to [substr(S,0,x) substr(S,1,x) ...]
:^ # Store in ^ (to avoid the token coalescing with the next char)
1/ # Split by length 1 to iterate over 1-elt arrays rather than strings
{^\/,2=}, # Filter to arrays which occur exactly once as a subarray of ^
.! # Duplicate and test emptiness
}do # end do-while loop: loop if the filtered array is empty
` # Stringify for output
This is arranged such that no special case is required for the empty string (which I've included as a test case in the online demo linked above).