My understaning of learning to solve promlems - the first issue

surya ravikumarsurya ravikumar
2 min read

2535. Difference Between Element sum and Digit Sum of an Array

Look up the problem statement.

the first solution for the problem is listed below but the bug was introduced. if you can find it share it with others.


package das;
public class differenceOfSum {
    public static void main(String[] args) {
        int[] nums = {1, 15, 6, 3};
        int result = differenceOfSum(nums);
        System.out.println(result);
    }

    public static int differenceOfSum(int[] nums) {
        int elementSum = 0;
        int digitSum = 0;
        for (int i = 0; i < nums.length; i++) {
            digitSum += nums[i];
            int current = i;
            while (current > 0) {
                elementSum = (elementSum * 10) + current % 10;
                current /= 10;
            }
        }
        int absolute = digitSum - elementSum;
        return absolute = (absolute < 0) ? absolute * -1 : absolute;
    }
}

fix the code, if you're naive or a student. Please cheat and look into the code.

Time Complexity is a revised and also bug too. i.e. code is revised

public int differenceOfSum(int[] nums) {
    int digitSum = 0;
    int elementSum = 0;

    for (int num : nums) {
        int absNum = Math.abs(num); // Take the absolute value to handle negative numbers
        digitSum += sumOfDigits(absNum);
        elementSum += absNum;
    }

    return Math.abs(digitSum - elementSum);
}

// Helper function to calculate the sum of digits of a number
private int sumOfDigits(int num) {
    int sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

In this code, we directly calculate the sum of the digits of each element using the sumOfDigits helper function, and then we compute the absolute difference between the digit sum and element sum. This approach has a linear time complexity of O(N) and is more efficient than the original code for large arrays with potentially large numbers.

10
Subscribe to my newsletter

Read articles from surya ravikumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

surya ravikumar
surya ravikumar