Start learning free

LESSON 85 OF 415 · CONDITIONAL STATEMENTS - CHALLENGES

Absolute Difference in Swift: Subtract Smaller from Larger

Practice Read the full explanation

The absolute difference is a measure of the difference between two numbers but expressed as a positive number.

In other words, it’s taking the difference between two values (x - y) and then calculating the absolute value of the result.

Create a function (called as absDiff in the examples below; use the name from the starter code) that takes in two numbers a and b and returns their absolute difference.

Examples:

absDiff(3, 0) ➞ 3

absDiff(0, 3) ➞ 3

absDiff(10, -1) ➞ 11

absDiff(-5, -7) ➞ 2

absDiff(6, -6) ➞ 12

absDiff(7, 7) ➞ 0

Note:

Do not use the absolute value function provided by Swift (it will defeat the purpose of the challenge)


Hints:


If a is less than b, the absolute difference equals b - a. What if a is greater than or equal to b?

If a < b, we should return b - a. Otherwise, we should return a - b. We can use an if statement to put this in code.
STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Absolute Difference in Swift, explained

    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

    1. Compare the two numbers. Write if a < b { }, with the braces in place and no parentheses around the condition.
    2. Return b - a inside it. Here a is the smaller number, so subtracting it from b can't give a negative result.
    3. Return a - b below the if. There is no else. If a < b was true, the function has already returned, so this line only runs when a is at least b, and a - b is 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 return ends the function immediately. The line after the if acts as the "otherwise" branch without being written as one. Adding else would also work, and both styles are common.
    • Unlabelled parameters. The underscores in _ a: Int, _ b: Int mean callers write absDiff(10, -1), with no labels.
    • Return on every path. The compiler accepts the function because the last line returns whenever the if doesn't.
    • Whole numbers only. The parameters and the result are Int. A call such as absDiff(1.5, 1.5) doesn't compile, because 1.5 is a Double.

    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 is false and the function returns a - b, which is 0.
    • Subtracting in the wrong order. Always returning a - b gives -3 for absDiff(0, 3), which is negative.
    • Both numbers negative. The rule still holds. For -5 and -7, a is larger, so the function returns -5 - (-7), which is 2.
    • Opposite signs. For 6 and -6, the distance is 12, not 0. Subtracting, not adding, is what measures the gap.
    • Overflow at the extremes. Int is 64 bits. If the true difference doesn't fit, for example Int.max and Int.min, the subtraction overflows and Swift stops the program at run time instead of wrapping around.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free