Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if an Array is a permutation of numbers from 1 to N : Set 2
Next article icon

Minimum steps to convert an Array into permutation of numbers from 1 to N

Last Updated : 28 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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




// C++ program to find minimum number of steps to
// convert a given sequence into a permutation
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number of steps to
// convert a given sequence into a permutation
int get_permutation(int arr[], int n)
{
    // Sort the given array
    sort(arr, arr + n);
 
    // To store the required minimum
    // number of operations
    int result = 0;
 
    // Find the operations on each step
    for (int i = 0; i < n; i++) {
        result += abs(arr[i] - (i + 1));
    }
 
    // Return the answer
    return result;
}
 
// Driver code
int main()
{
    int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << get_permutation(arr, n);
 
    return 0;
}
 
 

Java




// Java program to find minimum number of steps to
// convert a given sequence into a permutation
import java.util.*;
 
class GFG{
  
// Function to find minimum number of steps to
// convert a given sequence into a permutation
static int get_permutation(int arr[], int n)
{
    // Sort the given array
    Arrays.sort(arr);
  
    // To store the required minimum
    // number of operations
    int result = 0;
  
    // Find the operations on each step
    for (int i = 0; i < n; i++) {
        result += Math.abs(arr[i] - (i + 1));
    }
  
    // Return the answer
    return result;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 };
  
    int n = arr.length;
  
    // Function call
    System.out.print(get_permutation(arr, n));
  
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to find minimum number of steps to
# convert a given sequence into a permutation
 
# Function to find minimum number of steps to
# convert a given sequence into a permutation
def get_permutation(arr, n):
 
    # Sort the given array
    arr = sorted(arr)
 
    # To store the required minimum
    # number of operations
    result = 0
 
    # Find the operations on each step
    for i in range(n):
        result += abs(arr[i] - (i + 1))
 
    # Return the answer
    return result
 
# Driver code
if __name__ == '__main__':
    arr=[0, 2, 3, 4, 1, 6, 8, 9]
    n = len(arr)
 
    # Function call
    print(get_permutation(arr, n))
 
# This code is contributed by mohit kumar 29   
 
 

C#




// C# program to find minimum number of steps to
// convert a given sequence into a permutation
using System;
  
class GFG{
 
// Function to find minimum number of steps to
// convert a given sequence into a permutation
static int get_permutation(int []arr, int n)
{
    // Sort the given array
    Array.Sort(arr);
 
    // To store the required minimum
    // number of operations
    int result = 0;
 
    // Find the operations on each step
    for (int i = 0; i < n; i++) {
        result += Math.Abs(arr[i] - (i + 1));
    }
 
    // Return the answer
    return result;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 0, 2, 3, 4, 1, 6, 8, 9 };
 
    int n = arr.Length;
 
    // Function call
    Console.Write(get_permutation(arr, n));
}
}
 
// This code is contributed by shivanisinghss2110
 
 

Javascript




<script>
// javascript program to find minimum number of steps to
// convert a given sequence into a permutation
 
// Function to find minimum number of steps to
// convert a given sequence into a permutation
function get_permutation(arr , n)
{
 
    // Sort the given array
    arr.sort();
  
    // To store the required minimum
    // number of operations
    var result = 0;
  
    // Find the operations on each step
    for (i = 0; i < n; i++) {
        result += Math.abs(arr[i] - (i + 1));
    }
  
    // Return the answer
    return result;
}
  
// Driver code
var arr = [ 0, 2, 3, 4, 1, 6, 8, 9 ];
var n = arr.length;
  
// Function call
document.write(get_permutation(arr, n));
 
// This code is contributed by Amit Katiyar
</script>
 
 
Output: 
7

 

Time Complexity: O(n*log(n))
Auxiliary Space: O(1)



Next Article
Check if an Array is a permutation of numbers from 1 to N : Set 2

I

IshwarGupta
Improve
Article Tags :
  • Arrays
  • DSA
  • Sorting
  • Natural Numbers
  • permutation
Practice Tags :
  • Arrays
  • permutation
  • Sorting

Similar Reads

  • Change the array into a permutation of numbers from 1 to n
    Given an array A of n elements. We need to change the array into a permutation of numbers from 1 to n using minimum replacements in the array. Examples: Input : A[] = {2, 2, 3, 3} Output : 2 1 3 4 Explanation: To make it a permutation of 1 to 4, 1 and 4 are missing from the array. So replace 2, 3 wi
    5 min read
  • Check if an Array is a permutation of numbers from 1 to N : Set 2
    Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The
    4 min read
  • Check if an Array is a permutation of numbers from 1 to N
    Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The
    15+ min read
  • Minimum cost to make an Array a permutation of first N natural numbers
    Given an array arr of positive integers of size N, the task is to find the minimum cost to make this array a permutation of first N natural numbers, where the cost of incrementing or decrementing an element by 1 is 1.Examples: Input: arr[] = {1, 1, 7, 4} Output: 5 Explanation: Perform increment oper
    4 min read
  • Minimize sum of numbers required to convert an array into a permutation of first N natural numbers
    Given an array A[] of size N, the task is to find the minimum sum of numbers required to be added to array elements to convert the array into a permutation of 1 to N. If the array can not be converted to desired permutation, print -1. Examples: Input: A[] = {1, 1, 1, 1, 1}Output: 10Explanation: Incr
    5 min read
  • Minimum number of increment/decrement operations such that array contains all elements from 1 to N
    Given an array of N elements, the task is to convert it into a permutation (Each number from 1 to N occurs exactly once) by using the following operations a minimum number of times: Increment any number.Decrement any number. Examples: Input: arr[] = {1, 1, 4} Output: 2 The array can be converted int
    4 min read
  • Minimum operations to convert an Array into a Permutation of 1 to N by replacing with remainder from some d
    Given an array arr[] of size N, the task is to find the minimum number of operations to convert the array into a permutation of [1, n], in each operation, an element a[i] can be replaced by a[i] % d where d can be different in each operation performed. If it is not possible print -1. Examples: Input
    8 min read
  • Count minimum number of "move-to-front" moves to sort an array
    Given an array of size n such that array elements are in range from 1 to n. The task is to count a number of move-to-front operations to arrange items as {1, 2, 3,... n}. The move-to-front operation is to pick any item and place it in first position. This problem can also be seen as a stack of items
    6 min read
  • Find the Number of Permutations that satisfy the given condition in an array
    Given an array arr[] of size N, the task is to find the number of permutations in the array that follows the given condition: If K is the maximum element in the array, then the elements before K in the array should be in the ascending order and the elements after K in the array should be in the desc
    12 min read
  • Minimum cost to sort a matrix of numbers from 0 to n^2 - 1
    Given an n x n matrix containing all the numbers in the range 0 to n2-1. The problem is to calculate the total energy required for rearranging all the numbers in the matrix in strictly increasing order, i.e., after the rearrangement, the 1st row contains 'n' numbers from 0 to n-1, then 2nd row from
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences