Commit 7a30307
Changed files (1)
spec/first_duplicate_spec.rb
@@ -2,8 +2,8 @@
Note: Write a solution with O(n) time complexity and O(1) additional space complexity,
since this is what you would be asked to do during a real interview.
-Given an array a that contains only numbers in the range from 1 to a.length,
-find the first duplicate number for which the second occurrence has the minimal index.
+Given an array a that contains only numbers in the range from 1 to a.length,
+find the first duplicate number for which the second occurrence has the minimal index.
In other words, if there are more than 1 duplicated numbers,
return the number for which the second occurrence has a smaller index than the second occurrence of the other number does.
If there are no such elements, return -1.
@@ -36,19 +36,24 @@ DOC
describe "first_duplicate" do
def first_duplicate(items)
- head, tail = 0, items.size - 1
+ head, tail = 0, 1
min = -1
+ n = items.size
- until head == (items.size - 1) || head == min
+ until head == (n - 1) || head == min
+ puts [items[head], items[tail]].inspect
if items[head] == items[tail]
min = min < 0 ? tail + 1 : [min, tail + 1].min
+ puts ['match', items[head], items[tail], min].inspect
head += 1
+ tail = head + 1
break if tail == head
else
- tail -= 1
- if tail == head
- tail = items.size - 1
+ tail += 1
+ break if min >= 0 && tail > min
+ if tail == n
head += 1
+ tail = head + 1
end
end
end