Open In App

Count numbers in given range such that sum of even digits is greater than sum of odd digits

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers l and r denoting a range [l, r]. The task is to find the total count of numbers in the given range [l, r] whose sum of even digits is greater than the sum of odd digits. 

Examples:

Input: l = 2, r = 10 
Output : 4
Explanation: Numbers having the property that sum of even digits is greater than sum of odd digits are: 2, 4, 6, 8 

Input : l = 2, r = 17 
Output : 7

Prerequisites: Digit-DP 

[Naive Approach] Iterative Counting with Digit Sum Calculation

We can iterate through all the numbers in the given range and check if the sum of even digits is greater than the sum of odd digits for each number. If the condition is true, we increment a counter.

C++
// C++ program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd digits.

#include <iostream>
#include <string>

using namespace std;

int countNumbers(int l, int r) {
  
    // Initialize count to track valid numbers
    int count = 0;

    // Loop through each number in the range [l, r]
    for (int num = l; num <= r; num++) {
        int evenSum = 0, oddSum = 0;

        // Convert the number to a string to 
      	// access its digits
        string numStr = to_string(num);

        // Iterate over each character (digit) in the string
        for (char digit : numStr) {
          
            // Convert character to an integer
            int d = digit - '0';
            if (d % 2 == 0) {
                evenSum += d;
            }
            else {
                oddSum += d;
            }
        }

        // Check if the sum of even digits is greater 
      	// than the sum of odd digits
        if (evenSum > oddSum) {
            count++;
        }
    }

    return count;
}

int main() {
  
    int l = 2;
    int r = 10;
    int res = countNumbers(l, r);
    cout << res << endl;
    return 0;
}
Java
// Java program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd
// digits.

class GfG {

