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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find the number of operations required to make all array elements Equal
Next article icon

Minimum number of operations required to delete all elements of the array

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr, the task is to print the minimum number of operations required to delete all elements of the array. 
In an operation, any element from the array can be chosen at random and every element divisible by it can be removed from the array.

Examples: 

Input: arr[] = {2, 4, 6, 3, 5, 10} 
Output: 3 
Choosing 2 as the first element will remove 2, 4, 6 and 10 from the array. 
Now choose 3 which will result in the removal of 3. 
Finally, the only element left to choose is 5.

Input: arr[] = {2, 5, 3, 7, 11} 
Output: 5 

Approach: For optimal results, the smallest element from the array should be chosen from the remaining elements one after another until all the elements of the array are deleted.  

  1. Sort the array in ascending order and find the multiple of element in complete vector.
  2. For each element which are divisible by choose element mark it 0, and decrease the value of N.
  3. Return the value of N.

Below is the implementation of the above approach.

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
int solve(int N, vector<int> A)
{
    sort(A.begin(), A.end());
    int a = 0;
    for (int i = 0; i < A.size() - 1; i++) {
        int c = 0;
        if (A[i] != 0) {
            for (int j = i + 1; j < A.size(); j++) {
                if (A[j] % A[i] == 0 && A[j] != 0
                    && A[i] != 0) {
                    A[j] = 0;
                    N--;
                }
            }
        }
    }
    if (N == 0) {
        N = 1;
    }
    return N;
}
// Driver program
int main()
{
    vector<int> v = { 4, 6, 2, 8, 7, 21, 24, 49, 44 };
    int n = v.size();
 
    cout << solve(n, v);
    return 0;
}
// This code is contributed by Raunak_Kumar
 
 

Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Java implementation of the above approach
 
  static int solve(int N, int[] A)
  {
    Arrays.sort(A);
    int a = 0;
    for (int i = 0; i < A.length - 1; i++) {
      int c = 0;
      if (A[i] != 0) {
        for (int j = i + 1; j < A.length; j++) {
          if (A[j] % A[i] == 0 && A[j] != 0
              && A[i] != 0) {
            A[j] = 0;
            N--;
          }
        }
      }
    }
    if (N == 0) {
      N = 1;
    }
    return N;
  }
 
  // Driver Code
  public static void main(String args[])
  {
    int[] v = { 4, 6, 2, 8, 7, 21, 24, 49, 44 };
    int n = v.length;
 
    System.out.println(solve(n, v));
  }
}
 
// This code is contributed by shinjanpatra
 
 

Python3




# Python implementation of the above approach
def solve(N,A):
    A.sort()
    a = 0
    for i in range(len(A) - 1):
        c = 0
        if (A[i] != 0):
            for j in range(i + 1,len(A)):
                if (A[j] % A[i] == 0 and A[j] != 0 and A[i] != 0):
                    A[j] = 0
                    N -= 1
    if (N == 0):
        N = 1
    return N
 
# Driver program
v = [ 4, 6, 2, 8, 7, 21, 24, 49, 44 ]
n = len(v)
 
print(solve(n, v))
 
# This code is contributed by shinjanpatra
 
 

C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  static int solve(int N, int[] A)
  {
    Array.Sort(A);
//    int a = 0;
    for (int i = 0; i < A.Length - 1; i++) {
//      int c = 0;
      if (A[i] != 0) {
        for (int j = i + 1; j < A.Length; j++) {
          if (A[j] % A[i] == 0 && A[j] != 0
              && A[i] != 0) {
            A[j] = 0;
            N--;
          }
        }
      }
    }
    if (N == 0) {
      N = 1;
    }
    return N;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int[] v = { 4, 6, 2, 8, 7, 21, 24, 49, 44 };
    int n = v.Length;
 
    Console.WriteLine(solve(n, v));
  }
}
 
// This code is contributed by phasing17
 
 

Javascript




<script>
 
// JavaScript implementation of the above approach
let n = -1;
 
function solve(A)
{
    A.sort((a,b)=> a - b);
    let a = 0;
    for (let i = 0; i < A.length - 1; i++) {
        let c = 0;
        if (A[i] != 0) {
            for (let j = i + 1; j < A.length; j++) {
                if (A[j] % A[i] == 0 && A[j] != 0 && A[i] != 0) {
                    A[j] = 0;
                    n--;
                }
            }
        }
    }
    if (n == 0) {
        n = 1;
    }
    return n;
}
 
// Driver program
let v = [ 4, 6, 2, 8, 7, 21, 24, 49, 44 ];
n = v.length;
 
