Find total number of positions in all Subarrays such that position and value are same
Last Updated :
26 Sep, 2022
Given an array A[] of size N, the task is to find the total number of positions in all the subarrays such that the value and position are the same.
Examples:
Input: A[] = {1, 2}
Output: 3
?Explanation: Following are the subarrays:
In the subarray A[1, 1] = [1], elementat position 1 is 1.
In the subarray A[1, 2] = [1, 2], for both the elements the condition is satisfied.
In the subarray A[2, 2] = [2], element at position is 2 which is the only element.
Hence the total positions over all subarrays = 1 + 2 + 0 = 3.
Input: A[] = {1, 3, 4, 2}
Output: 5
Approach: The problem can be solved based on the following observation:
Fix some position 1 ? i ? N and a subarray A[L, R]
Further, the condition of i being a valid position is Ai = i ? L + 1. Rewriting this condition, we obtain L = i ? Ai + 1, in other words, there is exactly one choice of L given that i is symmetrical.
However, we must also have L ? 1, so i ? Ai + 1 ? 1? i ? Ai.
The choice of R doesn’t affect i being a symmetrical point, so any R such that R ? i works, and there are N ? i + 1 of these.
Our final answer is thus simply the sum of N ? i + 1 over all positions 1 ? i ? N such that Ai ? i.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int count( int arr[], int N)
{
int temp = 0;
for ( int i = 0; i < N; i++) {
if (arr[i] <= i + 1)
temp = temp + N - i;
}
return temp;
}
int main()
{
int A[] = { 1, 2 };
int N = sizeof (A) / sizeof (A[0]);
cout << count(A, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
public static int count( int arr[], int N)
{
int temp = 0 ;
for ( int i = 0 ; i < N; i++) {
if (arr[i] <= i + 1 )
temp = temp + N - i;
}
return temp;
}
public static void main(String[] args)
{
int A[] = { 1 , 2 };
int N = A.length;
System.out.println(count(A, N));
}
}
|
Python3
def count(arr, N):
temp = 0
for i in range ( 0 , N):
if (arr[i] < = i + 1 ):
temp = temp + N - i
return temp
A = [ 1 , 2 ]
N = len (A)
print (count(A, N))
|
C#
using System;
public class GFG{
static int count( int [] arr, int N)
{
int temp = 0;
for ( int i = 0; i < N; i++) {
if (arr[i] <= i + 1)
temp = temp + N - i;
}
return temp;
}
public static void Main (){
int [] A = {1, 2};
int N = A.Length;
Console.Write(count(A, N));
}
}
|
Javascript
<script>
function count( arr, N)
{
let temp = 0;
for (let i = 0; i < N; i++) {
if (arr[i] <= i + 1)
temp = temp + N - i;
}
return temp;
}
let A = [ 1, 2 ];
let N = A.length;
console.log(count(A, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...