Synechron | L4 Round 1 | Counting Contiguous Fragments with Given Arithmetic Mean
Anonymous User
717
Jul 11, 2024
Synechron interview experience for Software Engineer L4.
Online Assessment Question:
Count number of subarrays with arithmetic mean k or Counting Contiguous Fragments with Given Arithmetic Mean
You are given an array A of N integers and an integer S. Your task is to compute how many ways one can choose a contiguous fragment of A that has an arithmetic mean equal to S. The arithmetic mean (average) of a fragment is the sum of the elements of the fragment divided by its length. For example, the arithmetic mean of (1, 4, 4, 5] is 14/4 = 3.5. Write a function: class Solution { public int solution(intll A, int S) ; } which returns the number of contiguous fragments of A whose arithmetic means are equal to S. If the result is greater than 1,000,000,000, your function should return 1,000,000,000.
Examples:
- Given A = [2, 1, 3] and S = 2, your function should return 3, since the
arithmetic means of fragments (2], [1, 3] and [2, 1, 3] are equal to 2. - Given A = [0, 4, 3, - 1] and S = 2, your function should return 2, since
fragments [0, 4] and [4, 3, -1] have an arithmetic mean equal to 2. - Given A = [2, 1, 4] and S = 3, your function should return 0, since there
exist no contiguous fragments whose arithmetic mean is equal to 3.
Write an efficient algorithm for the following assumptions:
• N is an integer within the range [1..100,000);
• Sis an integer within the range [-1,000,000,000.. 1,000,000,0001;
class Solution {
public int solution(int[] A, int S) {
int count = 0;
int n = A.length;
for (int start = 0; start < n; start++) {
long sum = 0;
for (int end = start; end < n; end++) {
sum += A[end];
// Check if the current subarray has the required average
if (sum == (long)S * (end - start + 1)) {
count++;
}
}
if (count > 1_000_000_000) {
return 1_000_000_000;
}
}
return count;
}
}Accepted .... my tried optimizing it but i got 1st test case failed got 2 instead of 3
will update on this poost soon
Mean time if you find any optimsed solution please add it it will be help full!
Comments (2)

