8 karma · joined May 2, 2020 (6y ago) · 5 submissions
comment 6y ago · link · parent
When searching through a sorted list, your first instinct should be to use binary search. Your first instinct should not be "well maybe the list is always small, so linear search would be faster." Write the safe, predictable thing and save the optimizations for later.
comment 6y ago · link · parent
(I guess, most precisely, we should define K to be min(M + 1, N). Then the first solution is O(K^2) and the second solution is O(K))
EDIT: I assumed the first solution would compare each character to the characters visited so far, i.e.
for i in [0..N]
for j in [0..i]
if arr[i] == arr[j] return arr[i]
Maybe it's for i in [0..N]
for j in [0..N]
if arr[i] == arr[j] && i != j
return arr[i]
That would make it O(KN). Or O(N) if we treat the size of the alphabet as fixed.