703821. Queries for counts of multiples in an array

Medium

Queries for Counts of Multiples in an Array

Summary

Given a sorted array, write a function that takes two integers m and n as input, where m is the starting index and n is the ending index. The function should return the count of numbers in the range [m..n] that are multiples of some number (not necessarily all). For example, if the array is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], and m=0 and n=9, the function should return 5, because there are five numbers in this range that are multiples of some number: [2, 4, 6, 8, 10].

Detailed Explanation

The problem is about counting the numbers in a given range that are multiples of some number. Since the array is sorted, we can use a mathematical approach to solve this problem efficiently.

Here's a step-by-step breakdown of the solution:

  1. Calculate the count of numbers in the range [m..n] that are multiples of 2. This can be done by finding the count of multiples of 2 in the range using the formula (n - m + 1) / 2.
  2. Calculate the count of numbers in the range [m..n] that are not multiples of 2, but are multiples of some other number (not necessarily all). This can be done by subtracting the count of multiples of 2 from the total count of numbers in the range.

The time complexity of this approach is O(1), because we only need to perform a constant amount of work. The space complexity is also O(1), because we don't need any extra space.

Here's an ASCII art diagram showing the ranges:

  +---------------+
  |        m      |
  +---------------+
           |
           |  [m..n]
           v
  +---------------+
  |   multiples of 2  |
  +---------------+
  |  not multiples of 2  |
  +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
public int countMultiples(int[] arr, int m, int n) {
    int count = (n - m + 1) / 2;
    for (int i = m; i <= n; i++) {
        if (i % 2 == 0) {
            count++;
        }
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.