Arithmetic Subarrays
You are given an array ‘A’ of length ‘N’, you have to tell the number of arithmetic subarrays that exist in the array ‘A’.
An Arithmetic subarray is a subarray that has 3 or more elements and the difference between consecutive elements is the same. Eg: [1, 3, 5, 7] has a length of 4, and diff between any two consecutive elements is 2.
Note:
A subarray is a slice from a contiguous array (i.e., occupy consecutive positions) and inherently maintains the order of elements.
Input Format:
The first line of the input contains ‘T’ denoting the number of test cases.
The first line of each test case contains the three integers N, length of the array.
The second line of each test case contains N space-separated integers of the array A.
Output Format:
For each test case, return the number of arithmetic subarrays that can be formed.
Note:
Don't print anything it has already been taken care of. Just implement the given function
Constraints:
1 <= T <= 100
1 <= N <= 3000
0 <= A[i] <= 5000
Time Limit: 1 second
AnswerBot
1y
Count the number of arithmetic subarrays in an array.
An arithmetic subarray has 3 or more elements with the same difference between consecutive elements.
Loop through the array and check for all possib...read more
CodingNinjas
author
2y
We use a vector of unordered_maps for our dynamic programming.
The vector is used as follows: [ index, {diff, count} ].
For each index, we have all common differences and count arithmetic slices up to t...read more
CodingNinjas
author
2y
Brute Force
Here we use a simple idea that if we have an arithmetic subarray A[i...j] of difference ’d’ between two consecutive elements, then to check if subarray A[i….j+1] is also arithmetic subarra...read more
CodingNinjas
author
2y
Counting arithmetic subarrays
- If our A= [1 2 3 4 5 7 9 11] then B= [ 0 0 1 2 3 0 1 2], where ‘B’ is an array that tells the number of subarrays ending at index ‘i’, and we can clearly see some pattern ...read more
Add answer anonymously...
Top Dunzo Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app