    static int countNumbers(int l, int r) {
      
        int count = 0;

        // Loop through each number in the range [l, r]
        for (int num = l; num <= r; num++) {
            int evenSum = 0, oddSum = 0;

            // Convert the number to a string to access its
            // digits
            String numStr = Integer.toString(num);

            // Iterate over each character (digit) in the
            // string
            for (char digit : numStr.toCharArray()) {
              
                // Convert character to an integer
                int d = digit - '0';
                if (d % 2 == 0) {
                    evenSum += d;
                }
                else {
                    oddSum += d;
                }
            }

            // Check if the sum of even digits is greater
            // than the sum of odd digits
            if (evenSum > oddSum) {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
      
        int l = 2;
        int r = 10;
        int res = countNumbers(l, r);
        System.out.println(res);
    }
}
Python
# Python program to count the numbers in the range [L, R]
# whose sum of even digits is greater than the sum of odd digits.

def countNumbers(l, r):
    count = 0

    # Loop through each number in the range [l, r]
    for num in range(l, r + 1):
        evenSum = 0
        oddSum = 0

        # Convert the number to a string to access
        # its digits
        numStr = str(num)

        # Iterate over each character (digit) in the string
        for digit in numStr:
            d = int(digit) 
            if d % 2 == 0:
                evenSum += d
            else:
                oddSum += d

        # Check if the sum of even digits is greater than the
        # sum of odd digits
        if evenSum > oddSum:
            count += 1

    return count


l = 2
r = 10
res = countNumbers(l, r)
print(res)
C#
// C# method to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of
// odd digits

using System;

class GfG {
  
    static int CountNumbers(int l, int r) {
      
        int count = 0;

        // Loop through each number in the range [l, r]
        for (int num = l; num <= r; num++) {
            int evenSum = 0;
            int oddSum = 0;

            // Convert the number to a string to access its
            // digits
            string numStr = num.ToString();

            // Iterate over each character (digit) in the
            // string
            foreach(char digit in numStr) {
                int d = digit - '0';
                if (d % 2 == 0) {
                    evenSum += d;
                }
                else {
                    oddSum += d;
                }
            }

            // Check if the sum of even digits is greater
            // than the sum of odd digits
            if (evenSum > oddSum) {
                count++;
            }
        }

        return count;
    }

    static void Main(string[] args) {
      
        int l = 2;
        int r = 10;
        int res = CountNumbers(l, r);
        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript function to count the numbers in the range [L,
// R] whose sum of even digits is greater than the sum of
// odd digits

function countNumbers(l, r) {

    let count = 0;

    // Loop through each number in the range [l, r]
    for (let num = l; num <= r; num++) {
        let evenSum = 0;
        let oddSum = 0;

        // Convert the number to a string to access its
        // digits
        let numStr = num.toString();

        // Iterate over each character (digit) in the string
        for (let i = 0; i < numStr.length; i++) {
            let d
                = parseInt(numStr[i]);
            if (d % 2 === 0) {
                evenSum += d;
            }
            else {
                oddSum += d;
            }
        }

        // Check if the sum of even digits is greater than
        // the sum of odd digits
        if (evenSum > oddSum) {
            count++;
        }
    }

    return count;
}

 
let l = 2;
let r = 10;
let res = countNumbers(l, r);
console.log(res); 

Output
4

Time Complexity: O((r-l+1)*d), where d is the number of digits in the largest number in the range [l, r]. 
Auxiliary Space: O(d)

[Expected Approach – 1] Using recursion

In this approach, firstly, count the required numbers up to r i.e. in the range [0, r]. To reach the answer in the range [l, r] solve for the range from zero to r and then subtracting the answer for the range from zero to l – 1. We can consider the number as a sequence of digits, one state is the position at which we are currently at. This position can have values from 0 to 18 if we are dealing with the numbers up to 10^18. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.

First state is the sum of the even digits that has been placed so far. Second state is the sum of the odd digits that has been placed so far. Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than r so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, the maximum limit of digit we can place is the digit at the current position in r.

C++
// C++ program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd digits
// using recursion.

#include <iostream>
#include <string>
using namespace std;

int countNumbers(int index, int evenSum, int oddSum, 
                 int tight, string &s) {
  
    // Base Case: If we've processed all digits
    if (index == s.size()) {
      
        // Check if the sum of even digits is greater
      // than the sum of odd digits
        return evenSum > oddSum ? 1 : 0;
    }

    // Maximum limit up to which we can place digit.
    // If tight is 1, we are restricted by the digit 
  // in s[index], else we can choose any digit (0-9).
    int limit = tight ? s[index] - '0' : 9;
    int ans = 0;

    // Iterate over all possible digits from 0 to limit
    for (int d = 0; d <= limit; d++) {
        int currTight = (d == s[index] - '0') ? tight : 0;

        // If the digit is odd
        if (d % 2 != 0)
            ans += countNumbers(index + 1, evenSum, 
                                oddSum + d, currTight, s);
      
        // If the digit is even
        else
            ans += countNumbers(index + 1, evenSum + d,
                                oddSum, currTight, s);
    }

    return ans;
}

int main() {
  
    int l = 2, r = 10;

    string s1 = to_string(r);
    string s2 = to_string(l - 1);

    cout << countNumbers(0, 0, 0, 1, s1) -
      countNumbers(0, 0, 0, 1, s2) << endl;  

    return 0;
}
Java
// Java program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd
// digits using recursion.

class GfG {
  
    static int countNumbers(int index, int evenSum,
                            int oddSum, int tight, String s) {
      
        // Base Case: If we've processed all digits
        if (index == s.length()) {
          
            // Check if the sum of even digits is greater
            // than the sum of odd digits
            return evenSum > oddSum ? 1 : 0;
        }

        // Maximum limit up to which we can place digit.
        // If tight is 1, we are restricted by the digit in
        // s.charAt(index), else we can choose any digit
        // (0-9).
        int limit = tight == 1 ? s.charAt(index) - '0' : 9;
        int ans = 0;

        // Iterate over all possible digits from 0 to limit
        for (int d = 0; d <= limit; d++) {
            int currTight
                = (d == s.charAt(index) - '0') ? tight : 0;

            // If the digit is odd
            if (d % 2 != 0)
                ans += countNumbers(index + 1, evenSum,
                                    oddSum + d, currTight,
                                    s);
            // If the digit is even
            else
                ans += countNumbers(index + 1, evenSum + d,
                                    oddSum, currTight, s);
        }

        return ans;
    }

    public static void main(String[] args) {
      
        int l = 2, r = 10;
        String s1 = String.valueOf(r);
        String s2 = String.valueOf(l - 1);

        System.out.println(
            countNumbers(0, 0, 0, 1, s1)
            - countNumbers(0, 0, 0, 1, s2));  
    }
}
Python
# Python program to count the numbers in the range [L, R]
# whose sum of even digits is greater than the sum of odd digits
# using recursion.


def countNumbers(index, evenSum, oddSum, tight, s):
  
    # Base Case: If we've processed all digits
    if index == len(s):
      
        # Check if the sum of even digits is
        # greater than the sum of odd digits
        return 1 if evenSum > oddSum else 0

    # Maximum limit up to which we can place digit.
    # If tight is 1, we are restricted by the digit
    # in s[index], else we can choose any digit (0-9).
    limit = int(s[index]) if tight else 9
    ans = 0

    # Iterate over all possible digits from 0 to limit
    for d in range(0, limit + 1):
        currTight = tight and (d == int(s[index]))

        # If the digit is odd
        if d % 2 != 0:
            ans += countNumbers(index + 1, evenSum, oddSum + d, currTight, s)
            
        # If the digit is even
        else:
            ans += countNumbers(index + 1, evenSum + d, oddSum, currTight, s)

    return ans


if __name__ == "__main__":
    l, r = 2, 10
    s1 = str(r)
    s2 = str(l - 1)

    result = countNumbers(0, 0, 0, 1, s1) - countNumbers(0, 0, 0, 1, s2)
    print(result)
C#
// C# program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd
// digits using recursion.

using System;

class GfG {
    
    static int CountNumbers(int index, int evenSum,
                            int oddSum, bool tight,
                            string s) {
      
        // Base Case: If we've processed all digits
        if (index == s.Length) {
          
            // Check if the sum of even digits is greater
            // than the sum of odd digits
            return evenSum > oddSum ? 1 : 0;
        }

        // Maximum limit up to which we can place digit.
        // If tight is true, we are restricted by the digit
        // in s[index], else we can choose any digit (0-9).
        int limit = tight ? s[index] - '0' : 9;
        int ans = 0;

        // Iterate over all possible digits from 0 to limit
        for (int d = 0; d <= limit; d++) {
            bool currTight
                = (d == s[index] - '0') ? tight : false;

            // If the digit is odd
            if (d % 2 != 0)
                ans += CountNumbers(index + 1, evenSum,
                                    oddSum + d, currTight,
                                    s);
            // If the digit is even
            else
                ans += CountNumbers(index + 1, evenSum + d,
                                    oddSum, currTight, s);
        }

        return ans;
    }

    static void Main() {
        int l = 2, r = 10;

        string s1 = r.ToString();
        string s2 = (l - 1).ToString();

        int res = CountNumbers(0, 0, 0, true, s1)
                  - CountNumbers(0, 0, 0, true, s2);
        Console.WriteLine(res);  
    }
}
JavaScript
// JavaScript program to count the numbers in the range [L,
// R] whose sum of even digits is greater than the sum of
// odd digits using recursion.

function countNumbers(index, evenSum, oddSum, tight, s) {

    // Base Case: If we've processed all digits
    if (index === s.length) {

        // Check if the sum of even digits is greater than
        // the sum of odd digits
        return evenSum > oddSum ? 1 : 0;
    }

    // Maximum limit up to which we can place digit.
    // If tight is true, we are restricted by the digit in
    // s[index], else we can choose any digit (0-9).
    const limit = tight ? parseInt(s[index]) : 9;
    let ans = 0;

    // Iterate over all possible digits from 0 to limit
    for (let d = 0; d <= limit; d++) {
        const currTight
            = (d === parseInt(s[index])) ? tight : false;

        // If the digit is odd
        if (d % 2 !== 0)
            ans += countNumbers(index + 1, evenSum,
                                oddSum + d, currTight, s);
        // If the digit is even
        else
            ans += countNumbers(index + 1, evenSum + d,
                                oddSum, currTight, s);
    }

    return ans;
}

const l = 2, r = 10;

const s1 = r.toString();
const s2 = (l - 1).toString();

const result = countNumbers(0, 0, 0, true, s1)
               - countNumbers(0, 0, 0, true, s2);
console.log(result);

Output
4

[Expected Approach – 2] Using Memoization 

If notice carefully, we can see that the above recursive function countNumbers() also follows the overlapping subproblems property i.e., same substructure solved again and again in different recursion call paths. We can avoid this using the memoization approach. Since there is four parameter that changes in recursive calls so we have used a 4D array and initialize it as -1 to indicate that the values are not computed.

C++
// C++ program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd digits
// using memoization.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int countNumbers(int index, int evenSum, int oddSum, int tight, string &s,
                 vector<vector<vector<vector<int>>>> &memo) {

    // Base case: If we've processed all digits
    if (index == s.size()) {
      
        // Return 1 if evenSum > oddSum, else return 0
        return evenSum > oddSum ? 1 : 0;
    }

    // Return memoized result if already computed
    if (memo[index][evenSum][oddSum][tight] != -1) {
        return memo[index][evenSum][oddSum][tight];
    }

    // Set limit for current digit (either tight or 9)
    int limit = tight ? s[index] - '0' : 9;
    int ans = 0;

    // Loop over possible digits (0 to limit)
    for (int d = 0; d <= limit; d++) {
      
        // Update tight condition
        int currTight = (d == s[index] - '0') ? tight : 0;

        // Recursive call based on digit type
      	// (odd or even)
        if (d % 2 != 0)
            ans += countNumbers(index + 1, evenSum, oddSum + d, currTight, s, memo);  
        else
            ans += countNumbers(index + 1, evenSum + d, oddSum, currTight, s, memo);  
    }
 
    memo[index][evenSum][oddSum][tight] = ans;
    return ans;
}

int main() {
  
    int l = 2, r = 10;

    string s1 = to_string(r);
    string s2 = to_string(l - 1);

    int maxIndex = s1.size();
    int maxSum = maxIndex * 9; 
    vector<vector<vector<vector<int>>>> memo(
        maxIndex,
        vector<vector<vector<int>>>(maxSum + 1, 
		vector<vector<int>>(maxSum + 1, vector<int>(2, -1))));

    // Count valid numbers in range [0, L-1]
    int cnt1 = countNumbers(0, 0, 0, 1, s2, memo);

    // Reset memo table for the next range
    for (int i = 0; i < maxIndex; i++) {
        for (int j = 0; j < maxSum + 1; j++) {
            for (int k = 0; k < maxSum + 1; k++) {
                for (int l = 0; l < 2; l++) {
                    memo[i][j][k][l] = -1;  
                }
            }
        }
    }

    int cnt2 = countNumbers(0, 0, 0, 1, s1, memo);
    cout << cnt2 - cnt1 << endl;

    return 0;
}
Java
// Java program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd
// digits using memoization.

import java.util.*;

class GfG {
   
    static int countNumbers(int index, int evenSum,
                            int oddSum, int tight, String s,
                            int[][][][] memo) {

        // Base case: If we've processed all digits
        if (index == s.length()) {
          
            // Return 1 if evenSum > oddSum, else return 0
            return evenSum > oddSum ? 1 : 0;
        }

        // Return memoized result if already computed
        if (memo[index][evenSum][oddSum][tight] != -1) {
            return memo[index][evenSum][oddSum][tight];
        }

        // Set limit for current digit (either tight or 9)
        int limit = tight == 1 ? s.charAt(index) - '0' : 9;
        int ans = 0;

        // Loop over possible digits (0 to limit)
        for (int d = 0; d <= limit; d++) {
          
            // Update tight condition
            int currTight
                = (d == s.charAt(index) - '0') ? tight : 0;

            // Recursive call based on digit type (odd or
            // even)
            if (d % 2 != 0)
                ans += countNumbers(index + 1, evenSum,
                                    oddSum + d, currTight,
                                    s, memo);
            else
                ans += countNumbers(index + 1, evenSum + d,
                                    oddSum, currTight, s,
                                    memo);
        }

        // Memoize and return result
        memo[index][evenSum][oddSum][tight] = ans;
        return ans;
    }

    public static void main(String[] args) {
      
        int l = 2, r = 10;

        String s1 = Integer.toString(r);
        String s2 = Integer.toString(l - 1);

        int maxIndex = s1.length();
        int maxSum
            = maxIndex
              * 9;  
        int[][][][] memo
            = new int[maxIndex][maxSum + 1][maxSum + 1][2];

        for (int i = 0; i < maxIndex; i++) {
            for (int j = 0; j < maxSum + 1; j++) {
                for (int k = 0; k < maxSum + 1; k++) {
                    Arrays.fill(memo[i][j][k],
                                -1);  
                                    
                }
            }
        }

        int cnt1 = countNumbers(0, 0, 0, 1, s2, memo);

        for (int i = 0; i < maxIndex; i++) {
            for (int j = 0; j < maxSum + 1; j++) {
                for (int k = 0; k < maxSum + 1; k++) {
                    Arrays.fill(memo[i][j][k], -1);
                }
            }
        }
        int cnt2 = countNumbers(0, 0, 0, 1, s1, memo);
        System.out.println(cnt2 - cnt1);
    }
}
Python
# Python program to count the numbers in the range [L, R]
# whose sum of even digits is greater than the sum of odd digits
# using memoization.


def countNumbers(index, evenSum, oddSum, tight, s, memo):

    # Base case: If we've processed all digits
    if index == len(s):

        # Return 1 if evenSum > oddSum, else return 0
        return 1 if evenSum > oddSum else 0

    # Return memoized result if already computed
    if memo[index][evenSum][oddSum][tight] != -1:
        return memo[index][evenSum][oddSum][tight]

    # Set limit for current digit (either tight or 9)
    limit = int(s[index]) if tight else 9
    ans = 0

    # Loop over possible digits (0 to limit)
    for d in range(0, limit + 1):

        # Update tight condition
        currTight = tight if d == int(s[index]) else 0

        # Recursive call based on digit type (odd or even)
        if d % 2 != 0:
            ans += countNumbers(index + 1, evenSum,
                                oddSum + d, currTight, s, memo)
        else:
            ans += countNumbers(index + 1, evenSum + d,
                                oddSum, currTight, s, memo)

    # Memoize and return result
    memo[index][evenSum][oddSum][tight] = ans
    return ans


if __name__ == "__main__":
    l = 2
    r = 10

    # Convert L and R to strings for
    # easy digit processing
    s1 = str(r)
    s2 = str(l - 1)

    # Initialize memo table with -1 (indicating uncomputed state)
    maxIndex = len(s1)
    maxSum = maxIndex * 9
    memo = [[[[-1 for _ in range(2)] for _ in range(maxSum + 1)]\
             for _ in range(maxSum + 1)] for _ in range(maxIndex)]

    # Count valid numbers in range [0, L-1]
    cnt1 = countNumbers(0, 0, 0, 1, s2, memo)

    # Reset memo table for the next range
    memo = [[[[-1 for _ in range(2)] for _ in range(maxSum + 1)]\
             for _ in range(maxSum + 1)] for _ in range(maxIndex)]

    # Count valid numbers in range [0, R]
    cnt2 = countNumbers(0, 0, 0, 1, s1, memo)

    # Output the result (numbers in range [L, R])
    print(cnt2 - cnt1)
C#
// C# program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd digits
// using memoization.

using System;

class  GfG {
   static int countNumbers(int index, int evenSum,
                            int oddSum, int tight, string s,
                            int[, , , ] memo) {
     
        // Base case: If we've processed all digits
        if (index == s.Length) {
          
            // Return 1 if evenSum > oddSum, else return 0
            return evenSum > oddSum ? 1 : 0;
        }

        // Return memoized result if already computed
        if (memo[index, evenSum, oddSum, tight] != -1) {
            return memo[index, evenSum, oddSum, tight];
        }

        // Set limit for current digit (either tight or 9)
        int limit = tight == 1 ? s[index] - '0' : 9;
        int ans = 0;

        // Loop over possible digits (0 to limit)
        for (int d = 0; d <= limit; d++) {
          
            // Update tight condition
            int currTight
                = (d == s[index] - '0') ? tight : 0;

            // Recursive call based on digit type (odd or
            // even)
            if (d % 2 != 0) {
                ans += countNumbers(index + 1, evenSum,
                                    oddSum + d, currTight,
                                    s, memo);  
            }
            else {
                ans += countNumbers(index + 1, evenSum + d,
                                    oddSum, currTight, s,
                                    memo);  
            }
        }

        // Memoize and return result
        memo[index, evenSum, oddSum, tight] = ans;
        return ans;
    }

    static void Main(string[] args) {
        int L = 2;
        int R = 10;

        // Convert L and R to strings for easy digit
        // processing
        string s1 = R.ToString();
        string s2 = (L - 1).ToString();

        // Initialize memo table with -1 (indicating
        // uncomputed state)
        int maxIndex = s1.Length;
        int maxSum
            = maxIndex
              * 9;  

        // Create the 4D memo array
        int[, , , ] memo
            = new int[maxIndex, maxSum + 1, maxSum + 1, 2];

        // Manually initialize all elements of the 4D array
        // to -1
        for (int i = 0; i < maxIndex; i++) {
            for (int j = 0; j <= maxSum; j++) {
                for (int k = 0; k <= maxSum; k++) {
                    for (int l = 0; l < 2; l++) {
                        memo[i, j, k, l] = -1;
                    }
                }
            }
        }

        // Count valid numbers in range [0, L-1]
        int cnt1 = countNumbers(0, 0, 0, 1, s2, memo);

        // Reset memo table for the next range
        for (int i = 0; i < maxIndex; i++) {
            for (int j = 0; j <= maxSum; j++) {
                for (int k = 0; k <= maxSum; k++) {
                    for (int l = 0; l < 2; l++) {
                        memo[i, j, k, l] = -1;
                    }
                }
            }
        }

         
        int cnt2 = countNumbers(0, 0, 0, 1, s1, memo);
 
        Console.WriteLine(cnt2 - cnt1);
    }
}
JavaScript
// JavaScript program to count the numbers in the range [L,
// R] whose sum of even digits is greater than the sum of
// odd digits using memoization.

function countNumbers(index, evenSum, oddSum, tight, s,
                      memo) {

    // Base case: If we've processed all digits
    if (index === s.length) {

        // Return 1 if evenSum > oddSum, else return 0
        return evenSum > oddSum ? 1 : 0;
    }

    // Return memoized result if already computed
    if (memo[index][evenSum][oddSum][tight] !== -1) {
        return memo[index][evenSum][oddSum][tight];
    }

    // Set limit for current digit (either tight or 9)
    const limit = tight === 1 ? parseInt(s[index]) : 9;
    let ans = 0;

    // Loop over possible digits (0 to limit)
    for (let d = 0; d <= limit; d++) {

        // Update tight condition
        const currTight
            = (d === parseInt(s[index])) ? tight : 0;

        // Recursive call based on digit type (odd or even)
        if (d % 2 !== 0) {
            ans += countNumbers(index + 1, evenSum,
                                oddSum + d, currTight, s,
                                memo); // Odd digit
        }
        else {
            ans += countNumbers(index + 1, evenSum + d,
                                oddSum, currTight, s,
                                memo); // Even digit
        }
    }

    // Memoize and return result
    memo[index][evenSum][oddSum][tight] = ans;
    return ans;
}

const l = 2;
const r = 10;

// Convert L and R to strings for easy digit processing
const s1 = r.toString();
const s2 = (l - 1).toString();

// Initialize memo table with -1 (indicating uncomputed
// state)
const maxIndex = s1.length;
const maxSum = maxIndex * 9;

// Create the 4D memo array
const memo = Array.from(
    {length : maxIndex},
    () => Array.from(
        {length : maxSum + 1},
        () => Array.from({length : maxSum + 1},
                         () => Array(2).fill(-1))));

// Count valid numbers in range [0, L-1]
let cnt1 = countNumbers(0, 0, 0, 1, s2, memo);

// Reset memo table for the next range
for (let i = 0; i < maxIndex; i++) {
    for (let j = 0; j <= maxSum; j++) {
        for (let k = 0; k <= maxSum; k++) {
            for (let l = 0; l < 2; l++) {
                memo[i][j][k][l] = -1;
            }
        }
    }
}

let cnt2 = countNumbers(0, 0, 0, 1, s1, memo);
console.log(cnt2 - cnt1);

Output
4

Time Complexity : There would be at max 18*(180)*(180)*2 computations when 0 < l,r < 1018
Auxiliary Space: O(18*180*180*2), as we are using extra space.



Next Article

Similar Reads