Number of valid indices in the permutation of first N natural numbers
Given a permutation P of first N natural numbers. The task is to find the number of i’s such that Pi ? Pj for all 1 ? j ? i in the permutation of first N natural numbers.
Examples:
Input: arr[] = {4, 2, 5, 1, 3}
Output: 3
0, 1 and 3 are such indices.
Input: arr[] = {4, 3, 2, 1}
Output: 4
Approach: For i = 1, …, N, define Mi = min{ Pj, 1 ? j ? i}. Now, when i(1 ? i ? N) is fixed, Mi = Pi holds if and only if for all j(1 ? j ? i), Pi ? Pj holds. Therefore, it is enough to calculate all the Mi. These can be calculated in the increasing order of i, so the problem could be solved in a total of O(N) time.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int min_index( int p[], int n)
{
int ans = 0;
int mini = INT_MAX;
for ( int i = 0; i < n; i++) {
if (p[i] <= mini)
mini = p[i];
if (mini == p[i])
ans++;
}
return ans;
}
int main()
{
int P[] = { 4, 2, 5, 1, 3 };
int n = sizeof (P) / sizeof ( int );
cout << min_index(P, n);
return 0;
}
|
Java
class GFG
{
static int INT_MAX = Integer.MAX_VALUE;
static int min_index( int p[], int n)
{
int ans = 0 ;
int mini = INT_MAX;
for ( int i = 0 ; i < n; i++)
{
if (p[i] <= mini)
mini = p[i];
if (mini == p[i])
ans++;
}
return ans;
}
public static void main (String[] args)
{
int P[] = { 4 , 2 , 5 , 1 , 3 };
int n = P.length;
System.out.println(min_index(P, n));
}
}
|
Python3
import sys
INT_MAX = sys.maxsize
def min_index(p, n) :
ans = 0 ;
mini = INT_MAX;
for i in range (n) :
if (p[i] < = mini) :
mini = p[i];
if (mini = = p[i]) :
ans + = 1 ;
return ans;
if __name__ = = "__main__" :
P = [ 4 , 2 , 5 , 1 , 3 ];
n = len (P);
print (min_index(P, n));
|
C#
using System;
class GFG
{
static int INT_MAX = int .MaxValue;
static int min_index( int []p, int n)
{
int ans = 0;
int mini = INT_MAX;
for ( int i = 0; i < n; i++)
{
if (p[i] <= mini)
mini = p[i];
if (mini == p[i])
ans++;
}
return ans;
}
public static void Main ()
{
int []P = { 4, 2, 5, 1, 3 };
int n = P.Length;
Console.WriteLine(min_index(P, n));
}
}
|
Javascript
<script>
function min_index(p, n)
{
let ans = 0;
let mini = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
if (p[i] <= mini)
mini = p[i];
if (mini == p[i])
ans++;
}
return ans;
}
let P = [ 4, 2, 5, 1, 3 ];
let n = P.length;
document.write(min_index(P, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
01 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...