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:
Minimum number of swaps required to sort an array of first N number
Next article icon

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

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
Recommended Practice
Minimum move to front operations
Try It!

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++




// 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 Program
int main()
{
    int arr[] = {4, 3, 2, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << minMoves(arr, n);
    return 0;
}
 
 

Java




// 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
 
 

Python3




# 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 Code
arr = [4, 3, 2, 1]
n = len(arr)
print(minMoves(arr, n))
  
# This code is contributed 29AjayKumar
 
 

C#




// 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
// 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.
?>
 
 

Javascript




<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>
 
 
Output
3

Time Complexity : O(n)

Auxiliary Space: O(1)

 



Next Article
Minimum number of swaps required to sort an array of first N number

A

Anuj Chauhan(anuj0503)
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • 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
  • Minimum steps to convert an Array into permutation of numbers from 1 to N
    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 decremen
    4 min read
  • Minimum number of swaps required to sort an array of first N number
    Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array. Example: Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 } Output: 5 Explanation: i arr swap (indices) 0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3) 1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1) 2 [1,
    5 min read
  • Minimum range increment operations to Sort an array
    Given an array containing N elements. It is allowed to do the below move any number of times on the array: Choose any L and R and increment all numbers in range L to R by 1. The task is to find the minimum number of such moves required to sort the array in non decreasing order. Examples: Input : arr
    5 min read
  • Count of Missing Numbers in a sorted array
    Given a sorted array arr[], the task is to calculate the number of missing numbers between the first and last element of the sorted array. Examples: Input: arr[] = { 1, 4, 5, 8 } Output: 4 Explanation: The missing integers in the array are {2, 3, 6, 7}. Therefore, the count is 4. Input: arr[] = {5,
    9 min read
  • Count number of 1s in the array after N moves
    Given an array of size N in which initially all the elements are 0(zero). The task is to count the number of 1's in the array after performing N moves on the array as explained:In each move (starting from 1 to N) the element at the position of the multiple of the move number is changed from 0 to 1 o
    9 min read
  • Minimum number of moves required to sort Array by swapping with X
    Given an integer array, arr[] of size N and an integer X. The task is to sort the array in increasing order in a minimum number of moves by swapping any array element greater than X with X any number of times. If it is not possible print -1. Examples: Input: arr[] = {1, 3, 4, 6, 5}, X = 2Output: 3Ex
    7 min read
  • Sort an array containing two types of elements
    This problem appears in multiple forms as mentioned below. If we take a closer look at the below problems, we can notice that the problem is mainly a variation of partition algorithm in QuickSort. Table of Content Sort a Binary ArrayMove all zeros to end of array Separate Even and Odd NumbersSeparat
    3 min read
  • Minimize moves to next greater element to reach end of Array
    Given an array nums[] of size N and a starting index K. In one move from index i we can move to any other index j such that there exists no element in between the indices that is greater than nums[i] and nums[j] > nums[i]. Find the minimum number of moves to reach the last index. Print -1 if it i
    14 min read
  • Count number of ways to arrange first N numbers
    Count number of ways to arrange the first N natural numbers in a line such that the left-most number is always 1 and no two consecutive numbers have an absolute difference greater than 2. Examples: Input: N = 4 Output: 4 The only possible arrangements are (1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 4, 2) and
    13 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