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 = 3
Output: 2
Explanation:
Selecting a subsequence { 7 } and replacing all its elements by 0 modifies arr[] to { 3, 3, 3 }.
Selecting the array { 3, 3, 3 } and replacing all its elements by 0 modifies arr[] to { 0, 0, 0 }
Input: arr[] = {1, 5, 1, 3, 2, 3, 1}, N = 7
Output: 4
Approach: The problem can be solved using Greedy technique. The idea is to count the distinct elements present in the array which is not equal to 0 and print the count obtained. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void minOpsToTurnArrToZero( int arr[], int N)
{
unordered_set< int > st;
for ( int i = 0; i < N; i++) {
if (st.find(arr[i]) != st.end()
|| arr[i] == 0) {
continue ;
}
else {
st.insert(arr[i]);
}
}
cout << st.size() << endl;
}
int main()
{
int arr[] = { 3, 7, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
minOpsToTurnArrToZero(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void minOpsToTurnArrToZero( int [] arr, int N)
{
Set<Integer> st = new HashSet<Integer>();
for ( int i = 0 ; i < N; i++) {
if (st.contains(arr[i]) || arr[i] == 0 ) {
continue ;
}
else {
st.add(arr[i]);
}
}
System.out.println(st.size());
}
public static void main(String args[])
{
int arr[] = { 3 , 7 , 3 };
int N = arr.length;
minOpsToTurnArrToZero(arr, N);
}
}
|
Python3
def minOpsToTurnArrToZero(arr, N):
st = dict ()
for i in range (N):
if (i in st.keys() or arr[i] = = 0 ):
continue
else :
st[arr[i]] = 1
print ( len (st))
arr = [ 3 , 7 , 3 ]
N = len (arr)
minOpsToTurnArrToZero(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void minOpsToTurnArrToZero( int [] arr, int N)
{
HashSet< int > st = new HashSet< int >();
for ( int i = 0; i < N; i++)
{
if (st.Contains(arr[i]) || arr[i] == 0)
{
continue ;
}
else
{
st.Add(arr[i]);
}
}
Console.WriteLine(st.Count);
}
public static void Main(String []args)
{
int []arr = { 3, 7, 3 };
int N = arr.Length;
minOpsToTurnArrToZero(arr, N);
}
}
|
Javascript
<script>
function minOpsToTurnArrToZero(arr, N)
{
var st = new Set();
for ( var i = 0; i < N; i++)
{
if (st.has(arr[i]) || arr[i] == 0)
{
continue ;
}
else
{
st.add(arr[i]);
}
}
document.write(st.size)
}
var arr = [ 3, 7, 3 ];
var N = arr.length;
minOpsToTurnArrToZero(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
09 Jun, 2021
Like Article
Save Article