Problem overview
The absolute difference of two numbers is how far apart they are, written as a number that is never negative. It equals a - b or b - a, whichever is not negative. The method absDiff(_ a: Int, _ b: Int) -> Int in the class Solution returns it, and it must not use Swift's built-in abs().
For example, absDiff(3, 0) and absDiff(0, 3) both give 3. For 10 and -1 the answer is 11, and for -5 and -7 it is 2.
Approach
Subtracting the smaller number from the larger one always gives a result that is zero or positive. So the work is to find out which of the two is smaller. When a < b, the answer is b - a. Otherwise a is greater than or equal to b, and the answer is a - b. When the two are equal, either subtraction gives 0.
Step by step
- Compare the two numbers. Write
if a < b { }, with the braces in place and no parentheses around the condition. - Return
b - ainside it. Hereais the smaller number, so subtracting it frombcan't give a negative result. - Return
a - bbelow theif. There is noelse. Ifa < bwas true, the function has already returned, so this line only runs whenais at leastb, anda - bis not negative.
The solution in Swift
class Solution {
func absDiff(_ a: Int, _ b: Int) -> Int {
if a < b {
return b - a
}
return a - b
}
}
Some Swift details behind this short function:
- Early return instead of else. A
returnends the function immediately. The line after theifacts as the "otherwise" branch without being written as one. Addingelsewould also work, and both styles are common. - Unlabelled parameters. The underscores in
_ a: Int, _ b: Intmean callers writeabsDiff(10, -1), with no labels. - Return on every path. The compiler accepts the function because the last line returns whenever the
ifdoesn't. - Whole numbers only. The parameters and the result are
Int. A call such asabsDiff(1.5, 1.5)doesn't compile, because1.5is aDouble.
Why it works
The two cases cover every possible pair. Either a is strictly smaller than b, or it is not, and in the second case a is greater than or equal to b. There is no third possibility. In each case the function subtracts the smaller value from the larger one, so the result is never negative. This is the same as taking the absolute value of a - b, but without calling a function that does it for you.
Trace absDiff(0, 3): the test 0 < 3 is true, so the function returns 3 - 0, which is 3. Trace absDiff(10, -1): the test 10 < -1 is false, so the function skips the body and returns 10 - (-1), which is 11.
Trying it
let s = Solution()
print(s.absDiff(3, 0))
print(s.absDiff(0, 3))
print(s.absDiff(10, -1))
print(s.absDiff(-5, -7))
print(s.absDiff(6, -6))
The output is:
3
3
11
2
12
Edge cases and common mistakes
- Equal numbers. With
a == b, the condition isfalseand the function returnsa - b, which is0. - Subtracting in the wrong order. Always returning
a - bgives-3forabsDiff(0, 3), which is negative. - Both numbers negative. The rule still holds. For
-5and-7,ais larger, so the function returns-5 - (-7), which is2. - Opposite signs. For
6and-6, the distance is12, not0. Subtracting, not adding, is what measures the gap. - Overflow at the extremes.
Intis 64 bits. If the true difference doesn't fit, for exampleInt.maxandInt.min, the subtraction overflows and Swift stops the program at run time instead of wrapping around.
