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:
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Next article icon

Convert an array into another by repeatedly removing the last element and placing it at any arbitrary index

Last Updated : 16 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays A[] and B[], both consisting of a permutation of first N natural numbers, the task is to count the minimum number of times the last array element is required to be shifted to any arbitrary position in the array A[] to make both the arrays A[] and B[] equal.

Examples:

Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 5, 2, 3, 4}
Output:1
Explanation:
Initially, the array A[] is {1, 2, 3, 4, 5}. After moving the last array element, i.e. 5, and placing them between arr[0] (= 1) and arr[1](= 2) modifies the array to {1, 5, 2, 3, 4}, which is the same as the array B[].
Therefore, the minimum number of operations required to convert the array A[] to B[] is 1.

Input: A[] = {3, 2, 1}, B[] = {1, 2, 3}
Output: 2
Explanation:
Initially, the array A[] is {3, 2, 1}.
Operation 1: After moving the last array element, i.e. 1, to the beginning of the array, modifies the array to {1, 3, 2}.
Operation 2: After moving the last element of the array, i.e. 2 and placing them between the elements arr[0] (= 1) and arr[1] (= 3) modifies the array to {1, 2, 3}, which is the same as the array B[].
Therefore, the minimum number of operations required to convert the array A[] to B[] is 2.

Approach: The given problem can be solved by finding the first i consecutive elements of the first permutation which is the same as the subsequence of the second permutation, then the count of operations must be less at least (N – I), since the last (N – i) elements can be selected optimally and inserted at required indices. Therefore, (N – i) is the minimum number of steps required for the conversion of the array A[] to B[].

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to count the minimum number
// of operations required to convert
// the array A[] into array B[]
int minCount(int A[], int B[], int N)
{
    // Stores the index in the first
    // permutation A[] which is same
    // as the subsequence in B[]
    int i = 0;
 
    // Find the first i elements in A[]
    // which is a subsequence in B[]
    for (int j = 0; j < N; j++) {
 
        // If element A[i]
        // is same as B[j]
        if (A[i] == B[j]) {
            i++;
        }
    }
 
    // Return the count of
    // operations required
    return N - i;
}
 
// Driver Code
int main()
{
    int A[] = { 1, 2, 3, 4, 5 };
    int B[] = { 1, 5, 2, 3, 4 };
 
    int N = sizeof(A) / sizeof(A[0]);
 
    cout << minCount(A, B, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
class GFG{
     
// Function to count the minimum number
// of operations required to convert
// the array A[] into array B[]
static int minCount(int A[], int B[], int N)
{
     
    // Stores the index in the first
    // permutation A[] which is same
    // as the subsequence in B[]
    int i = 0;
 
    // Find the first i elements in A[]
    // which is a subsequence in B[]
    for(int j = 0; j < N; j++)
    {
         
        // If element A[i]
        // is same as B[j]
        if (A[i] == B[j])
        {
            i++;
        }
    }
 
    // Return the count of
    // operations required
    return N - i;
}
 
// Driver Code
public static void main (String[] args)
{
    int A[] = { 1, 2, 3, 4, 5 };
    int B[] = { 1, 5, 2, 3, 4 };
    int N = A.length;
 
    System.out.println(minCount(A, B, N));
}
}
 
// This code is contributed by AnkThon
 
 

Python3




# Python3 program for the above approach
 
# Function to count the minimum number
# of operations required to convert
# the array A[] into array B[]
def minCount(A, B, N):
     
    # Stores the index in the first
    # permutation A[] which is same
    # as the subsequence in B[]
    i = 0
 
    # Find the first i elements in A[]
    # which is a subsequence in B[]
    for j in range(N):
         
        # If element A[i]
        # is same as B[j]
        if (A[i] == B[j]):
            i += 1
 
    # Return the count of
    # operations required
    return N - i
 
# Driver Code
if __name__ == '__main__':
     
    A = [ 1, 2, 3, 4, 5 ]
    B = [ 1, 5, 2, 3, 4 ]
 
    N = len(A)
 
    print(minCount(A, B, N))
     
# This code is contributed by ipg2016107
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to count the minimum number
// of operations required to convert
// the array A[] into array B[]
static int minCount(int[] A, int[] B, int N)
{
     
    // Stores the index in the first
    // permutation A[] which is same
    // as the subsequence in B[]
    int i = 0;
 
    // Find the first i elements in A[]
    // which is a subsequence in B[]
    for(int j = 0; j < N; j++)
    {
         
        // If element A[i]
        // is same as B[j]
        if (A[i] == B[j])
        {
            i++;
        }
    }
 
    // Return the count of
    // operations required
    return N - i;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] A = { 1, 2, 3, 4, 5 };
    int[] B = { 1, 5, 2, 3, 4 };
    int N = A.Length;
 
    Console.WriteLine(minCount(A, B, N));
}
}
 
