Problem overview
The method contains takes an array of integers nums and an integer value. It returns true if value occurs anywhere in nums and false otherwise. For [1, 2, 4, 5] and 4 the answer is true. For [-1, 2, -4, 0, 10] and 7 it is false.
The task is to write the search yourself rather than call the array's built-in contains, so the loop is the whole point.
Approach: look at every element until you find it
Nothing is known about the order of the array, so the only way to be sure a value is missing is to look at every element. This is a linear search. Start at the first element and compare each one with value. The first match settles the question, so the method can return true at once. If the loop ends without a match, every element has been ruled out, and the answer is false.
The answer false can only be given after the loop, never inside it. One element that differs from value says nothing about the rest.
Step by step
- Loop over the array with
for num in nums. This visits each element in order and gives it the namenum. No index is needed. - Compare inside the loop. When
num == value, returntrue. Areturnends the whole method immediately, so the remaining elements are never examined. - Return
falseafter the loop. The line is reached only when no element matched, so noelseis needed.
The solution in Swift
class Solution {
func contains(_ nums: [Int], _ value: Int) -> Bool {
for num in nums {
if num == value {
return true
}
}
return false
}
}
Swift details worth knowing:
- Unlabeled parameters. Each parameter is declared with a leading
_, so the call isSolution().contains([1, 2, 4, 5], 4)with no labels. - Method versus built-in. The method is named
contains, like the standard library's[1, 2, 3].contains(2). The two are unrelated: the method belongs toSolution, and the loop does the work. - Value semantics. The array is passed as a value and the method only reads it, so the caller's array is untouched.
- Return paths. Swift requires every path of a function that returns
Boolto return a value. The finalreturn falsecovers the case where the loop finishes, including an empty array.
Complexity
Time: O(n). In the worst case, a missing value or one in the last position, every element is compared once. If the value is the first element, the method returns after one comparison.
Space: O(1). Only the loop variable is used, whatever the size of the array.
Edge cases and common mistakes
- Empty array. The loop doesn't run and the method returns
false. - Returning
falsein anelseinside the loop. The method would then decide after the first element and miss matches further on. For[1, 2, 4, 5]and 4 it would returnfalse. - Duplicates. The method stops at the first occurrence, so repeated values cost nothing extra.
- Negative numbers and zero. The comparison with
==works the same for them.
Testing
[1, 2, 4, 5], 4 givestrue.[-1, 2, -4, 0, 10], 7 givesfalse.[], 3 givesfalse.[3], 3 givestrue.
