You are given an array of integers nums. Write a function to find the number of "squareful" subarrays. A squareful subarray is a subarray whose sum is a perfect square. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given an array of integers nums. We need to count the number of subarrays (contiguous) whose sum is a perfect square.
We need to write a function that returns the count.
We need to consider:
Negative numbers? The problem says "array of integers", so could be negative. The sum could be negative? Perfect squares are non-negative, so a negative sum cannot be a perfect square (unless we consider complex numbers, but no). So we only consider non-negative sums? Actually perfect square is an integer that is the square of an integer, so non-negative. So if sum is negative, it's not squareful.
We need to count all contiguous subarrays. The array length can be? Not specified, but we need efficient algorithm. Naive O(n^2) might be too slow for large n. But maybe constraints are moderate? We should aim for an efficient solution.
Plan:
We can use prefix sums. Let prefix[i] = sum of nums[0..i-1] (with prefix[0]=0). Then sum of subarray [i, j) (i inclusive, j exclusive) = prefix[j] - prefix[i]. We want prefix[j] - prefix[i] = k^2 for some integer k>=0. So prefix[j] = prefix[i] + k^2.
So for each j, we want to count number of i < j such that prefix[j] - prefix[i] is a perfect square. Equivalently, for each j, we want to count how many prefix[i] (i from 0 to j-1) are equal to prefix[j] - k^2 for some k^2 <= prefix[j] (since prefix[i] must be non-negative? Actually prefix[i] can be negative because nums can be negative. But k^2 is non-negative, so prefix[j] - k^2 could be any number. So we need to consider all k^2 such that prefix[i] = prefix[j] - k^2 is present in the set of prefix sums seen so far.
But k^2 can be up to what? prefix[j] can be as large as sum of all positive numbers, or as low as sum of all negative. But we need k^2 to be at most prefix[j] - (some possible prefix[i]). Actually we need prefix[i] = prefix[j] - k^2. Since i<j, we have already computed prefix[i] values. For a given prefix[j], we need to check for each possible k^2 such that prefix[j] - k^2 is in the set of previous prefix sums. But how many k^2 values? If prefix[j] is large, there could be many squares up to prefix[j]. That could be up to sqrt(prefix[j]) possibilities. If prefix[j] is as large as 10^10, sqrt is 10^5, which might be okay if we iterate over all squares for each j? But j could be up to n, and n might be large. So total complexity could be O(n * sqrt(M)) where M is max prefix sum magnitude. That might be too high if M is large.
Alternatively, we can think: we want to count pairs (i, j) such that prefix[j] - prefix[i] is a perfect square. We can iterate over all possible square values s = k^2, and then count pairs (i,j) such that prefix[j] - prefix[i] = s. For a fixed s, we can count number of pairs with difference s by using a map: for each prefix value p, we can count occurrences. But s can be up to max difference? The difference can be as large as the range of prefix sums. But there are many possible s? Actually s must be a perfect square. The number of perfect squares up to some maximum D is about sqrt(D). But D could be the maximum absolute difference of prefix sums, which could be large. But maybe the constraints are such that n is not huge? The problem statement did not give constraints. We need to assume that n might be up to 10^5 or more. So we need an efficient solution.
We could try to use a hash map for prefix sums and iterate over possible squares for each prefix[j]. But that is O(n * sqrt(max_prefix)). That might be acceptable if max_prefix is not too large. But if nums contain large numbers, max_prefix could be huge. However, note that the sum of a subarray is a perfect square, and perfect squares grow quadratically. For a given prefix[j], the number of squares k^2 such that k^2 <= prefix[j] - min_prefix? Actually we need prefix[i] = prefix[j] - k^2. Since prefix[i] can be any integer (including negative) that we have seen. So for each j, we need to consider all k^2 such that prefix[j] - k^2 is in the set of previous prefix sums. But we don't know which k^2 to consider. We could iterate k from 0 to sqrt(prefix[j] - min_possible_prefix?) but that's not bounded nicely.
Maybe we can bound the number of squares that can appear as differences? Actually for a given prefix[j], the possible k^2 must be such that prefix[j] - k^2 is a prefix sum we have seen. But we don't know which ones. Alternatively, we could precompute all perfect squares up to a certain maximum possible absolute sum. What is the maximum possible absolute sum? If nums are integers, each could be up to, say, 10^4? Not specified. But if n is large and numbers are large, the sum could be huge. But maybe the problem expects an O(n^2) solution? Let's think about typical "squareful" subarray problems. There is a known problem: "Count the number of subarrays with sum equal to a perfect square". Usually constraints are moderate, like n <= 1000 or 5000, so O(n^2) is acceptable. But the problem says "write a function", no constraints given. We should provide a solution that is efficient for reasonable n.
Maybe we can do: For each starting index i, compute cumulative sum and check if it's a perfect square as we extend j. That is O(n^2) with O(1) check for perfect square (using sqrt). That might be acceptable if n <= 10000? But if n is 10^5, that's 10^10 operations, too many.
We need something better. Possibly using two pointers? Not monotonic. Or using hash map with dynamic programming? Consider: we want count of subarrays where sum is square. That is like count of pairs (i,j) with prefix[j]-prefix[i] square. If we could for each prefix[j], quickly count how many prefix[i] satisfy that condition. If we had a set of all previous prefix sums, we could for each possible square s, check if prefix[j]-s is in the set. But the number of s to check is the number of perfect squares up to some bound. What bound? The maximum possible s is the maximum possible difference between two prefix sums. That could be very large. But maybe we can bound s by the maximum absolute sum? Actually the sum of a subarray can be at most the sum of all positive numbers if all are positive, but if there are negatives, the maximum sum is the maximum subarray sum, which can be computed by Kadane. But that could be large.
Alternatively, we can note that perfect squares become sparse as they grow. For a given prefix[j], the number of k such that k^2 <= some upper bound is about sqrt(upper bound). But if prefix[j] is large, sqrt(prefix[j]) is much smaller than prefix[j]. So for each j, we might iterate over k from 0 to sqrt(prefix[j] - min_prefix_seen?) but we need to consider all k such that k^2 <= prefix[j] - min_prefix? Actually prefix[i] can be less than prefix[j] if the subarray sum is positive. But if the subarray sum is negative, then prefix[j] < prefix[i] and the difference is negative, cannot be square. So only consider j where prefix[j] >= prefix[i] and difference is non-negative. But wait: if nums contain negative numbers, it's possible that prefix[j] < prefix[i] and the difference is negative, which is not square. So we only care about pairs where prefix[j] >= prefix[i] and their difference is square. But that's not necessary: if prefix[j] < prefix[i], then the subarray sum is negative, not a perfect square (since perfect squares are non-negative). So indeed we only consider i such that prefix[i] <= prefix[j]. So for a given j, we only need to consider k^2 such that k^2 <= prefix[j] - min_prefix_seen_so_far? Actually we need prefix[i] = prefix[j] - k^2. For prefix[i] to be in the set of previous prefix sums, we need prefix[j] - k^2 to be one of them. And since k^2 >= 0, we have prefix[i] <= prefix[j]. So we only consider k^2 up to prefix[j] - (minimum possible prefix[i] that we have seen). But the minimum prefix[i] seen so far could be negative large? Actually if we have seen very negative prefix sums, then prefix[j] - k^2 could be very negative? But k^2 is non-negative, so prefix[j] - k^2 <= prefix[j]. So if we have seen very negative prefix sums, they might be less than prefix[j] - k^2? Actually we need prefix[i] = prefix[j] - k^2. So if k^2 is large, prefix[j] - k^2 becomes very negative. But we only have seen prefix[i] values up to the current point. If we have seen very negative values, they could be equal to prefix[j] - k^2 for some large k^2. But k^2 would then be prefix[j] - prefix[i]. Since prefix[i] could be very negative, the difference could be huge positive. So k^2 could be huge if prefix[i] is much smaller than prefix[j]. But we are iterating over k? Actually we are considering k^2 as the square. So for a given j, we need to consider all k such that k^2 = prefix[j] - prefix[i] for some i. That means k^2 can be as large as prefix[j] - min_prefix_seen_so_far. min_prefix_seen_so_far could be very small (large negative), so that difference could be huge. That would make sqrt of that huge, so iterating over k up to sqrt(prefix[j] - min_prefix) could be very large.
But perhaps we can do the opposite: For each possible square s, we can count pairs (i,j) such that prefix[j] - prefix[i] = s. This is equivalent to for each s, we count number of pairs of prefix sums that differ by s. If we have all prefix sums, we can for each prefix value p, count how many times p+s occurs. That would be like: Count = sum_{s in squares} (number of pairs (i,j) with prefix[j] - prefix[i] = s). We can compute this by scanning and using a map: as we iterate j from 0 to n, we have a map of counts of prefix sums seen so far. For current prefix[j], we want to add to answer the sum over all squares s of count[prefix[j] - s]. But again we need to iterate over all squares s that are possible. But what is the range of s? s can be from 0 up to (max_prefix - min_prefix). That could be huge. But note: s must be a perfect square. The number of perfect squares up to D is about sqrt(D). So if D is huge, say 10^10, sqrt(D)=10^5. For each j, iterating over 10^5 squares might be too heavy if n is 10^5, that's 10^10 operations. So we need to reduce.
Alternative: Instead of iterating over all squares for each j, we can iterate over possible k such that k^2 is not too large? But k^2 could be large if the prefix difference is large. But maybe the range of prefix sums is not that large? It depends on input. Without constraints, we cannot guarantee.
Maybe the intended solution is O(n^2) because n is small? The problem statement didn't specify constraints, but in many coding interview problems, n can be up to 1000 or 2000. But we should not assume.
Let's think: Is there a way to bound the number of squares we need to consider per j by something like O(sqrt(max_abs_sum))? That might be acceptable if max_abs_sum is not astronomically large. But if nums are arbitrary integers, they could be huge. But in practice, for programming problems, the numbers are usually within 32-bit or 64-bit range. The sum could be up to about 10^14 if n=10^5 and each number up to 10^9. sqrt(10^14)=10^7, which is too many per j.
Maybe we can use the fact that perfect squares are sparse. But still, for each j, we would need to check all squares up to the maximum possible difference between prefix[j] and the smallest prefix seen. That could be large.
Alternatively, we can iterate over possible k values (the square root) and for each k, we can count pairs with difference k^2. That would be like: for each k from 0 to K_max, where K_max is sqrt(max_difference), we can count pairs (i,j) such that prefix[j] - prefix[i] = k^2. How to count pairs with a given difference efficiently? If we have all prefix sums, we can use a map: for each prefix p, we add count[p] * count[p+k^2] to answer. But careful: pairs (i,j) with i<j. If we count all unordered pairs, we need to ensure order. We can do: as we iterate j, we have count of prefix sums for indices less than j. Then for current prefix[j], we add count[prefix[j] - k^2]. So that is exactly what we would do for each j and each k. But if we do it per k, we need to iterate over k for each j, same as before. Or we could precompute for each k, and then for each prefix value p, we could multiply counts? But that would count all pairs regardless of order? Actually if we have frequencies of all prefix sums (over all indices), then the total number of pairs (i<j) with difference s is sum_{p} freq[p] * freq[p+s] but that counts pairs where i and j can be any order? Actually if we have all prefix sums, and we want ordered pairs i<j such that prefix[j] - prefix[i] = s, then if we sum over all p, freq[p] * freq[p+s] counts pairs (i,j) where prefix[i]=p and prefix[j]=p+s, but it also includes i>j if we consider all occurrences? Because the frequencies are over all indices. To get ordered i<j, we need to consider the indices. Typically, when we iterate j from 0 to n, and maintain a map of frequencies of prefix[i] for i<j, then for each j we add count[prefix[j]-s]. That ensures i<j. So that's the way.
So we are back to per j, iterate over s in squares. To reduce the number of squares, we need to bound s. But what is the maximum s that could possibly yield a match? For a given j, s must be such that prefix[j] - s is in the set of previous prefix sums. So s = prefix[j] - p for some p in the set. So s is exactly the difference between prefix[j] and some previous prefix. So the set of possible s for a given j is exactly the set of differences {prefix[j] - p | p in previous prefixes}. That set could be large (up to j elements). But we only care about those that are perfect squares. So we could instead, for each previous prefix p, compute d = prefix[j] - p and check if d is a perfect square. That would be O(j) per j, leading to O(n^2). That's the naive approach. So we are trying to improve over O(n^2).
Maybe we can use some number theory to limit the number of squares we check. But the differences are arbitrary.
Perhaps the constraints are such that the array values are small? Or maybe the number of perfect squares up to the maximum sum is not too large because the maximum sum is bounded by, say, 10^4? Not given.
Given the lack of constraints, I think we should provide a solution that works for moderate n (say up to 10^4) using O(n^2) naive approach, because it's simple and correct. But we can also provide an optimized version using hash map and iterating over squares up to a bound. But we need to decide.
Let's consider typical LeetCode problem: "Number of Squareful Arrays" but that is about permutations. This is about subarrays. There is a problem "Count Number of Nice Subarrays" etc. Usually for sum problems with condition on sum, we use prefix sum and hash map. Here condition is "sum is perfect square". The number of perfect squares up to the maximum possible sum might be manageable if the maximum sum is not huge. For example, if each number is at most 10^4 and n=10^5, max sum ~ 10^9, sqrt ~ 31623. That's about 31623 squares. For each j, iterating over 31623 squares gives total operations ~ 3e9, which is borderline but maybe too slow in Python. But if we do it in C++ it might be okay? But 3e9 is still too high.
But note: we don't need to iterate over all squares up to max_possible for each j. We can iterate over squares up to prefix[j] - min_prefix_seen? But min_prefix_seen could be negative, so prefix[j] - min_prefix_seen could be large. However, we can also note that many squares will not have corresponding prefix in the map. But we still have to check each square? We need to check count[prefix[j] - s] for each s. That is a constant-time lookup per s. So the cost is number of s we iterate over. To reduce the number of s, we can bound s by the current maximum possible difference? Actually, for a given j, the maximum s that could yield a prefix[i] that we have seen is prefix[j] - min_prefix_seen_so_far (where min_prefix_seen_so_far is the minimum prefix value among indices < j). Similarly, the minimum s is prefix[j] - max_prefix_seen_so_far, but s must be non-negative, so we consider s >= 0. So s ranges from 0 to (prefix[j] - min_prefix). That could be large if min_prefix is very negative. But the number of perfect squares in that range is about sqrt(prefix[j] - min_prefix). That could still be large.
Maybe we can do it the other way: For each previous prefix p, we can record the value p. Then for each j, we want to know if prefix[j] - p is a perfect square. That's like we have a set of numbers and we want to count how many of them satisfy that prefix[j] minus that number is a square. That is like: for each j, we want to count p in set such that p = prefix[j] - k^2. So it's equivalent to: for each k, check if prefix[j] - k^2 is in the set. That is what we had.
Perhaps we can precompute all possible squares up to some global maximum difference. What is the maximum possible difference between any two prefix sums? That is max_prefix - min_prefix over the entire array. Let's denote D = max_prefix - min_prefix. Then the number of squares <= D is about sqrt(D). If D is not too large, we can precompute all squares up to D. Then for each j, we iterate over all squares s in that list, and check if prefix[j] - s is in the map. But we need to consider that for a given j, s might be larger than prefix[j] - min_prefix_seen? Actually if we use global D, some s might be larger than prefix[j] - min_prefix_seen? But we can just check; if prefix[j] - s is not in the map, it's fine. But we would be iterating over all squares up to D for each j. That's O(n * sqrt(D)). D could be large if prefix sums vary a lot. But if numbers are not huge, D might be moderate.
But what if the array has both large positive and large negative numbers? Then D could be huge. For example, if we have a prefix sum that goes up to 10^9 and down to -10^9, D = 2e9, sqrt(D) ~ 44721. That's still about 45k squares. For n=10^5, that's 4.5e9 checks, too many.
We need a better approach.
Maybe we can use the fact that perfect squares are spaced increasingly farther apart. For a given prefix[j], we can iterate k from 0 upwards while k^2 <= prefix[j] - min_prefix_seen? But min_prefix_seen may be very negative, so that bound is large. But we can also stop when k^2 becomes greater than prefix[j] - min_prefix_seen? Actually we need k^2 <= prefix[j] - p where p is a prefix seen. Since p could be as low as min_prefix_seen, the maximum k^2 we need to consider is prefix[j] - min_prefix_seen. That could be huge. But maybe we can also consider that p cannot be less than some value because we only have a finite set of p. But the set of p is exactly the prefix sums seen so far. So the maximum k^2 we need to consider is max_{p in set} (prefix[j] - p) = prefix[j] - min_prefix_seen. So indeed we need to consider all k such that k^2 <= prefix[j] - min_prefix_seen. That could be large if min_prefix_seen is very negative.
But note: min_prefix_seen might be very negative only if we have large negative numbers early on. But then prefix[j] might also be large? Not necessarily. But the difference could still be huge.
Maybe we can avoid iterating over k for each j by instead, for each prefix value p we have seen, we can "schedule" future prefix values that would make a square. That is, when we encounter a prefix value p, we can compute for each square s, the target prefix value q = p + s. Then when we later see q, we increment count. But that would require iterating over squares for each p as well, similar cost.
Another idea: Use a hash map for prefix sums, and for each j, we want to sum over all squares s the count of prefix[j] - s. We can try to iterate over the squares that are not too large. But maybe the maximum square we need to consider is bounded by the maximum absolute value of prefix sums? Actually, the difference s = prefix[j] - p. Since both prefix[j] and p are from the set of prefix sums, the maximum absolute difference between any two prefix sums is D. So s is at most D. So we only need squares up to D. That is a global bound. So we can precompute all squares up to D. But D could be large. However, note that D is the range of prefix sums. In many problems, the numbers are bounded such that the sum fits in 32-bit, so D <= 2^31-1 ~ 2e9, sqrt ~ 46341. That's about 46k squares. For n up to 10^5, total operations 4.6e9, which might be borderline in C++ but in Python it's too slow. But maybe n is smaller? Not sure.
Maybe we can optimize by only considering squares that are plausible given the current prefix[j] and the set of prefix sums. For each j, instead of iterating over all squares up to D, we could iterate over k such that k^2 <= prefix[j] - min_prefix_seen? But that is similar.
Alternatively, we could use a different representation: For each prefix value p, we store it in a set. For each j, we want to count p such that prefix[j] - p is a square. That is like we have a set of numbers and we want to query: how many numbers in the set are equal to prefix[j] minus a square. That's like multiple queries with shifting by squares. Could we precompute for each p, the squares that when added to p give a value that might appear later? That seems symmetric.
Maybe we can use the fact that perfect squares are relatively sparse. For each j, we could iterate over k from 0 to sqrt(prefix[j] - min_prefix_seen?) but that's still many.
What about using a two-pointer like approach? Not applicable.
Maybe we can accept O(n^2) for simplicity and mention that for large n we might need optimization. But the problem asks to "write a function that solves this problem", so we need to provide a working solution. We can provide an O(n^2) solution that checks all subarrays. That is straightforward: for each start i, iterate j from i to n-1, keep running sum, check if sum is perfect square. That's O(n^2) time, O(1) extra space. For n up to a few thousand, it's fine.
But if we want to be more efficient, we can use prefix sums and a hash map with precomputed squares up to a bound. Let's see if we can bound the squares by something like the maximum absolute sum of any subarray? That could be computed as the maximum of |prefix[j] - prefix[i]|. But that's the same D.
Maybe the problem expects an O(n^2) solution because it's not trivial to do better without constraints. Let's search memory: There is a known problem on LeetCode: "Count Number of Squareful Subarrays" maybe? Actually I recall a problem "Count the number of subarrays with sum equal to a perfect square" but I'm not sure. There is also "Subarray Sum Equals K" which is O(n) using hash map. Here K is not fixed but must be a perfect square. So we need to count for all squares. That is like: For each j, answer += sum_{s in squares} count[prefix[j] - s]. So if we could quickly compute sum over s of count[prefix[j]-s] without iterating over all s, maybe using convolution? But the set of squares is not a regular pattern.
Another thought: The number of squares up to X is about sqrt(X). So if X is the maximum absolute prefix difference, and if that is not too large (like if numbers are small), then iterating over all squares for each j might be okay. But we need to consider worst-case.
Perhaps we can do: Precompute all squares up to some limit, say up to max_possible_sum. What is max_possible_sum? If we assume nums are 32-bit integers, the sum of all could be up to about 2^31 * n, which for n=10^5 is huge. But maybe we can compute the actual maximum possible difference from the given array? We can compute min_prefix and max_prefix while iterating. But we need to know D before we start counting? We could first compute all prefix sums, find min and max, compute D = max - min, then precompute squares up to D. Then do a second pass: maintain a map of prefix counts, and for each prefix[j], iterate over all squares s <= D and if prefix[j] - s in map, add count. But that requires D known beforehand. That's fine: we can compute prefix sums array first, then compute min and max of prefix array. Then precompute squares up to D. Then iterate j from 0 to n, with map initially having prefix[0]=1? Actually we need to include prefix[0]=0. We'll do: map = {0:1} initially? Wait, prefix[0]=0 represents sum of empty prefix. For subarray from i to j-1, we use prefix[j] - prefix[i]. So i can be 0 to j-1. So we start with map containing prefix[0] = 1. Then for j from 1 to n, we compute prefix[j], then for each square s in squares (precomputed up to D), we check if prefix[j] - s is in map, add map[prefix[j]-s]. Then add prefix[j] to map. That works.
But careful: D is max_prefix - min_prefix over all prefix sums. But when we iterate j, the map only contains prefix sums up to j-1. The squares we consider should be such that s <= prefix[j] - min_prefix_seen_so_far? But we are iterating over all squares up to global D. That's fine because if s is larger than prefix[j] - min_prefix_seen_so_far, then prefix[j] - s will be less than min_prefix_seen_so_far, and thus not in the map. So it's safe. But we are doing extra checks for s that are too large. But the number of squares up to D is fixed. So total operations is n * (number of squares up to D). That could be large if D is large.
But what is D? D = max_prefix - min_prefix. This is the range of prefix sums. If the numbers are arbitrary, D could be huge. But in practice, if numbers are within typical integer range, D might be up to about 2*10^9 * n? Actually prefix sums are cumulative. If n is large and numbers are large, D can be huge. But if we assume 64-bit integers, D could be up to 10^15, sqrt ~ 3e7, which is too many squares.
So this approach is not scalable for huge numbers.
Maybe we can use the fact that the number of distinct prefix sums might be small? Not necessarily.
Perhaps the intended solution is indeed O(n^2) because n is at most 1000. In many problems, if they ask to count subarrays with a certain property and the property is "sum is a perfect square", they might expect O(n^2) because checking perfect square is O(1) and n^2 is acceptable for n up to 10^4. But 10^4 squared is 100 million, which is okay in C++ but borderline in Python. But if n=5000, 25 million, fine.
Given that the problem statement does not provide constraints, I think it's safe to provide an O(n^2) solution and mention that for larger inputs one could optimize using prefix sums and precomputed squares but the complexity depends on the range of sums.
But the instruction: "Write a function to find the number of 'squareful' subarrays." So we need to produce code. I'll write in Python.
I'll do:
def count_squareful_subarrays(nums):
n = len(nums)
count = 0
for i in range(n):
total = 0
for j in range(i, n):
total += nums[j]
# check if total is perfect square
if total >= 0: # only non-negative can be perfect square
root = int(total**0.5)
if root*root == total:
count += 1
return count
But careful: total could be negative, then skip. But what if total is negative? It's not a perfect square. So we can skip check if total < 0.
This is O(n^2) time, O(1) space.
But we can improve slightly by using prefix sums and for each i, we compute cumulative sum quickly? Actually the inner loop already accumulates, so it's fine.
Alternatively, using prefix sums and double loop: for i in range(n): for j in range(i+1, n+1): sum = prefix[j]-prefix[i]; check. That is also O(n^2).
I'll go with that.
But we should also consider that the sum might be large, so taking sqrt might cause floating point inaccuracies. Better to use integer sqrt. In Python, we can do: root = isqrt(total) from math module (Python 3.8+). isqrt returns integer floor sqrt. Then check root*root == total. That works for non-negative total. So we should import math.isqrt.
So:
import math
def count_squareful_subarrays(nums):
n = len(nums)
count = 0
for i in range(n):
total = 0
for j in range(i, n):
total += nums[j]
if total < 0:
continue
root = math.isqrt(total)
if root * root == total:
count += 1
return count
That's straightforward.
But is there any edge case? If total is 0? 0 is a perfect square (0^2=0). So we should count subarrays with sum 0. That's fine.
Now, we might want to optimize for large n? Could we do better? Possibly using the prefix sum and hash map with precomputed squares up to a bound, but we need to decide a bound. We could compute min_prefix and max_prefix from the prefix array, then D = max_prefix - min_prefix. Then precompute squares up to D. But D could be huge, but we can still compute squares up to D if D is not too large? But if D is huge, precomputing squares up to D is not feasible because the number of squares is sqrt(D), but we need to store them. sqrt(D) could be up to 10^7 or more, which might be memory heavy (10 million integers ~ 80 MB, maybe okay). But the iteration per j would be multiplied by n.
Maybe we can do a hybrid: For each j, we iterate over k such that k^2 <= prefix[j] - min_prefix_seen? But we can compute min_prefix_seen as we go. Actually, we can maintain the minimum prefix seen so far. But the number of k to iterate is sqrt(prefix[j] - min_prefix_seen). That could be large if min_prefix_seen is very negative. But maybe in practice min_prefix_seen is not extremely negative relative to prefix[j]? Not necessarily.
Maybe we can note that the number of squares that actually appear as differences might be limited because the prefix sums are integers and squares are sparse. But we still need to check each possible square to see if the corresponding prefix exists.
Another idea: Instead of iterating over squares, we could for each prefix[j], iterate over the set of previous prefix sums and check if the difference is a square. That is O(j) per j, leading to O(n^2) total, same as naive. So no improvement.
So it seems that without additional constraints, the best we can do is O(n^2) worst-case. But maybe there is a way to do better using some mathematical transformation? For example, representing the condition as prefix[j] = prefix[i] + k^2. That is like we have points (prefix value, index). We want to count pairs with difference a square. That's like a convolution of the indicator function of prefix sums with a function that is 1 at square positions. If we could do FFT? But the domain of prefix values might be large and not contiguous. So not easy.
Maybe we can use a technique similar to "Two Sum" but for multiple targets? Not really.
Given that, I'll present the O(n^2) solution as the main solution, and in explanation mention that for larger inputs, one could consider using prefix sums with a hash map and precomputing squares up to the maximum prefix difference, but that might still be heavy.
But the problem says "write a function that solves this problem, and explain your algorithm." So I'll explain the O(n^2) approach: iterate over all subarrays, compute sum incrementally, check if perfect square using integer sqrt.
Example: nums = [2, 2, 2]
Subarrays: [2] no (2), [2] no, [2] no, [2,2] sum=4 square, [2,2] sum=4 square (two of them? Actually subarrays: indices: (0,1):4, (1,2):4, and (0,2):6 no. So count=2.
Example: nums = [0] -> sum 0 square, count=1.
Example: nums = [-1, 1] -> subarrays: [-1] sum=-1 no, [1] sum=1 yes, [-1,1] sum=0 yes. So count=2.
Check negative: our code will skip negative total, so -1 not counted, 1 counted, 0 counted. Good.
Now, what about large numbers? Using math.isqrt is safe for large integers.
So code seems fine.
But we can also consider using prefix sums and a dictionary to reduce time if there are many repeated prefix sums? Actually if there are many repeated prefix sums, then for a given j, the number of distinct previous prefix sums might be small, but we still need to check each distinct p? We would still need to check for each p whether difference is square. That is O(number of distinct prefixes) per j. But worst-case all distinct, so O(j). Same as O(n^2).
Maybe we can use the fact that squares are of the form k^2. For each previous prefix p, we can compute d = prefix[j] - p. Then check if d is square. That is same cost.
So I think O(n^2) is the straightforward.
But wait, could we do better by iterating over possible k values and for each k, use a sliding window? For a fixed k, we want subarrays where sum = k^2. That is the classic "subarray sum equals K" problem, which can be solved in O(n) using hash map. So if we could iterate over all possible k such that k^2 <= max_possible_sum, we could solve each K=k^2 in O(n) and sum the counts. That would be O(n * number_of_squares). That's the same as before but with the roles reversed: instead of for each j iterating over squares, we iterate over squares and for each square do a linear scan. That gives O(n * sqrt(max_sum)). That might be better if the number of squares is smaller than n? But n and sqrt(max_sum) could be comparable. Actually if n is large, sqrt(max_sum) might be smaller? For example, if numbers are small, max_sum might be O(n) so sqrt(max_sum) ~ sqrt(n). Then total O(n * sqrt(n)) which is better than O(n^2). That is interesting! Let's analyze:
Suppose the numbers are bounded by some constant C, then the maximum subarray sum is at most Cn. So max_sum = O(n). Then number of squares up to max_sum is about sqrt(Cn) = O(sqrt(n)). So iterating over all squares and for each doing an O(n) pass yields O(n * sqrt(n)) total. That is better than O(n^2) for large n. However, if numbers are large, max_sum could be much larger than n, and sqrt(max_sum) might be larger than n, then O(n * sqrt(max_sum)) could be worse than O(n^2). But if max_sum is huge, sqrt(max_sum) might be less than n? Actually if max_sum is huge, say max_sum = n^2, then sqrt(max_sum)=n, so O(n^2) same. If max_sum is exponential in n, sqrt(max_sum) could be > n, but that would require numbers to be huge, but n is the number of elements, so max_sum depends on the magnitude of numbers, not on n. If numbers can be arbitrarily large, max_sum could be huge even for small n. But then O(n * sqrt(max_sum)) could be large because sqrt(max_sum) might be huge. But we could bound the number of squares by something like: we only consider squares that are possible given the actual min and max prefix differences. That number is sqrt(D) where D = max_prefix - min_prefix. If numbers are huge, D could be huge, but then n might be small? Not necessarily. For example, n=10^5 and each number is around 10^9, then max_sum could be 10^14, sqrt ~ 10^7. That's larger than n? 10^7 > 10^5? Yes, 10^7 > 10^5. So O(n * sqrt(max_sum)) = 10^5 * 10^7 = 10^12, too big. But O(n^2)=10^10, which is smaller. So the square iteration approach might be worse in that case.
But if numbers are small, say each between -100 and 100, and n=10^5, then max_sum ~ 10^7, sqrt ~ 3162, then O(n * sqrt(max_sum)) = 3e8, which is okay in C++ but in Python might be borderline but maybe acceptable with optimizations? 300 million operations in Python is likely too slow. O(n^2) would be 10^10, definitely too slow. So the square iteration approach could be better for small-magnitude numbers but worse for large-magnitude numbers. It depends on input.
Given no constraints, we might choose the approach that adapts: if the range D is small enough, we can use the square iteration method; otherwise, fall back to O(n^2)? But we don't know which is better.
Maybe we can compute D quickly after first pass (computing prefix sums). Then decide: if sqrt(D) < n, then use the method that iterates over squares (O(n * sqrt(D))), else use O(n^2). But we need to implement both. That might be overkill.
But the problem likely expects a simple solution. I'll stick to O(n^2) because it's simple and works for moderate n. In explanation, I can mention that for larger n, an optimization using prefix sums and iterating over possible square values can be used, but its complexity depends on the range of prefix sums.
Given the instruction "write a function", I'll provide a clean Python function using O(n^2). I'll also include a note about using math.isqrt for integer sqrt.
But let's think: The O(n^2) solution might time out if n is large (like 10^5). But without constraints, perhaps the intended n is small. Many subarray counting problems have n up to 10^3 or 10^4.
I'll write the function and explain.
However, to be thorough, I'll also present an alternative optimized approach in explanation, but code only the O(n^2) one? The problem says "write a function". I should provide one function. I could provide the optimized one using prefix sums and precomputed squares up to a bound, but I need to decide a bound. I could compute the min and max prefix sums first, then D = max - min. Then precompute all squares up to D. Then use a hash map. That would be O(n + sqrt(D) + n * sqrt(D))? Actually precomputing squares is O(sqrt(D)). Then the main loop is O(n * sqrt(D)). That might be acceptable if sqrt(D) is not huge. But if D is huge, this could be slow. But we could also check: if sqrt(D) > some threshold (like 10^5), then maybe we revert to O(n^2)? But that would be complex.
Maybe we can assume that the numbers are not extremely large, so D is manageable. But we can't assume.
Given that this is an interview-style question, they might expect the O(n^2) solution with a note about optimization. I'll provide the O(n^2) solution as it's safe for small inputs.
But let's see if we can do O(n^2) with some early termination? Not really.
I'll go with O(n^2) and explain.
But wait, there is also possibility of using dynamic programming? Not really.
Another thought: We can use the fact that the sum of a subarray can be computed quickly with prefix sums, and we can iterate over all starting indices and for each, we can break early if the sum becomes too large? But perfect squares are not monotonic; sum can increase or decrease depending on sign of numbers. If numbers are non-negative, then as we extend the subarray, the sum increases. Then we could use two pointers? Actually if all numbers are non-negative, then for a fixed start i, the sum increases with j. Then we could for each i, use a pointer j and maintain current sum, and for each j, check if sum is square. That's still O(n^2) but could be optimized by precomputing squares and using binary search? For non-negative numbers, the sum is increasing, so for each i, we could find the j where sum reaches a certain square? But squares are sparse. But still, we would need to check each j? Not necessarily: we could for each i, we want to count j such that sum(i,j) is square. That's like we have a list of squares: s0, s1, s2,... up to max_sum. For each i, we want to find j such that prefix[j] = prefix[i] + s_k. Since prefix[j] is increasing (if numbers non-negative), we could binary search for each square? But that would be O(number_of_squares * log n) per i, total O(n * sqrt(max_sum) * log n), which might be better than O(n^2) if sqrt(max_sum) is small. But if numbers can be negative, prefix is not monotonic, so binary search not possible.
So we cannot rely on monotonicity unless we assume non-negative. The problem doesn't say non-negative.
Thus, the general case requires handling negatives, so prefix not monotonic.
Therefore, the simple O(n^2) is the safest.
I'll implement that.
But before finalizing, I'll consider if there is any way to do better in the general case. Maybe using meet-in-the-middle? Not likely.
Maybe we can use the following: The number of perfect squares up to X is about sqrt(X). If we can bound X by something like the maximum absolute value of any element times n? That is still large.
Given the lack of constraints, I'll produce the O(n^2) solution and in explanation, discuss the possibility of optimization.
Now, write the function.
Edge cases: empty array? Should return 0.
We'll implement:
def count_squareful_subarrays(nums):
import math
n = len(nums)
count = 0
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
if s < 0:
continue
root = math.isqrt(s)
if root * root == s:
count += 1
return count
That's it.
But we might want to use a faster integer sqrt? math.isqrt is fine.
Let's simulate [-1,1]:
i=0: s=-1 (skip), then s +=1 -> s=0, check: isqrt(0)=0, 00=0 -> count=1.
i=1: s=1, check: isqrt(1)=1, 11=1 -> count=2. So returns 2.
Good.
Now, what about [1, -1]? i=0: s=1 -> square? 1 is square, count=1. Then s += -1 -> s=0 -> square, count=2. i=1: s=-1 skip. So count=2. Subarrays: [1] sum=1 square, [1,-1] sum=0 square, [-1] not. So 2.
All good.
Now, performance: for n=1000, about 500k iterations, fine. For n=10000, about 50 million, might be slow in Python but maybe acceptable if optimized? 50 million checks with math.isqrt might be heavy. But we can maybe avoid isqrt for every iteration? We could precompute squares up to a certain bound? But the sums vary. However, we can note that for a fixed i, as we extend j, the sum changes by adding nums[j]. We could keep track of current sum and maybe check if it's a square by comparing to next square? But that would require generating squares on the fly. Not sure.
Maybe we can precompute a set of squares up to the maximum possible sum for the entire array? But the maximum sum for any subarray might be less than total sum of positives. We could compute the maximum possible absolute subarray sum? That is the maximum subarray sum (Kadane) and the minimum subarray sum. But we need squares up to max_abs_sum. That could be precomputed once. Then for each subarray sum, we can check if it's in the set of squares. That would be O(1) check with a set. But we need to generate all squares up to max_abs_sum. How to get max_abs_sum? We can compute the maximum possible absolute sum of any subarray. That is max( max_subarray_sum, -min_subarray_sum ). Actually we need the maximum absolute value of subarray sum. That could be as high as the sum of absolute values of all elements if they alternate? But worst-case, if all positive, max sum = sum(all), min sum = min element? Actually min subarray sum could be negative if negatives exist. The absolute maximum could be max( max_subarray_sum, -min_subarray_sum ). That could be computed in O(n) using Kadane for max and min subarray sums. But that gives the maximum absolute sum of any contiguous subarray. Then we can precompute all squares up to that value. Then in the double loop, we can check if the absolute value of sum is in the square set? But careful: sum could be negative, but we only care about non-negative squares. So if sum is negative, skip. So we only need squares up to max_subarray_sum (the maximum positive sum). But there could be subarrays with sum larger than max_subarray_sum? No, max_subarray_sum is the maximum sum over all subarrays. So the maximum positive sum we might encounter is max_subarray_sum. So we can precompute squares up to max_subarray_sum. That number of squares is about sqrt(max_subarray_sum). That might be much smaller than the number of subarrays. Then in the double loop, we can check if sum is in the precomputed square set (if sum >=0). That would be O(1) check per subarray. The double loop is still O(n^2), but the check is faster? math.isqrt might be fast, but set membership might be faster? Possibly. But we can precompute squares set only if max_subarray_sum is not too large. But if max_subarray_sum is huge, the set could be huge. But we can avoid precomputing if it's too large? But we can still compute sqrt for each sum. I think math.isqrt is fast enough for integers.
But the double loop is the bottleneck.
So O(n^2) is acceptable for n up to a few thousand.
Given that the problem statement does not specify constraints, I'll assume n is moderate.
Thus, final solution: O(n^2) time, O(1) space.
I'll write the function accordingly.
Now, I need to produce the answer in the required format: provide the function and explanation.
I'll include an explanation of algorithm, time and space complexity, and note about possible optimizations.
Let's craft the response.
We are given an array nums of integers. We need to count the number of contiguous subarrays whose sum is a perfect square (i.e., an integer that is the square of another integer, such as 0, 1, 4, 9, ...). Negative sums cannot be perfect squares, so they are ignored.
Algorithm
We use a straightforward approach that checks every possible subarray:
Iterate over all starting indices i from 0 to n-1.
For each start i, maintain a running sum s as we extend the subarray to the right.
For each ending index j (from i to n-1), add nums[j] to s.
If the current sum s is non‑negative, test whether it is a perfect square:
Compute the integer square root r = isqrt(s) (the floor of the square root).
If r * r == s, then s is a perfect square → increment the count.
Continue until all subarrays have been considered.
We use math.isqrt for an exact integer square root without floating‑point errors.
Correctness
The algorithm examines every contiguous subarray exactly once. For each subarray, it computes the sum correctly by cumulative addition. The check r * r == s is true iff s is a perfect square (including 0). Therefore, every squareful subarray is counted exactly once, and no non‑squareful subarray is counted.
Complexity Analysis
Time: There are n starting positions and for each start we scan up to n elements → O(n²) subarrays. The perfect square check is O(1) using isqrt. Overall time complexity is O(n²).
Space: Only a few integer variables are used → O(1) auxiliary space.
Note
For very large n (e.g., n > 10⁴), this solution may become slow in Python. A more advanced method could use prefix sums with a hash map and iterate over all perfect squares up to the maximum possible subarray sum (which is about √(max_sum) per position), but that approach’s performance depends heavily on the magnitude of the numbers. The simple O(n²) solution is robust and works well for moderate input sizes.
Code
python
import math
def count_squareful_subarrays(nums):
"""
Count the number of contiguous subarrays whose sum is a perfect square.
Args:
nums: List[int] - the input array of integers.
Returns:
int - number of squareful subarrays.
"""
n = len(nums)
count = 0
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
if s < 0:
continue # negative sums cannot be perfect squares
r = math.isqrt(s)
if r * r == s:
count += 1
return count
Example Usage
python
print(count_squareful_subarrays([1, 2, 3])) # Output: 1 (subarray [1])
print(count_squareful_subarrays([2, 2, 2])) # Output: 2 (subarrays [2,2] at positions (0,1) and (1,2))
print(count_squareful_subarrays([0])) # Output: 1 (subarray [0])
print(count_squareful_subarrays([-1, 1])) # Output: 2 (subarrays [1] and [-1,1] sum to 1 and 0)