// This code is contributed by ukasp
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to count the minimum number
// of operations required to convert
// the array A[] into array B[]
function minCount(A, B, N){
     
    // Stores the index in the first
    // permutation A[] which is same
    // as the subsequence in B[]
    var i = 0
 
    // Find the first i elements in A[]
    // which is a subsequence in B[]
    for(let j = 0; j < N; j++){
         
        // If element A[i]
        // is same as B[j]
        if (A[i] == B[j])
            i += 1
      }
    // Return the count of
    // operations required
    return N - i
     
}
 
// Driver Code
     
var A = [ 1, 2, 3, 4, 5 ]
var B = [ 1, 5, 2, 3, 4 ]
 
N = A.length
 
document.write(minCount(A, B, N))
     
// This code is contributed by AnkThon
 
</script>
 
 
Output: 
1

 

Time Complexity: O(N)
Auxiliary Space: O(1)

 



Next Article
Modify array to another given array by replacing array elements with the sum of the array | Set-2

A

aditya7409
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Searching
  • array-rearrange
  • permutation
  • subsequence
Practice Tags :
  • Arrays
  • Greedy
  • permutation
  • Searching

Similar Reads

  • Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times
    Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Outp
    7 min read
  • Reduce array to a single element by repeatedly removing an element from any increasing pair
    Given an array arr[] consisting of permutation in the range [1, N], the task is to check if the given array can be reduced to a single non-zero element by performing the following operations: Select indices i and j such that i < j and arr[i] < arr[j] and convert one of the two elements to 0. I
    9 min read
  • Modify array to another given array by replacing array elements with the sum of the array | Set-2
    Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES
    10 min read
  • Array obtained by repeatedly reversing array after every insertion from given array
    Given an array arr[], the task is to print the array obtained by inserting elements of arr[] one by one into an initially empty array, say arr1[], and reversing the array arr1[] after every insertion. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4 2 1 3Explanation:Operations performed on the array a
    6 min read
  • Last element remaining after repeated removal of Array elements at perfect square indices
    Given an array arr[](1-based indexing) consisting of N integers, the task is to find the last element remaining element after repeated removal of array element at perfect square indices. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 5Explanation:Following the removal of array element at perfect sq
    7 min read
  • Find Array formed by adding each element of given array with largest element in new array to its left
    Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the elem
    6 min read
  • Find K such that array A can be converted into array B by adding K to a selected range [L, R]
    Given two arrays a[] and b[] of length N consisting of unique elements, the task is to find a number K (K > 0) such that the first array can be converted into the second array by adding K to a selected range [L, R] in the array. If no such number K exists, print NExamples: Input: a[] = {3, 7, 1,
    10 min read
  • Print the Array formed by reversing the given Array after each index
    Given an array arr[], the task is to print the array formed by traversing given array from first to the last index by flipping the whole array after printing every element. Example: Input: arr = {0, 1, 2, 3, 4, 5} Output: 0 4 2 2 4 0Explanation: On 1st iteration element on index 0 -> 0 is printed
    6 min read
  • Find last remaining element of Array after sorting and subtracting adjacents repeatedly
    Given an array arr[] of length N containing non negative integers, the task is to find the last remaining element after performing the following operations (N - 1) times: Sort the array in ascending order.Replace each element arr[i] with arr[i + 1] - arr[i], for i in [0, N - 2].Remove the last eleme
    13 min read
  • Generate an N-length array A[] from an array arr[] such that arr[i] is the last index consisting of a multiple of A[i]
    Given an array arr[] of length N, with values less than N, the task is to construct another array A[] of same length such that for every ith element in the array A[], arr[i] is the last index (1-based indexing) consisting of a multiple of A[i]. Examples: Input: arr[] = {4, 1, 2, 3, 4}Output: 2 3 5 7
    10 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