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 element left from the array after performing given operations
Next article icon

Minimize operations of removing 2i -1 array elements to empty given array

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

Given an array arr[] of size N, the task is to empty given array by removing 2i - 1 array elements in each operation (i is any positive integer). Find the minimum number of operations required.

Examples:

Input: arr[] = { 2, 3, 4 } 
Output: 1 
Explanation: 
Removing (22 - 1) elements i.e { arr[0], arr[1], arr[2] } modifies arr[] to { } 
Since no elements left in the array therefore, the required output is 1.

Input: arr[] = { 1, 2, 3, 4 } 
Output: 2 
Explanation: 
Removing (21 - 1) element i.e, { arr[0] } modifies arr[] to { 2, 3, 4 } 
Removing (22 - 1) elements i.e, { arr[0], arr[1], arr[2] } modifies arr[] to { } 
Since no elements left in the array therefore, the required output is 2.

Approach: The problem can be solved using Greedy technique. The idea is to always remove the maximum possible count(2i - 1) of elements from the array. Follow the steps below to solve the problem:

  • Initialize a variable, say cntSteps, to store the minimum count of operations required to empty given array.
  • Removing N array elements modifies arr[] to 0 length array. Therefore, increment the value of N by 1.
  • Traverse each bit of N using variable i and for every ith bit, check if the bit is set or not. If found to be true, then update cntSteps += 1
  • Finally, print the value of cntSteps.

Below is the implementation of the above approach:

C++
// C++ program to implement // the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find minimum count of steps // required to remove all the array elements int minimumStepReqArr(int arr[], int N) {      // Stores minimum count of steps required     // to remove all the array elements     int cntStep = 0;      // Update N     N += 1;      // Traverse each bit of N     for (int i = 31; i >= 0; i--) {          // If current bit is set         if (N & (1 << i)) {              // Update cntStep             cntStep += 1;         }     }      return cntStep; }  // Driver Code int main() {     int arr[] = { 1, 2, 3 };      int N = sizeof(arr) / sizeof(arr[0]);     cout << minimumStepReqArr(arr, N);      return 0; } 
Java
// Java program to implement  // the above approach  import java.util.*; class GFG {    // Function to find minimum count of steps    // required to remove all the array elements    static int minimumStepReqArr(int[] arr, int N)    {       // Stores minimum count of steps required      // to remove all the array elements      int cntStep = 0;       // Update N      N += 1;       // Traverse each bit of N      for (int i = 31; i >= 0; i--)      {         // If current bit is set        if ((N & (1 << i)) != 0)        {           // Update cntStep          cntStep += 1;        }      }            return cntStep;    }    // Driver code   public static void main(String[] args)   {     int[] arr = { 1, 2, 3 };       int N = arr.length;     System.out.println(minimumStepReqArr(arr, N));   } }  // This code is contributed by susmitakundugoaldanga 
Python3
# Python3 program to implement # the above approach  # Function to find minimum count of steps # required to remove all the array elements def minimumStepReqArr(arr, N):          # Stores minimum count of steps required     # to remove all the array elements     cntStep = 0      # Update N     N += 1      i = 31      while(i >= 0):                  # If current bit is set         if (N & (1 << i)):              # Update cntStep             cntStep += 1                      i -= 1      return cntStep  # Driver Code if __name__ == '__main__':          arr = [ 1, 2, 3 ]     N = len(arr)          print(minimumStepReqArr(arr, N))  # This code is contributed by SURENDRA_GANGWAR 
C#
// C# program to implement  // the above approach  using System; class GFG  {    // Function to find minimum count of steps    // required to remove all the array elements    static int minimumStepReqArr(int[] arr, int N)    {       // Stores minimum count of steps required      // to remove all the array elements      int cntStep = 0;       // Update N      N += 1;       // Traverse each bit of N      for (int i = 31; i >= 0; i--)      {         // If current bit is set        if ((N & (1 << i)) != 0)        {           // Update cntStep          cntStep += 1;        }      }            return cntStep;    }     // Driver code   static void Main()    {     int[] arr = { 1, 2, 3 };       int N = arr.Length;     Console.WriteLine(minimumStepReqArr(arr, N));   } }  // This code is contributed by divyesh072019 
JavaScript
<script>     // Javascript program to implement the above approach          // Function to find minimum count of steps     // required to remove all the array elements     function minimumStepReqArr(arr, N)     {        // Stores minimum count of steps required       // to remove all the array elements       let cntStep = 0;        // Update N       N += 1;        // Traverse each bit of N       for (let i = 31; i >= 0; i--)       {          // If current bit is set         if ((N & (1 << i)) != 0)         {            // Update cntStep           cntStep += 1;         }       }             return cntStep;     }          let arr = [ 1, 2, 3 ];       let N = arr.length;     document.write(minimumStepReqArr(arr, N));  // This code is contributed by suresh07. </script> 

Output: 
1

 

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


Next Article
Minimum element left from the array after performing given operations

D

divyeshrabadiya07
Improve
Article Tags :
  • Bit Magic
  • Greedy
  • DSA
  • Arrays
  • setBitCount
  • array-rearrange
  • Greedy Algorithms
Practice Tags :
  • Arrays
  • Bit Magic
  • Greedy

Similar Reads

  • Minimize the non-zero elements in the Array by given operation
    Given an array arr[] of length N, the task is to minimize the count of the number of non-zero elements by adding the value of the current element to any of its adjacent element and subtracting from the current element at most once.Examples: Input: arr[] = { 1, 0, 1, 0, 0, 1 } Output: 2 Explanation:
    5 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Minimum element left from the array after performing given operations
    Given an array arr[] of N integers, the task is to remove the elements from both the ends of the array i.e. in a single operation, either the first or the last element can be removed from the current remaining elements of the array. This operation needs to be performed in such a way that the last el
    3 min read
  • Maximize sum of array elements removed by performing the given operations
    Given two arrays arr[] and min[] consisting of N integers and an integer K. For each index i, arr[i] can be reduced to at most min[i]. Consider a variable, say S(initially 0). The task is to find the maximum value of S that can be obtained by performing the following operations: Choose an index i an
    8 min read
  • Minimize Cost to reduce the Array to a single element by given operations
    Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K
    15+ min read
  • Minimize remaining array sizes by removing equal pairs of first array elements
    Given two binary arrays L1[] and L2[], each of size N, the task is to minimize the count of remaining array elements after performing the following operations: If the first element of both the arrays is same, then remove it from both the arrays.Otherwise, remove the first element from L1[] and appen
    8 min read
  • Minimize steps to make Array elements equal by using giving operations
    Given an arr[] of length N. Then the task is to find minimum steps to make all the elements of the given array equal. Two types of operations can be performed as given below: Choose a prefix of size K, where arr[K] = max element in that chosen sub-array and convert all elements equal to max. Choose
    8 min read
  • Minimum operations to make all Array elements 0 by MEX replacement
    Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
    5 min read
  • Minimize operations to convert Array elements to 0s
    Given an array nums[] of length N containing non-negative integers, the task is to convert all elements from index 0 to N-2 to zero, after doing the below operations minimum number of times. In one operation select two indices i and j such that i < j and all the elements between i and j has to be
    6 min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
    9 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