Daily Coding Day One Sixty Two

Oh beautiful, for spacious skies, for Amber waves of …

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Given a list of words, return the shortest unique prefix of each word. 
For example, given the list:

dog
cat
apple
apricot
fish
Return the list:

d
c
app
apr
f

I used a dictionary on this bad boy and am just keeping track of the count. Does not seem wildly efficient, and honestly I’m not sure I even understand the question but Wynaut:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Foundation

func prefix(_ words: [String]) -> [String] {
// dict to keep count of preix to count
var prefixCount = [String: Int]()

// Add prefixes, nothing fancy. Grab chars, Add chars
for word in words {
var prefix = ""
for char in word {
prefix += String(char)
prefixCount[prefix, default: 0] += 1
}
}

// find the lowest number, in our case 1s
var result = [String]()
for word in words {
var prefix = ""
for char in word {
prefix += String(char)
if prefixCount[prefix] == 1 {
result.append(prefix)
break
}
}
}

return result
}

Given some input
let words = ["dog", "cat", "apple", "apricot", "fish"]
and calling
print(shortestUniquePrefixes(words))
would print
["d", "c", "app", "apr", "f"]