This problem falls in P. Here's an O(n)
solution.
Let's do some algebra with prefix sums:
j - i = p * (prefix_sum_j - prefix_sum_i)
j - i = p * prefix_sum_j - p * prefix_sum_i
j - p * prefix_sum_j = i - p * prefix_sum_i
p * prefix_sum_j - j = p * prefix_sum_i - i
JavaScript code with testing against brute force.
const f = (nums, p) =>
nums.reduce(([map, sum, answer], val, i) => {
const newSum = sum + val;
answer += p * newSum == i + 1;
answer += map[p * newSum - i] || 0;
map[p * newSum - i] = (map[p * newSum - i] || 0) + 1;
return [map, newSum, answer];
}, [{}, 0, 0])[2];
console.log('Input: [2,-1,3,0,1,2,1], 2')
console.log('Output: ' + f([2,-1,3,0,1,2,1], 2));
function bruteForce(A, p){
let result = 0;
for (let windowSize=1; windowSize<=A.length; windowSize++){
for (let start=0; start<A.length-windowSize+1; start++){
let sum = 0;
for (let end=start; end<start+windowSize; end++)
sum += A[end];
if (p * sum == windowSize)
result += 1;
}
}
return result;
}
var numTests = 500;
var n = 20;
var m = 20;
var pRange = 10;
console.log('\nTesting against brute force...')
for (let i=0; i<numTests; i++){
const A = new Array(n);
for (let j=0; j<n; j++)
A[j] = Math.floor(Math.random() * m) * [1, -1][Math.floor(Math.random()*2)];
const p = Math.floor(Math.random() * pRange) * [1, -1][Math.floor(Math.random()*2)];
_f = f(A, p);
_brute = bruteForce(A, p);
//console.log(String([_f, _brute, p, JSON.stringify(A)]));
if (_f != _brute){
console.log('MISMATCH!');
console.log(p, JSON.stringify(A));
console.log(_f, _brute);
break;
}
}
console.log('Done testing.')
In case it helps readers, the function, f
, as a for
loop could look like:
function f(A, p){
const seen = {}; // Map data structure
let sum = 0;
let result = 0;
for (let i=0; i<A.length; i++){
sum += A[i];
result += p * sum == i + 1; // Boolean evaluates to 1 or 0
result += seen[p * sum - i] || 0;
seen[p * sum - i] = (seen[p * sum - i] || 0) + 1;
}
return result;
}
My (first) attempt at C# code:
using System;
using System.Collections.Generic;
public class Solution{
static int f(int[] A, int p){
var seen = new Dictionary<int, int>();
int sum = 0;
int result = 0;
for (int i=0; i<A.Length; i++){
sum += A[i];
result += Convert.ToInt32( p * sum == i + 1 );
int key = p * sum - i;
if (seen.ContainsKey(key)){
result += seen[key];
seen[key] += 1;
} else {
seen[key] = 1;
}
}
return result;
}
public static void Main(){
int[] A = new int[7]{2, -1, 3, 0, 1, 2, 1};
int p = 2;
Console.WriteLine(f(A, p));
}
}