Code Logo

Absolute Difference

Published at25 Jul 2026
Basic Operations Easy 0 views
Like0

Given two integers a and b, compute the absolute difference between them: |a - b|. The result is always a non-negative integer regardless of which number is larger.

For example, if a = 5 and b = 3, the difference is 2. If a = 3 and b = 5, the difference is also 2, because absolute value disregards the sign. If both numbers are equal, the result is 0.

This problem introduces the concept of absolute value, a fundamental mathematical operation used extensively in geometry (distance between points), physics (magnitude of velocity), and computer graphics (collision detection). The absolute difference measures the distance between two numbers on the number line without caring about direction.

In programming, most languages provide a built-in absolute value function (abs in most languages, Math.abs in JavaScript/Java, f64::abs in Rust). The mathematical definition is: |a - b| = a - b when a >= b, and |a - b| = b - a when a < b. You can implement it directly with a conditional or use the built-in function.

Edge cases include very large integers that might overflow if subtraction is performed before taking absolute value, and cases where both numbers are negative. However, for typical 32-bit integer ranges, direct subtraction followed by absolute value is safe.

Example Input & Output

Example 1
Input
5,3
Output
2
Explanation

|5-3|=2

Example 2
Input
10,10
Output
0
Explanation

Equal numbers

Example 3
Input
3,8
Output
5
Explanation

|3-8|=5

Example 4
Input
100,1
Output
99
Explanation

|100-1|=99

Example 5
Input
0,7
Output
7
Explanation

|0-7|=7

Algorithm Flow

Recommendation Algorithm Flow for Absolute Difference
Recommendation Algorithm Flow for Absolute Difference

Solution Approach

The simplest solution uses the built-in absolute value function provided by your language.

function solution(a, b) {
  return Math.abs(a - b);
}

The algorithm subtracts b from a, then applies the absolute value function. This works because |a - b| = |b - a|, so the order of subtraction does not matter once absolute value is applied. If you wanted to implement it manually, you would check: if (a >= b) return a - b; else return b - a.

The time complexity is O(1) since it involves only a subtraction and a single function call. The space complexity is O(1) as well, using no additional memory beyond the input values. This makes it optimal.

One caveat in languages like C++ or Java is integer overflow: if a is very large positive and b is very large negative, a - b could overflow before the absolute value is taken. In those cases, using a larger integer type (long) or comparing the values first avoids the issue. For the constraints of this challenge, standard 32-bit integers are sufficient.

Best Answers

java
class Solution {
    public int solution(int a, int b) {
        return Math.abs(a-b);
    }
}