Minimum number of steps required to place all 1s at a single index
Given a binary array A[] of size N, where all 1s can be moved to its adjacent position, the task is to print an array res[] of size N, where res[i] contains the minimum number of steps required to move all the 1s at the ith index.
Examples:
Input: A[] = {1, 0, 1, 0}
Output: {2, 2, 2, 4}
Explanation:
For i = 0, moving all 1s to 0th index requires 2 steps, i.e abs(0 – 0) + abs(0 – 2) = 2.
For i = 1, moving all 1s to 1st index requires 2 steps, i.e abs(1 – 0) + abs(1 – 2) = 2.
For i = 2, moving all 1s to 2nd index requires 2 steps, i.e abs(2 – 0) + abs(2 – 2) = 2.
For i = 3, moving all 1’s to 3rd index requires 4 steps, i.e abs(3 – 0) + abs(3 – 2) = 4.
Hence, res[] is {2, 2, 2, 4}Input: A[] = {0, 0, 1, 0, 0, 1}
Output: {7, 5, 3, 3, 3, 3}
Explanation:
For i = 0, moving all 1s to 0th index requires 7 steps, i.e abs(2 – 0) + abs(5 – 0) = 7.
For i = 1, moving all 1s to 1st index requires 5 steps, i.e abs(2 – 1) + abs(5 – 1) = 5.
For i = 2, moving all 1s to 2nd index requires 3 steps, i.e abs(2 – 2) + abs(5 – 2) = 3.
For i = 3, moving all 1s to 3rd index will take 3 steps, i.e abs(2 – 2) + abs(5 – 3) = 3.
For i = 4, moving all 1s to 4th index will take 3 steps, i.e abs(2 – 4) + abs(5 – 4) = 3.
For i = 5, moving all 1s to 5th index will take 3 steps, i.e abs(2 – 5) + abs(5 – 5) = 3.
Hence, res[] is {7, 5, 3, 3, 3, 3}
Naive Approach: Follow the steps to solve the problem :
- Traverse the array.
- For every ith index, count the number of steps required to move all 1s to the ith index.
- Iterate over the range [0, N – 1], using a variable, say i.
- Initialize steps = 0.
- Iterate over the range [0, N – 1], using a variable j.
- If A[j] is equal to 1, add abs(i – j) to steps.
- Print the minimum number of steps.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Prefix Sum. Follow the steps below to solve this problem:
- Traverse the array.
- Initialize an array, say left[], and initialize count = A[0].
- Iterate over the range [1, N – 1], and update left[i] = left[i – 1] + count, where count is the number of 1s on the left side of i.
- Initialize an array, say right[], and initialize count = A[N – 1].
- Iterate over the range [N – 2, 0], and update right[i] = right[i + 1] + count, where count is the number of 1s on the right side of i.
- Calculate and update the final answer in res[], where res[i] is the sum of the steps from left and right sides, i.e res[i] = right[i] + left[i]
- Print the array res[].
Below is the implementation of the above approach:
C++
// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std;// Function to print minimum steps// required to shift all 1s to a// single index in a binary arrayvoid minsteps(vector<int>& A){ // Size of array int n = A.size(); // Used to store cumulative sum vector<int> left(n, 0), right(n, 0), res(n, 0); // Initialize count int count = A[0]; // Traverse the array in // forward direction for (int i = 1; i < n; i++) { // Steps needed to store all // previous ones to ith index left[i] = left[i - 1] + count; // Count number of 1s // present till i-th index count += A[i]; } // Initialize count count = A[n - 1]; // Traverse the array in // backward direction for (int i = n - 2; i >= 0; i--) { // Steps needed to store all 1s to // the right of i at current index right[i] = right[i + 1] + count; // Count number of 1s // present after i-th index count += A[i]; } // Print the number of steps required for (int i = 0; i < n; i++) { res[i] = left[i] + right[i]; cout << res[i] << " "; } cout << "\n";}// Driver Codeint main(){ vector<int> A = { 1, 0, 1, 0 }; minsteps(A);} |
Java
// Java program for the above approachimport java.util.*;import java.lang.*;class GFG{ // Function to print minimum steps // required to shift all 1s to a // single index in a binary array static void minsteps(int[] A) { // Size of array int n = A.length; // Used to store cumulative sum int[] left = new int [n]; Arrays.fill(left, 0); int[] right = new int [n]; Arrays.fill(right, 0); int[] res = new int [n]; Arrays.fill(res, 0); // Initialize count int count = A[0]; // Traverse the array in // forward direction for (int i = 1; i < n; i++) { // Steps needed to store all // previous ones to ith index left[i] = left[i - 1] + count; // Count number of 1s // present till i-th index count += A[i]; } // Initialize count count = A[n - 1]; // Traverse the array in // backward direction for (int i = n - 2; i >= 0; i--) { // Steps needed to store all 1s to // the right of i at current index right[i] = right[i + 1] + count; // Count number of 1s // present after i-th index count += A[i]; } // Print the number of steps required for (int i = 0; i < n; i++) { res[i] = left[i] + right[i]; System.out.print(res[i] + " "); } System.out.println(); } // Driver code public static void main(String[] args) { int[] A = { 1, 0, 1, 0 }; minsteps(A); }}// This code is contributed by souravghosh0416. |
Python3
# Python3 implementation of# the above approach# Function to print minimum steps# required to shift all 1s to a# single index in a binary arraydef minsteps(A): # Size of array n = len(A) # Used to store cumulative sum left, right, res =[0]*n, [0]*n, [0]*n # Initialize count count = A[0] # Traverse the array in # forward direction for i in range(1, n): # Steps needed to store all # previous ones to ith index left[i] = left[i - 1] + count # Count number of 1s # present till i-th index count += A[i] # Initialize count count = A[n - 1] # Traverse the array in # backward direction for i in range(n - 2, -1, -1): # Steps needed to store all 1s to # the right of i at current index right[i] = right[i + 1] + count # Count number of 1s # present after i-th index count += A[i] # Print the number of steps required for i in range(n): res[i] = left[i] + right[i] print(res[i], end = " ") print()# Driver Codeif __name__ == '__main__': A = [1, 0, 1, 0] minsteps(A)# This code is contributed by mohit kumar 29. |
C#
// C# Program to implement// the above approachusing System;class GFG{ // Function to print minimum steps // required to shift all 1s to a // single index in a binary array static void minsteps(int[] A) { // Size of array int n = A.Length; // Used to store cumulative sum int[] left = new int [n]; for (int i = 1; i < n; i++) { left[i] = 0; } int[] right = new int [n]; for (int i = 1; i < n; i++) { right[i] = 0; } int[] res = new int [n]; for (int i = 1; i < n; i++) { res[i] = 0; } // Initialize count int count = A[0]; // Traverse the array in // forward direction for (int i = 1; i < n; i++) { // Steps needed to store all // previous ones to ith index left[i] = left[i - 1] + count; // Count number of 1s // present till i-th index count += A[i]; } // Initialize count count = A[n - 1]; // Traverse the array in // backward direction for (int i = n - 2; i >= 0; i--) { // Steps needed to store all 1s to // the right of i at current index right[i] = right[i + 1] + count; // Count number of 1s // present after i-th index count += A[i]; } // Print the number of steps required for (int i = 0; i < n; i++) { res[i] = left[i] + right[i]; Console.Write(res[i] + " "); } Console.WriteLine(); } // Driver Code public static void Main(String[] args) { int[] A = { 1, 0, 1, 0 }; minsteps(A); }}// This code is contributed by susmitakundugoaldanga. |
Javascript
<script>// JavaScript program to implement// the above approach // Function to prlet minimum steps // required to shift all 1s to a // single index in a binary array function minsteps(A) { // Size of array let n = A.length; // Used to store cumulative sum let left = Array.from({length: n}, (_, i) => 0); let right = Array.from({length: n}, (_, i) => 0); let res = Array.from({length: n}, (_, i) => 0); // Initialize count let count = A[0]; // Traverse the array in // forward direction for (let i = 1; i < n; i++) { // Steps needed to store all // previous ones to ith index left[i] = left[i - 1] + count; // Count number of 1s // present till i-th index count += A[i]; } // Initialize count count = A[n - 1]; // Traverse the array in // backward direction for (let i = n - 2; i >= 0; i--) { // Steps needed to store all 1s to // the right of i at current index right[i] = right[i + 1] + count; // Count number of 1s // present after i-th index count += A[i]; } // Print the number of steps required for (let i = 0; i < n; i++) { res[i] = left[i] + right[i]; document.write(res[i] + " "); } document.write("<br/>"); }// Driver code let A = [ 1, 0, 1, 0 ]; minsteps(A);// This code is contributed by sanjoy_62.</script> |
2 2 2 4
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



