Start learning free

LESSON 83 OF 410 · CONDITIONAL STATEMENTS - CHALLENGES

Find the absolute difference in Java with O(1) Time Complexity

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 Java (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

    JAVA · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Absolute Difference in Java, explained

    Understanding the Problem

    The core challenge of this problem is to compute the absolute difference between two numbers without using the built-in abs() function. The absolute difference is always a positive number, regardless of the order of the inputs.

    This problem is significant in various applications such as calculating distances, error margins, and differences in data values. A common pitfall is to forget that the result must always be positive.

    Approach

    To solve this problem, we need to consider the following:

    • If a is less than b, the absolute difference is b - a.
    • If a is greater than or equal to b, the absolute difference is a - b.

    We can implement this logic using an if statement to check the condition and return the appropriate result.

    Naive Solution

    A naive solution would involve checking the condition and returning the difference accordingly. This approach is straightforward and has a time complexity of O(1), which is optimal for this problem.

    Optimized Solution

    The naive solution is already optimal for this problem. However, we can further simplify the code by using the ternary operator to make it more concise.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Check if a is less than b.
    2. If true, return b - a.
    3. If false, return a - b.

    Code Implementation

    Below is the Java implementation of the solution:

    public class AbsoluteDifference {
        // Function to calculate the absolute difference between two numbers
        public static double absDiff(double a, double b) {
            // Check if a is less than b
            if (a < b) {
                return b - a; // Return b - a if a is less than b
            } else {
                return a - b; // Return a - b if a is greater than or equal to b
            }
        }
    
        // Main method to test the function
        public static void main(String[] args) {
            // Test cases
            System.out.println(absDiff(3, 0)); // ➞ 3
            System.out.println(absDiff(0, 3)); // ➞ 3
            System.out.println(absDiff(10, -1)); // ➞ 11
            System.out.println(absDiff(-5, -7)); // ➞ 2
            System.out.println(absDiff(6, -6)); // ➞ 12
            System.out.println(absDiff(1.5, 1.5)); // ➞ 0
        }
    }
    

    Complexity Analysis

    The time complexity of this solution is O(1) because it involves a constant number of operations regardless of the input values. The space complexity is also O(1) as no additional space is required.

    Edge Cases

    Potential edge cases include:

    • Both numbers being the same (e.g., absDiff(1.5, 1.5) should return 0).
    • One or both numbers being negative (e.g., absDiff(-5, -7) should return 2).
    • One number being zero (e.g., absDiff(0, 3) should return 3).

    These edge cases are handled by the algorithm as it correctly computes the absolute difference in all scenarios.

    Testing

    To test the solution comprehensively, we should include a variety of test cases:

    • Simple cases with positive numbers.
    • Cases with negative numbers.
    • Cases with one or both numbers being zero.
    • Cases with floating-point numbers.

    We can use the main method provided in the code implementation to run these test cases and verify the results.

    Thinking and Problem-Solving Tips

    When approaching such problems, it is essential to:

    • Understand the problem requirements and constraints.
    • Break down the problem into smaller, manageable parts.
    • Consider edge cases and how to handle them.
    • Write clean, readable code with comments explaining the logic.

    Practicing similar problems and studying different algorithms can help improve problem-solving skills.

    Conclusion

    In this blog post, we discussed how to find the absolute difference between two numbers in Java without using the built-in abs() function. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in programming.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free