Problem overview
The function firstRepeat receives an array of integers, nums. Reading from left to right, it returns the first value that appears for the second time. If no value appears twice, it returns -1.
The answer depends on where the second occurrence is, not the first. For [3, 1, 4, 1, 3], the second 1 (index 3) comes before the second 3 (index 4), so the answer is 1, although 3 appeared first. For [2, 7, 9] nothing repeats, so the result is -1, and for [6, 6, 6, 6] the second 6, at index 1, is already a repeat, so the answer is 6.
Approach: remember what you have seen
Keep a set of the values met so far. For each number, ask whether it is already in the set. If it is, this is its second time, and because the loop reads from the left, no earlier number could have repeated first, so return it. If it isn't, add it and move on.
The check on a set is fast, so the whole scan takes one pass. The slower alternative compares each number with all the ones before it.
Step by step
- Create an empty
Set<Int>namedseen, withvar, because values are added to it. - Loop over
numswithfor num in nums. - Check first: if
seen.contains(num), returnnum. - Then add the number with
seen.insert(num). - Return -1 after the loop, which means the loop never found a repeat.
The solution in Swift
class Solution {
func firstRepeat(_ nums: [Int]) -> Int {
var seen = Set<Int>()
for num in nums {
if seen.contains(num) {
return num
}
seen.insert(num)
}
return -1
}
}
Swift details
- Check, then insert. If the number were inserted first, every number would be found in
seen, even on its first appearance, and the function would return the first element every time. insertreturns a tuple.seen.insert(num)returns(inserted: Bool, memberAfterInsert: Int), andinsertedisfalsewhen the value was already present. The lesson ignores that result and usescontains. Swift marksinsertas discardable, so ignoring the result gives no warning. A common shortcut isif !seen.insert(num).inserted { return num }, which checks and adds in one call.- The empty set.
Set<Int>()names the element type, because there are no values yet to infer it from. - Early return. A
returninside the loop ends the whole function, so the rest of the array is never read.
Complexity
Time: O(n) on average. The loop runs at most n times, and contains and insert take constant time on average.
Space: O(n). In the worst case, when nothing repeats, the set holds every value.
Edge cases and common mistakes
- No repeat.
[2, 7, 9]returns -1. The lesson's numbers are never negative, so -1 can't be confused with a real answer. - The repeat that comes first.
[3, 1, 4, 1, 3]returns 1, not 3: judge by the second occurrence. - Immediate repeat.
[6, 6, 6, 6]returns 6 at index 1. - A single number.
[5]returns -1. - Inserting before checking. It makes the first number come back as a repeat.
Testing
[3, 1, 4, 1, 3]gives 1.[2, 7, 9]gives -1.[6, 6, 6, 6]gives 6.[5]gives -1.
