Open In App

Minimum number of moves to make all elements equal

Last Updated : 19 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array containing N elements and an integer K. It is allowed to perform the following operation any number of times on the given array: 
 

  • Insert the K-th element at the end of the array and delete the first element of the array.

The task is to find the minimum number of moves needed to make all elements of the array equal. Print -1 if it is not possible.
Examples: 
 

Input : arr[] = {1, 2, 3, 4}, K = 4
Output : 3
Step 1: 2 3 4 4
Step 2: 3 4 4 4
Step 3: 4 4 4 4

Input : arr[] = {2, 1}, K = 1
Output : -1
The array will keep alternating between 1, 2 and 
2, 1 regardless of how many moves you apply.

Let’s look at the operations with respect to the original array, first, we copy a[k] to the end, then a[k+1], and so on. To make sure that we only copy equal elements, all elements in the range K to N should be equal. 
So, to find the minimum number of moves, we need to remove all elements in range 1 to K that are not equal to a[k]. Hence, we need to keep applying operations until we reach the rightmost term in range 1 to K that is not equal to a[k].
Below is the implementation of the above approach: 
 

C++




// C++ Program to find minimum number of operations to make
// all array Elements equal
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number of operationsto make all
// array Elements equal
int countMinimumMoves(int arr[], int n, int k)
{
    int i;
    // Check if it is possible or not i.e., if all the
    // elements from index K to N are not equal
    for (i = k - 1; i < n; i++)
        if (arr[i] != arr[k - 1])
            return -1;
    // Find minimum number of moves
    for (i = k - 1; i >= 0; i--)
        if (arr[i] != arr[k - 1])
            return i + 1;
    // Elements are already equal
    return 0;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int K = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countMinimumMoves(arr, n, K);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


C




// C Program to find minimum number of operations to make
// all array Elements equal
 
#include <stdio.h>
 
// Function to find minimum number of operations to make all
// array Elements equal
int countMinimumMoves(int arr[], int n, int k)
{
    int i;
    // Check if it is possible or not i.e., if all the
    // elements from index K to N are not equal
    for (i = k - 1; i < n; i++)
        if (arr[i] != arr[k - 1])
            return -1;
    // Find minimum number of moves
    for (i = k - 1; i >= 0; i--)
        if (arr[i] != arr[k - 1])
            return i + 1;
    // Elements are already equal
    return 0;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int K = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d", countMinimumMoves(arr, n, K));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




// Java Program to find minimum number of operations to make
// all array Elements equal
 
import java.io.*;
 
class GFG {
    // Function to find minimum number of operations to make
    // all array Elements equal
    static int countMinimumMoves(int arr[], int n, int k)
    {
        int i;
        // Check if it is possible or not i.e., if all the
        // elements from index K to N are not equal
        for (i = k - 1; i < n; i++)
            if (arr[i] != arr[k - 1])
                return -1;
        // Find minimum number of moves
        for (i = k - 1; i >= 0; i--)
            if (arr[i] != arr[k - 1])
                return i + 1;
        // Elements are already equal
        return 0;
    }
 
    // Driver Code
 
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4 };
        int K = 4;
        int n = arr.length;
        System.out.print(countMinimumMoves(arr, n, K));
    }
}
 
// This code is contributed by Sania Kumari Gupta


Python3




# Python3 Program to find minimum
# number of operations to make all
# array Elements equal
 
# Function to find minimum number
# of operations to make all array
# Elements equal
def countMinimumMoves(arr, n, k) :
 
    # Check if it is possible or not
    # That is if all the elements from
    # index K to N are not equal
    for i in range(k - 1, n) :
        if (arr[i] != arr[k - 1]) :
            return -1
 
    # Find minimum number of moves
    for i in range(k - 1, -1, -1) :
        if (arr[i] != arr[k - 1]) :
            return i + 1
 
    # Elements are already equal
    return 0
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 4 ]
    K = 4
 
    n = len(arr)
 
    print(countMinimumMoves(arr, n, K))
 
# This code is contributed by Ryuga


C#




// C# Program to find minimum number of
// operations to make all array Elements
// equal
using System;
 
class GFG
{
     
// Function to find minimum number
// of operations to make all array
// Elements equal
static int countMinimumMoves(int []arr,
                             int n, int k)
{
    int i;
 
    // Check if it is possible or not
    // That is if all the elements from
    // index K to N are not equal
    for (i = k - 1; i < n; i++)
        if (arr[i] != arr[k - 1])
            return -1;
 
    // Find minimum number of moves
    for (i = k - 1; i >= 0; i--)
        if (arr[i] != arr[k - 1])
            return i + 1;
 
    // Elements are already equal
    return 0;
}
 
// Driver Code
public static void Main ()
{
    int []arr = { 1, 2, 3, 4 };
    int K = 4;
     
    int n = arr.Length;
     
    Console.Write(countMinimumMoves(arr, n, K));
}
}
 
// This code is contributed
// by 29AjayKumar


PHP




<?php
// PHP Program to find minimum number of
// operations to make all array Elements
// equal
 
