LeetCode 2470: Number of Subarrays With LCM Equal to K Solution

Master LeetCode problem 2470 (Number of Subarrays With LCM Equal to K), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2470. Number of Subarrays With LCM Equal to K

Problem Explanation

Explanation

To solve this problem, we will iterate through all subarrays of the given array and calculate the least common multiple (LCM) of each subarray. We will then count the number of subarrays where the LCM is equal to the given integer k.

Algorithm:

  1. Initialize a count variable to store the number of subarrays with LCM equal to k.
  2. Iterate through all subarrays using two nested loops.
  3. For each subarray, calculate the LCM of its elements.
  4. If the LCM equals k, increment the count variable.
  5. Return the count as the final result.

Time Complexity:

  • O(n^3) where n is the length of the input array nums. This is because we iterate through all subarrays and calculate the LCM for each subarray.

Space Complexity:

  • O(1) as we are using constant extra space.

Solution Code

class Solution {
    public int countSubarrays(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i; j < nums.length; j++) {
                int lcm = calculateLCM(Arrays.copyOfRange(nums, i, j + 1));
                if (lcm == k) {
                    count++;
                }
            }
        }
        return count;
    }
    
    private int calculateLCM(int[] arr) {
        int lcm = arr[0];
        for (int i = 1; i < arr.length; i++) {
            lcm = lcm * arr[i] / gcd(lcm, arr[i]);
        }
        return lcm;
    }
    
    private int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2470 (Number of Subarrays With LCM Equal to K)?

This page provides optimized solutions for LeetCode problem 2470 (Number of Subarrays With LCM Equal to K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2470 (Number of Subarrays With LCM Equal to K)?

The time complexity for LeetCode 2470 (Number of Subarrays With LCM Equal to K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2470 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2470 in Java, C++, or Python.

Back to LeetCode Solutions