Imagine you're analyzing data sequences where prime numbers serve as key landmarks. Your task is to find all contiguous subsequences (subarrays) that are "prime-gap balanced" - meaning they contain at least two prime numbers with a controlled gap between them.
Given an integer array nums and an integer k, count how many subarrays satisfy these conditions:
- š Contains at least two prime numbers
- š The difference between the largest and smallest prime in that subarray is ā¤
k
Example: In array [2, 4, 3, 5, 7] with k = 4, the subarray [2, 4, 3, 5] is prime-gap balanced because it contains primes 2, 3, 5 and max(2,3,5) - min(2,3,5) = 5 - 2 = 3 ⤠4.
Note: A prime number is a natural number > 1 with exactly two factors: 1 and itself.
Input & Output
Visualization
Time & Space Complexity
O(n²) for generating subarrays à O(n) for prime checking and gap calculation
Only using constant extra space for variables
Constraints
- 1 ⤠nums.length ⤠1000
- 1 ⤠nums[i] ⤠1000
- 0 ⤠k ⤠1000
- All array elements are positive integers