// Function to find minimum number
// of operations to make all array
// Elements equal
function countMinimumMoves($arr, $n, $k)
{
 
    // Check if it is possible or not
    // That is if all the elements from
    // index K to N are not equal
    for ($i = $k - 1; $i < $n; $i++)
        if ($arr[$i] != $arr[$k - 1])
            return -1;
 
    // Find minimum number of moves
    for ($i = $k - 1; $i >= 0; $i--)
        if ($arr[$i] != $arr[$k - 1])
            return $i + 1;
 
    // Elements are already equal
    return 0;
}
 
// Driver Code
$arr = array(1, 2, 3, 4);
$K = 4;
 
$n = sizeof($arr);
 
echo countMinimumMoves($arr, $n, $K);
 
// This code is contributed
// by Akanksha Rai
?>


Javascript




<script>
 
// JavaScript Program to find minimum number of
// operations to make all array Elements
// equal
 
 
// Function to find minimum number of operations
// to make all array Elements equal
function countMinimumMoves(arr, n, k)
{
    let i;
 
    // Check if it is possible or not
    // That is if all the elements from
    // index K to N are not equal
    for (i = k - 1; i < n; i++)
        if (arr[i] != arr[k - 1])
            return -1;
 
    // Find minimum number of moves
    for (i = k - 1; i >= 0; i--)
        if (arr[i] != arr[k - 1])
            return i + 1;
 
    // Elements are already equal
    return 0;
}
 
// Driver Code
    let arr = [ 1, 2, 3, 4 ];
    let K = 4;
 
    let n = arr.length;
 
    document.write(countMinimumMoves(arr, n, K));
 
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>


Output: 

3

 

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



Similar Reads

Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number
Given two numbers N and M, the task is to find the minimum number of moves to change N to M or -1 if it's impossible. In one move, add to the current number any of its divisors not equal to 1 and the number itself. Examples: Input: N = 4, M = 24Output: 5Explanation: the number 24 can be reached starting from 4 using 5 operations: 4-&gt;6-&gt;8-&gt;
16 min read
Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements
Given an array arr[] of size N, the task is to make all array elements equal to 0 by replacing all elements of a subsequences of equal elements by any integer, minimum number of times. Examples: Input: arr[] = {3, 7, 3}, N = 3Output: 2Explanation:Selecting a subsequence { 7 } and replacing all its elements by 0 modifies arr[] to { 3, 3, 3 }. Select
5 min read
Find the minimum number of preprocess moves required to make two strings equal
Given two strings A and B of equal lengths consisting of lower case English letters. The task is to count the minimum number of pre-processing moves on string A required to make it equal to string B after applying below operations: Choose any index i (0 ? i &lt; n) and swap characters ai and bi.Choose any index i (0 ? i &lt; n) and swap characters
9 min read
Minimum moves to make count of lowercase and uppercase letters equal
Given a string, S of even length N, the task is to find the minimum number of moves needed to convert the string to a string consisting of half upper case and half lower case characters. Examples: Input: S = "AbcdEf"Output: 1 ABcdEfExplanation: One possible way to modify the string is by converting the second character to S[1]( ='b') to an uppercas
9 min read
Minimum moves to make M and N equal by repeated addition of divisors except 1 using Dynamic Programming
Given two integers N and M, the task is to calculate the minimum number of moves to change N to M, where In one move it is allowed to add any divisor of the current value of N to N itself except 1. Print "-1" if it is not possible. Example: Input: N = 4, M = 24Output: 5Explanation: The given value of N can be converted into M using the following st
8 min read
Make all array elements equal by reducing array elements to half minimum number of times
Given an array arr[] consisting of N integers, the task is to minimize the number of operations required to make all array elements equal by converting Ai to Ai / 2. in each operation Examples: Input: arr[] = {3, 1, 1, 3}Output: 2Explanation: Reducing A0 to A0 / 2 modifies arr[] to {1, 1, 1, 3}. Reducing A3 to A3 / 2 modifies arr[] to {1, 1, 1, 1}.
6 min read
Minimum number of bits of array elements required to be flipped to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to find the minimum number of bits of array elements required to be flipped to make all array elements equal. Examples: Input: arr[] = {3, 5}Output: 2Explanation:Following are the flipping of bits of the array elements required: For element arr[0](= 3): Flipping the 3rd bit from th
7 min read
Minimize moves to make Array elements equal by incrementing and decrementing pairs
Given an array arr[] of size N, the task is to print the minimum number of moves needed to make all array elements equal by selecting any two distinct indices and then increment the element at the first selected index and decrement the element at the other selected index by 1 in each move. If it is impossible to make all the array elements equal th
14 min read
Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2
Given an array arr[] of size N, the task is to print the minimum number of moves required to make all array elements equal by selecting any pair of distinct indices and then increment the element at the first index and decrement the element at the other index by 1 each time. If it is impossible to make all array elements equal, then print “-1“. Exa
7 min read
Minimum moves to make String Palindrome incrementing all characters of Substrings
Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following operations:Select the substring "4341". The string
6 min read