Number of moves required to guess a permutation.
Last Updated :
08 Jul, 2022
Given an integer N and there is a hidden permutation (of numbers from 1 to N, each occurring exactly once) that you need to guess. You can do the following:
Choose a number at 1st position:
- If it is correct, you guess the next position.
- If it is wrong, the whole permutation resets and you go back to guessing the first position.
You can perform trial and error to arrive at the correct permutation, you can also use your previous knowledge for the next guesses. i.e if you know the number at first position correctly, and get 2nd position wrong, in the next move you can input the first position correctly and move on to the second position.
Find the minimum number of moves that it would take in the worst case scenario to get the entire permutation correct.
Examples:
Input: N = 2
Output: 3
You choose 2 for 1st position, and the permutation resets.
You choose 1 for 1st position, the guess is correct and now you are to guess for the 2nd position.
You choose 2 for the 2nd position since that is the only remaining option you have.
Input: N = 3
Output: 7
Approach: To guess the ith position correctly, it would take (n-i) guesses. And for each guess you would need to make total of i moves( (i-1) moves to enter the correct prefix that you already know and 1 move to guess the current one). In the final step, it would take you N more moves to enter the correct permutation.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countMoves( int n)
{
int ct = 0;
for ( int i = 1; i <= n; i++)
ct += i * (n - i);
ct += n;
return ct;
}
int main()
{
int n = 3;
cout << countMoves(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int countMoves( int n)
{
int ct = 0 ;
for ( int i = 1 ; i <= n; i++)
ct += i * (n - i);
ct += n;
return ct;
}
public static void main (String[] args) {
int n = 3 ;
System.out.println( countMoves(n));
}
}
|
Python3
def countMoves(n):
ct = 0
for i in range ( 1 , n + 1 ):
ct + = i * (n - i)
ct + = n
return ct
if __name__ = = "__main__" :
n = 3
print (countMoves(n))
|
C#
using System;
class GFG {
static int countMoves( int n)
{
int ct = 0;
for ( int i = 1; i <= n; i++)
ct += i * (n - i);
ct += n;
return ct;
}
static void Main()
{
int n = 3;
Console.WriteLine(countMoves(n));
}
}
|
PHP
<?php
function countMoves( $n )
{
$ct = 0;
for ( $i = 1; $i <= $n ; $i ++)
$ct += $i * ( $n - $i );
$ct += $n ;
return $ct ;
}
$n = 3;
echo countMoves( $n );
?>
|
Javascript
<script>
function countMoves(n)
{
let ct = 0;
for (let i = 1; i <= n; i++)
ct += i * (n - i);
ct += n;
return ct;
}
let n = 3;
document.write(countMoves(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...