document.write(solve(v));
 
// This code is contributed by shinjanpatra
 
</script>
 
 
Output
2

Time Complexity: O(N2 logN), where N is the size of the array
Space Complexity: O(1)

Approach: For optimal results, the smallest element from the array should be chosen from the remaining elements one after another until all the elements of the array are deleted. 

  • Sort the array in ascending order and prepare a hash for occurrences.
  • For each unmarked element starting from beginning mark all elements which are divisible by choose element, and increase the result counter.

Below is the implementation of the above approach

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
#define MAX 10000
 
using namespace std;
 
int hashTable[MAX];
 
// function to find minimum operations
int minOperations(int arr[], int n)
{
    // sort array
    sort(arr, arr + n);
 
    // prepare hash of array
    for (int i = 0; i < n; i++)
        hashTable[arr[i]]++;
 
    int res = 0;
    for (int i = 0; i < n; i++) {
        if (hashTable[arr[i]]) {
            for (int j = i; j < n; j++)
                if (arr[j] % arr[i] == 0)
                    hashTable[arr[j]] = 0;
            res++;
        }
    }
 
    return res;
}
 
// Driver program
int main()
{
    int arr[] = { 4, 6, 2, 8, 7, 21, 24, 49, 44 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << minOperations(arr, n);
    return 0;
}
 
 

Java




//Java implementation of the above approach
import java.util.*;
class Solution
{
static final int MAX=10000;
 
static int hashTable[]= new int[MAX];
 
// function to find minimum operations
static int minOperations(int arr[], int n)
{
    // sort array
    Arrays.sort(arr);
 
    // prepare hash of array
    for (int i = 0; i < n; i++)
        hashTable[arr[i]]++;
 
    int res = 0;
    for (int i = 0; i < n; i++) {
        if (hashTable[arr[i]]!=0) {
            for (int j = i; j < n; j++)
                if (arr[j] % arr[i] == 0)
                    hashTable[arr[j]] = 0;
            res++;
        }
    }
 
    return res;
}
 
// Driver program
public static void main(String args[])
{
    int arr[] = { 4, 6, 2, 8, 7, 21, 24, 49, 44 };
    int n = arr.length;
 
    System.out.print( minOperations(arr, n));
  
}
}
// This code is contributed by Arnab Kundu
 
 

Python 3




# Python 3 implementation of
# the above approach
MAX = 10000
 
hashTable = [0] * MAX
 
# function to find minimum operations
def minOperations(arr, n):
     
    # sort array
    arr.sort()
 
    # prepare hash of array
    for i in range(n):
        hashTable[arr[i]] += 1
 
    res = 0
    for i in range(n) :
        if (hashTable[arr[i]]) :
            for j in range(i, n):
                if (arr[j] % arr[i] == 0):
                    hashTable[arr[j]] = 0
            res += 1
 
    return res
 
# Driver Code
if __name__ == "__main__":
    arr = [ 4, 6, 2, 8, 7, 21, 24, 49, 44 ]
    n = len(arr)
 
    print(minOperations(arr, n))
 
# This code is contributed
# by ChitraNayal
 
 

C#




using System;
 
// C# implementation of the above approach 
public class Solution
{
public const int MAX = 10000;
 
public static int[] hashTable = new int[MAX];
 
// function to find minimum operations 
public static int minOperations(int[] arr, int n)
{
    // sort array 
    Array.Sort(arr);
 
    // prepare hash of array 
    for (int i = 0; i < n; i++)
    {
        hashTable[arr[i]]++;
    }
 
    int res = 0;
    for (int i = 0; i < n; i++)
    {
        if (hashTable[arr[i]] != 0)
        {
            for (int j = i; j < n; j++)
            {
                if (arr[j] % arr[i] == 0)
                {
                    hashTable[arr[j]] = 0;
                }
            }
            res++;
        }
    }
 
    return res;
}
 
// Driver program 
public static void Main(string[] args)
{
    int[] arr = new int[] {4, 6, 2, 8, 7, 21, 24, 49, 44};
    int n = arr.Length;
 
    Console.Write(minOperations(arr, n));
 
}
}
 
// This code is contributed by Shrikant13
 
 

PHP




<?php
// PHP implementation of the
// above approach
 
// function to find minimum operations
function minOperations(&$arr, $n)
{
    $hashTable = array();
     
    // sort array
    sort($arr);
 
    // prepare hash of array
    for ($i = 0; $i < $n; $i++)
        $hashTable[$arr[$i]]++;
 
    $res = 0;
    for ($i = 0; $i < $n; $i++)
    {
        if ($hashTable[$arr[$i]])
        {
            for ($j = $i; $j < $n; $j++)
                if ($arr[$j] % $arr[$i] == 0)
                    $hashTable[$arr[$j]] = 0;
            $res++;
        }
    }
 
    return $res;
}
 
// Driver Code
$arr = array(4, 6, 2, 8, 7, 21,
                    24, 49, 44);
$n = sizeof($arr);
 
echo minOperations($arr, $n);
 
// This code is contributed
// by Shivi_Aggarwal
?>
 
 

Javascript




<script>
 
// javascript implementation of the above approach
 
var MAX = 10000;
 
var hashTable = Array(MAX).fill(0);
 
// function to find minimum operations
function minOperations(arr, n)
{
    // sort array
    arr.sort((a,b)=>a-b);
 
    // prepare hash of array
    for (var i = 0; i < n; i++)
        hashTable[arr[i]]++;
 
    var res = 0;
    for (var i = 0; i < n; i++) {
        if (hashTable[arr[i]]) {
            for (var j = i; j < n; j++)
                if (arr[j] % arr[i] == 0)
                    hashTable[arr[j]] = 0;
            res++;
        }
    }
 
    return res;
}
 
// Driver program
var arr = [ 4, 6, 2, 8, 7, 21, 24, 49, 44 ];
var n = arr.length;
document.write( minOperations(arr, n));
 
</script>
 
 
Output
2

Time Complexity: O(N logN), where N is the size of the array
Space Complexity: O(MAX)



Next Article
Find the number of operations required to make all array elements Equal

S

Shivam.Pradhan
Improve
Article Tags :
  • DSA
  • Greedy
  • Hash
  • divisibility
Practice Tags :
  • Greedy
  • Hash

Similar Reads

  • Find the minimum number of operations required to make all array elements equal
    Given an array arr[] of size N. The task is to make all the array elements equal by applying the below operations minimum number of times: Choose a pair of indices (i, j) such that |i - j| = 1 (indices i and j are adjacent) and set arr[i] = arr[i] + |arr[i] - arr[j]|Choose a pair of indices (i, j) s
    6 min read
  • Find the number of operations required to make all array elements Equal
    Given an array of N integers, the task is to find the number of operations required to make all elements in the array equal. In one operation we can distribute equal weights from the maximum element to the rest of the array elements. If it is not possible to make the array elements equal after perfo
    6 min read
  • Minimum no. of operations required to make all Array Elements Zero
    Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.
    12 min read
  • Minimum number of given operations required to reduce the array to 0 element
    Given an array arr[] of N integers. The task is to find the minimum number of given operations required to reduce the array to 0 elements. In a single operation, any element can be chosen from the array and all of its multiples get removed including itself.Examples: Input: arr[] = {2, 4, 6, 3, 4, 6,
    6 min read
  • Minimum operations required to make all the array elements equal
    Given an array arr[] of n integer and an integer k. The task is to count the minimum number of times the given operation is required to make all the array elements equal. In a single operation, the kth element of the array is appended at the end of the array and the first element of the array gets d
    6 min read
  • Minimum number of operations required to make all elements equal
    Given an array arr[] of length N along with an integer M. All the elements of arr[] are in the range [1, N]. Then your task is to output the minimum number of operations required to make all elements equal given that in one operation you can select at most M elements and increment all of them by 1.
    5 min read
  • Minimum number of operations required to make all the elements positive
    Given an array A[] of length N. You can apply the below operation: Choose an index i such that (i+1) element exists. After that choose any number X (positive or negative). Then subtract X from the ith element and add it into (i+1)th element.The task is to find the minimum number of operations requir
    9 min read
  • Minimum delete operations to make all elements of array same
    Given an array of n elements such that elements may repeat. We can delete any number of elements from the array. The task is to find a minimum number of elements to be deleted from the array to make it equal.Examples: Input: arr[] = {4, 3, 4, 4, 2, 4} Output: 2 After deleting 2 and 3 from array, arr
    10 min read
  • Minimum operations required to make all elements in an array of first N odd numbers equal
    Given an array consisting of first N odd numbers, the task is to find the minimum number of operations required to make all the array elements equal by repeatedly selecting a pair and incrementing one element and decrementing the other element in the pair by 1. Examples: Input: N = 3Output: 2Explana
    10 min read
  • Minimum number of increment-other operations to make all array elements equal.
    We are given an array consisting of n elements. At each operation we can select any one element and increase rest of n-1 elements by 1. We have to make all elements equal performing such operation as many times you wish. Find the minimum number of operations needed for this. Examples: Input: arr[] =
    5 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