Skip to main content

How Many Xs Solution

In this page, we will solve the How Many Xs problem using different approaches: iterative and mathematical. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, and C++.

Problem Description​

You are given an integer L, R, and X. Find the number of occurrences of X in all the numbers in the range (L, R) excluding L and R.

Examples​

Example 1:

Input: L = 10, R = 20, X = 1
Output: 10
Explanation: The digit 1 appears 11 times in numbers from 10 to 19.

Example 2:

Input: L = 100, R = 120, X = 2
Output: 2
Explanation: The digit 2 appears 3 times in numbers from 100 to 119.

Constraints​

  • 0 <= L <= R <= 10^9
  • 0 <= X <= 9

Solution for How Many Xs Problem​

Intuition and Approach​

The problem can be solved using different approaches such as iterative counting and mathematical properties.

Approach 1: Iterative​

The iterative approach involves iterating through each number in the range and counting the occurrences of the digit X.

Implementation​

Live Editor
function countXs() {
  const L = 10;
  const R = 20;
  const X = 1;

  const countDigitOccurrences = (L, R, X) => {
    let count = 0;
    for (let i = L+1; i < R; i++) {
      let num = i;
      while (num > 0) {
        if (num % 10 === X) count++;
        num = Math.floor(num / 10);
      }
    }
    return count;
  };

  const result = countDigitOccurrences(L, R, X);
  return (
    <div>
      <p>
        <b>Input:</b> L = {L}, R = {R}, X = {X}
      </p>
      <p>
        <b>Output:</b> {result}
      </p>
    </div>
  );
}
Result
Loading...

Codes in Different Languages​

Written by @manishh12
 function countDigitOccurrences(L, R, X) {
let count = 0;
for (let i = L+1; i < R; i++) {
let num = i;
while (num > 0) {
if (num % 10 === X) count++;
num = Math.floor(num / 10);
}
}
return count;
}

Complexity Analysis​

  • Time Complexity: O((Rβˆ’L)βˆ—logR)O((R - L)*logR)
  • Space Complexity: O(1)O(1)
tip

The mathematical approach is more efficient for large ranges. Choose the method that best suits the given constraints.

References​