Count minimum number of “move-to-front” moves to sort an array

06 Jul, 2022
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 with only move available is to pull an item from the stack and placing it on top of the stack. 
Examples : 
Input: arr[] = {3, 2, 1, 4}.
Output: 2
First, we pull out 2 and places it on top, 
so the array becomes (2, 3, 1, 4). After that, 
pull out 1 and becomes (1, 2, 3, 4).

Input:  arr[] = {5, 7, 4, 3, 2, 6, 1}
Output:  6
We pull elements in following order
7, 6, 5, 4, 3 and 2

Input: arr[] = {4, 3, 2, 1}.
Output: 3
The idea is to traverse array from end. We expect n at the end, so we initialize expectedItem as n. All the items which are between actual position of expectedItem and current position must be moved to front. So we calculate the number of items between current item and expected item. Once we find expectedItem, we look for next expectedItem by reducing expectedITem by one. 
Following is the algorithm for the minimum number of moves: 
1. Initialize expected number at current position as n 
2. Start from the last element of array.
     a) If the current item is same as expected item, 
           decrease expected item by 1.
3. Return expected item.
Below is the implementation of this approach. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum number of move-to-front// moves to arrange items in sorted order.#include <bits/stdc++.h>using namespace std; // Calculate minimum number of moves to arrange array// in increasing order.int minMoves(int arr[], int n){    // Since we traverse array from end, expected item    // is initially  n    int expectedItem = n;     // Traverse array from end    for (int i=n-1; i >= 0; i--)    {        // If current item is at its correct position,        // decrement the expectedItem (which also means        // decrement in minimum number of moves)        if (arr[i] == expectedItem)            expectedItem--;    }     return expectedItem;} // Driver Programint main(){    int arr[] = {4, 3, 2, 1};    int n = sizeof(arr)/sizeof(arr[0]);    cout << minMoves(arr, n);    return 0;}
// java program to find minimum// number of move-to-front moves// to arrange items in sorted order.import java.io.*; class GFG{    // Calculate minimum number of moves    // to arrange array in increasing order.    static int minMoves(int arr[], int n)    {        // Since we traverse array from end,        // expected item is initially n        int expectedItem = n;             // Traverse array from end        for (int i = n - 1; i >= 0; i--)        {            // If current item is at its correct position,            // decrement the expectedItem (which also means            // decrement in minimum number of moves)            if (arr[i] == expectedItem)                expectedItem--;        }             return expectedItem;    }         // Driver Program    public static void main (String[] args)    {        int arr[] = {4, 3, 2, 1};        int n = arr.length;        System.out.println( minMoves(arr, n));     }} // This code is contributed by vt_m
# Python 3 program to find minimum# number of move-to-front moves# to arrange items in sorted order. # Calculate minimum number of moves# to arrange array in increasing order.def minMoves(arr, n):         # Since we traverse array from end,    # expected item is initially n    expectedItem = n     # Traverse array from end    for i in range(n - 1, -1, -1):                 # If current item is at its        # correct position, decrement        # the expectedItem (which also        # means decrement in minimum        # number of moves)        if (arr[i] == expectedItem):            expectedItem -= 1    return expectedItem     # Driver Codearr = [4, 3, 2, 1]n = len(arr)print(minMoves(arr, n)) # This code is contributed 29AjayKumar
// C# program to find minimum// number of move-to-front moves// to arrange items in sorted order.using System; class GFG {     // Calculate minimum number of moves    // to arrange array in increasing order.    static int minMoves(int []arr, int n)    {        // Since we traverse array from end,        // expected item is initially n        int expectedItem = n;             // Traverse array from end        for (int i = n - 1; i >= 0; i--)        {            // If current item is at its            // correct position, decrement            // the expectedItem (which also            // means decrement in minimum            // number of moves)            if (arr[i] == expectedItem)                expectedItem--;        }             return expectedItem;    }         // Driver Program    public static void Main ()    {        int []arr = {4, 3, 2, 1};        int n = arr.Length;        Console.Write( minMoves(arr, n));     }} // This code is contributed by nitin mittal.
<?php// PHP program to find minimum// number of move-to-front moves// to arrange items in sorted order. // Calculate minimum number of// moves to arrange array// in increasing order.function minMoves($arr, $n){    // Since we traverse array    // from end, expected item    // is initially n    $expectedItem = $n;     // Traverse array from end    for ($i = $n - 1; $i >= 0; $i--)    {        // If current item is at its        // correct position, decrement        // the expectedItem (which also        // means decrement in minimum        // number of moves)        if ($arr[$i] == $expectedItem)            $expectedItem--;    }     return $expectedItem;} // Driver Code$arr = array(4, 3, 2, 1);$n = count($arr);echo minMoves($arr, $n); // This code is contributed by anuj_67.?>
<script>     // JavaScript program to find minimum    // number of move-to-front moves    // to arrange items in sorted order.         // Calculate minimum number of moves    // to arrange array in increasing order.    function minMoves(arr, n)    {        // Since we traverse array from end,        // expected item is initially n        let expectedItem = n;               // Traverse array from end        for (let i = n - 1; i >= 0; i--)        {            // If current item is at its            // correct position, decrement            // the expectedItem (which also            // means decrement in minimum            // number of moves)            if (arr[i] == expectedItem)                expectedItem--;        }               return expectedItem;    }         let arr = [4, 3, 2, 1];    let n = arr.length;    document.write( minMoves(arr, n));     </script>
3
Time Complexity : O(n)
This article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
nitin mittal
vt_m
29AjayKumar
decode2207
surindertarika1234
arorakashish0911
hardikkoriintern
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures