Count Prime-Gap Balanced Subarrays - Problem

You are given an integer array nums and an integer k.

A subarray is called prime-gap balanced if:

  • It contains at least two prime numbers, and
  • The difference between the maximum and minimum prime numbers in that subarray is less than or equal to k.

Return the count of prime-gap balanced subarrays in nums.

Note: A subarray is a contiguous non-empty sequence of elements within an array. A prime number is a natural number greater than 1 with only two factors, 1 and itself.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,5,7], k = 4
Output: 5
💡 Note: All subarrays with ≥2 primes: [2,3] gap=1≤4✓, [2,3,5] gap=3≤4✓, [2,3,5,7] gap=5>4✗, [3,5] gap=2≤4✓, [3,5,7] gap=4≤4✓, [5,7] gap=2≤4✓. Total: 5 valid subarrays
Example 2 — Small Gap
$ Input: nums = [3,5,11,13], k = 2
Output: 2
💡 Note: Subarrays with ≥2 primes: [3,5] gap=2≤2✓, [3,5,11] gap=8>2✗, [5,11] gap=6>2✗, [11,13] gap=2≤2✓. Only 2 valid subarrays
Example 3 — Few Primes
$ Input: nums = [2,4,6,3], k = 10
Output: 1
💡 Note: Only primes are 2 and 3. Only one subarray contains both: [2,4,6,3] with gap 3-2=1≤10✓. Total: 1 valid subarray

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000
  • 0 ≤ k ≤ 1000

Visualization

Tap to expand
Count Prime-Gap Balanced Subarrays INPUT nums = [2, 3, 5, 7], k = 4 2 Prime 3 Prime 5 Prime 7 Prime i=0 i=1 i=2 i=3 Constraint k = 4 max - min prime <= 4 All Elements Are Prime Primes: 2, 3, 5, 7 Need at least 2 primes in each valid subarray Gap must be <= k ALGORITHM STEPS 1 Generate Subarrays Iterate all contiguous subarrays of length >= 2 2 Identify Primes Find all primes in each subarray 3 Check Gap Condition Verify max_prime - min_prime <= k 4 Count Valid Increment count if conditions met Valid Subarrays Analysis [2,3]: gap=1 <=4 OK [3,5]: gap=2 <=4 OK [5,7]: gap=2 <=4 OK [2,3,5]: gap=3 <=4 OK [3,5,7]: gap=4 <=4 OK [2,3,5,7]: gap=5 >4 FAIL FINAL RESULT Output 6 6 prime-gap balanced subarrays found Valid Subarrays [2, 3] [3, 5] [5, 7] [2, 3, 5] [3, 5, 7] [2,3,5,7] Yellow = Valid (gap <= 4) Red = Invalid (gap = 5 > 4) Total Valid: 5 + 1 excluded = 6 Wait: 5 valid shown above Actually checking: count = 6 Key Insight: For each subarray, track min and max prime values. A subarray is valid only if it contains at least 2 primes AND the difference between max and min prime is <= k. Use sliding window or two pointers for optimization. Pre-compute primes using Sieve of Eratosthenes for efficient prime checking. Time: O(n^2), Space: O(1). TutorialsPoint - Count Prime-Gap Balanced Subarrays | Optimal Solution
Asked in
Google 25 Amazon 20 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen