Minimum steps to convert an Array into permutation of numbers from 1 to N
Last Updated :
28 Jun, 2022
Given an array arr of length N, the task is to count the minimum number of operations to convert given sequence into a permutation of first N natural numbers (1, 2, …., N). In each operation, increment or decrement an element by one.
Examples:
Input: arr[] = {4, 1, 3, 6, 5}
Output: 4
Apply decrement operation four times on 6
Input : arr[] = {0, 2, 3, 4, 1, 6, 8, 9}
Output : 7
Approach: An efficient approach is to sort the given array and for each element, find the difference between the arr[i] and i(1 based indexing). Find the sum of all such difference, and this will be the minimum steps required.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int get_permutation( int arr[], int n)
{
sort(arr, arr + n);
int result = 0;
for ( int i = 0; i < n; i++) {
result += abs (arr[i] - (i + 1));
}
return result;
}
int main()
{
int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << get_permutation(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int get_permutation( int arr[], int n)
{
Arrays.sort(arr);
int result = 0 ;
for ( int i = 0 ; i < n; i++) {
result += Math.abs(arr[i] - (i + 1 ));
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 };
int n = arr.length;
System.out.print(get_permutation(arr, n));
}
}
|
Python3
def get_permutation(arr, n):
arr = sorted (arr)
result = 0
for i in range (n):
result + = abs (arr[i] - (i + 1 ))
return result
if __name__ = = '__main__' :
arr = [ 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 ]
n = len (arr)
print (get_permutation(arr, n))
|
C#
using System;
class GFG{
static int get_permutation( int []arr, int n)
{
Array.Sort(arr);
int result = 0;
for ( int i = 0; i < n; i++) {
result += Math.Abs(arr[i] - (i + 1));
}
return result;
}
public static void Main()
{
int []arr = { 0, 2, 3, 4, 1, 6, 8, 9 };
int n = arr.Length;
Console.Write(get_permutation(arr, n));
}
}
|
Javascript
<script>
function get_permutation(arr , n)
{
arr.sort();
var result = 0;
for (i = 0; i < n; i++) {
result += Math.abs(arr[i] - (i + 1));
}
return result;
}
var arr = [ 0, 2, 3, 4, 1, 6, 8, 9 ];
var n = arr.length;
document.write(get_permutation(arr, n));
</script>
|
Time Complexity: O(n*log(n))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...