KatInterview

Smallest Integer Divisible by All Values in Every Subarray of Length K

Math & Bit ManipulationAuto-graded · 17 test cases
MediumAuto-gradedMath & Bit Manipulationmathgcd/lcmsliding window

Last updated

Tests the ability to combine sliding-window enumeration with LCM/GCD reasoning to find the minimum positive integer that is simultaneously divisible by every contiguous subarray LCM.

Subarray-LCM Coverage

You are given a list of positive integers nums and a positive integer k.

For every contiguous subarray of nums of length exactly k, compute the LCM (least common multiple) of its elements.

Return the LCM of all those per-subarray LCMs — in other words, the smallest positive integer that is divisible by every element in every length-k contiguous subarray of nums.

If k is greater than the length of nums, there are no valid subarrays; return 1 in that case.

How it works

  1. Slide a window of size k across nums, computing the LCM of each window.
  2. Compute the LCM of all those window-LCMs.
  3. Return that single integer.

Constraints

  • 1 ≤ len(nums) ≤ 2000
  • 1 ≤ nums[i] ≤ 1000
  • 1 ≤ k ≤ 2000
  • The answer is always a positive integer (it may be very large; Python handles big integers natively).
  • If k > len(nums), return 1.

Examples

Example 1

Input: subarray_lcm_coverage([2, 3, 4, 6], 2)

Output: 12

Example 2

Input: subarray_lcm_coverage([1, 2, 3, 4, 5], 3)

Output: 60

Example 3

Input: subarray_lcm_coverage([6], 2)

Output: 1

Hints

Hint 1

Recall that lcm(a, b) = a * b // gcd(a, b). Python's math module provides math.gcd directly.

Hint 2

Slide a window of size k across the array; for each window, fold lcm over its k elements to get that window's LCM. Then fold lcm over all window-LCMs.

Hint 3

Think about why the final answer equals the LCM of every element that appears in at least one valid window — elements outside all windows never affect divisibility.