C++ Program to find minimum moves to get all books contiguous

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements. Consider there is a bookshelf and this =can fit n books. The i-th position of bookshelf is A[i], is 1 if there is a book on this position and 0 otherwise. There will be at least one book in the bookshelf. In one move, we can take some contiguous segment [l to r] and −

  • Shift them to the right by 1. This move can be done only if there are empty slots at the right side of r.

  • Shift them to the left by 1: This move can be done only if there are empty slots at the left of l.

We have to find the find the minimum number of moves required to collect all the books on the shelf as a contiguous segment.

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.



So, if the input of our problem is like A = [0, 0, 1, 0, 1, 0, 1], then the output will be 2, because we can shift the segment [3 to 3] to the right and the segment [4 to 5] to the right. Now after all moves, the books form the contiguous segment [5 to 7]. So the answer is 2.


To solve this, we will follow these steps −

n := size of A
ans := 0
Define an empty array v
for initialize i := 0, when i < n, update (increase i by 1), do:
   a := A[i]
   if a is same as 1, then:
      insert i at the end of v
for initialize i := 1, when i < size of v, update (increase i by 1), do:
   ans := ans + (v[i] - v[i - 1] - 1)
return ans


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int n = A.size();
   int ans = 0;
   int a;
   vector<int> v;
   for (int i = 0; i < n; i++){
      a = A[i];
      if (a == 1)
   for (int i = 1; i < v.size(); i++)
      ans += (v[i] - v[i - 1] - 1);
   return ans;
int main(){
   vector<int> A = { 0, 0, 1, 0, 1, 0, 1 };
   cout << solve(A) << endl;


{ 0, 0, 1, 0, 1, 0, 1 }


Updated on 08-Apr-2022 08:05:48