Start learning free

LESSON 84 OF 348 · CONDITIONAL STATEMENTS - CHALLENGES

Absolute Difference in Kotlin: Subtract the Smaller from the 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 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(1.5, 1.5) ➞ 0

Note:

Do not use the abs() function provided by Kotlin (it will defeat the purpose of the challenge)


Hints:


If a is less then 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

    KOTLIN · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Absolute Difference in Kotlin, explained

    Problem overview

    The absolute difference of two numbers is how far apart they are, written as a positive number. You get it by subtracting one number from the other and then dropping any minus sign. The task is a function absDiff(a: Int, b: Int): Int inside class Solution that returns it. Kotlin's own abs is off limits, so the sign has to be handled with a comparison.

    Examples with whole numbers:

    • absDiff(3, 0) returns 3.
    • absDiff(0, 3) also returns 3: the order of the arguments doesn't matter.
    • absDiff(10, -1) returns 11.
    • absDiff(-5, -7) returns 2.
    • absDiff(6, -6) returns 12.

    Approach

    The result of a - b is negative when a is smaller than b, and that is the only case where the sign is wrong. In that case, b - a gives the same distance with a positive sign. So the rule is: subtract the smaller number from the larger one.

    That means one comparison, a < b, and two possible subtractions. The result is never negative, which is what "absolute" requires.

    Step by step

    1. Compare the inputs. Write if (a < b) { ... }. The body comes next.
    2. Handle the smaller a. Inside the if, return b - a. Subtracting the smaller number from the larger one cannot go negative.
    3. Handle everything else. After the if, return a - b. This line only runs when a < b was false, which means a is greater than or equal to b, so a - b is not negative. When they are equal it is 0, which is the right answer.

    The solution in Kotlin

    class Solution {
        fun absDiff(a: Int, b: Int): Int {
            if (a < b) {
                return b - a
            }
            return a - b
        }
    }
    

    Kotlin details worth knowing:

    • No else needed. A return ends the function immediately. When the condition is true, the function has already returned before the last line, so that line is reached only for the other case. An else around the final return would work too but add nothing.
    • Parameters are read-only. The function computes new values and does not change a or b.
    • The same logic as one expression. fun absDiff(a: Int, b: Int): Int = if (a < b) b - a else a - b does the same thing, because if in Kotlin can produce a value.

    Tracing two calls

    For absDiff(0, 3), the condition 0 < 3 is true, so the function returns 3 - 0, which is 3. For absDiff(3, 0), the condition 3 < 0 is false, so the if body is skipped and the function returns 3 - 0 as well. Both orders of the arguments end in the same subtraction, with the larger number first.

    Edge cases and common mistakes

    • Equal numbers. absDiff(4, 4) skips the if and returns 4 - 4, which is 0.
    • Negative inputs. absDiff(-5, -7) has a = -5, which is greater than b = -7. The function returns -5 - (-7), and subtracting a negative adds, so the result is 2. Mixed signs work the same way: absDiff(10, -1) is 10 - (-1), which is 11.
    • Returning a - b alone. It is right only when a is at least b. For absDiff(0, 3) it gives -3.
    • Swapping the branches. If the first branch returned a - b when a < b, every answer would come out negative or zero.
    • Overflow. An Int holds values up to 2147483647, and arithmetic that goes past it wraps silently. absDiff(2147483647, -1) returns -2147483648 instead of 2147483648, because the true difference doesn't fit in 32 bits. The lesson's tests use small numbers, so this does not matter here. To cover it, use Long for the type of the result.
    • Decimals. The parameters are Int, so fractional inputs such as 1.5 are not accepted. The same logic works unchanged with Double parameters and a Double result.

    Testing

    • absDiff(3, 0) gives 3.
    • absDiff(0, 3) gives 3.
    • absDiff(10, -1) gives 11.
    • absDiff(-5, -7) gives 2.
    • absDiff(6, -6) gives 12.
    • absDiff(7, 7) gives 0.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free