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: 6
💡 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: 6 valid subarrays (note: [2,3,5,7] has gap 7-2=5 > 4)
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
Prime-Gap Balanced Subarrays: nums=[2,3,5,7], k=42357All elements are prime numbers[2,3] gap=1≤4✓[2,3,5] gap=3≤4✓[3,5] gap=2≤4✓[3,5,7] gap=4≤4✓[5,7] gap=2≤4✓[2,3,5,7] gap=5>4✗Result: 6 valid subarrays (5 shown ✓ + 1 more)
Understanding the Visualization
1
Input
Array with numbers and gap limit k
2
Process
Find subarrays with ≥2 primes and max-min prime ≤ k
3
Output
Count of valid prime-gap balanced subarrays
Key Takeaway
🎯 Key Insight: Only consider prime numbers and use gap constraint to efficiently prune invalid subarrays
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