Absolute Difference
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
|5-3|=2
Equal numbers
|3-8|=5
|100-1|=99
|0-7|=7
Algorithm Flow

Solution Approach
The simplest solution uses the built-in absolute value function provided by your language.
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
class Solution {
public int solution(int a, int b) {
return Math.abs(a-b);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
