Minimize operations to make all the elements of given Subarrays distinct
Last Updated :
19 Dec, 2022
Given an arr[] of positive integers and start[] and end[] arrays of length L, Which contains the start and end indexes of L number of non-intersecting sub-arrays as a start[i] and end[i] for all (1 ? i ? L). An operation is defined as below:
- Select an ordered continuous or non - continuous part of the sub-array and then add an integer let's say A to all of the elements of the chosen part.
Then, the task is to output the minimum number of given operations required to make all the elements of all given non - intersecting sub-arrays distinct.
Note: If more than one sub-arrays contains the same element, It doesn't matter. Just each sub-array should contain distinct elements in itself.
Examples:
Input: arr[] = {2, 2, 1, 2, 3}, start[] = {1, 3}, end[] = {2, 5}
Output: 1
Explanation: First sub-array : [start[1], end[1]] = {2, 2}.
Second sub-array : [start[3], end[5]] = {1, 2, 3}.
In First sub-array choose sub-sequence from index 1 to 1 as {2} and plus any integer random integer let say 1.Then, First sub-array = {3, 2}. Now, both sub-array contains distinct elements in itself. Total number of required operation are 1.
Input: arr[] = {1, 2, 3, 3, 4, 5}, start[] = {1, 4}, end[] = {3, 6}
Output: 0
Explanation: It can be verified that sub-arrays {1, 2, 3} and {3, 4, 5} both are distinct in itself. Therefore, total number of required operations are 0.
Approach: Implement the idea below to solve the problem
Making all the elements distinct in a sub-array by given operation only depends upon the maximum frequency in an sub-array, If we converted high frequent element in distinct form then rest of the frequencies less than max frequency can be make distinct simultaneously. For more clarity see the concept of approach.Obtain the maximum frequency in each sub-array and apply the algorithm provided below.
Concept of approach:
Suppose our sub-array A[] is = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2}. Highest frequency is 10 here.
First operation: Choose ordered sub-sequence from index 6 to 10 and add any integer let say 1 to all elements in sub-sequence. Then, A[] = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3}. Highest frequency is 5 till here.
Second Operation: Choose ordered sub-sequence from index 3 to 5 and 8 to 10 add any integer let say 2 to all elements in sub-sequence. Then, A[] = {2, 2, 4, 4, 4, 3, 3, 5, 5, 5}. Highest frequency is 3 till here.
Third Operation: Choose ordered sub-sequence from index 4 to 5 and 9 to 10 add any integer let say 3 to all elements in sub-sequence. Then, A[] = {2, 2, 4, 7, 7, 3, 3, 5, 8, 8}
Fourth Operation: Choose ordered sub-sequence of indices : {1, 4, 6, 9} add any integer let say 10 to all elements in sub-sequence. Then, A[] = {12, 2, 4, 17, 7, 13, 3, 5, 18, 8}
Thus, Only four operation are required to convert into distinct elements. At second operation we can see the both 2 and 3 element has 5 frequency and we successfully convert them into distinct elements. This gives us idea that If we try to make max frequent element distinct, Then rest of the elements having frequency less than or equal to max frequency can be converted into distinct simultaneously.
In above example, It can be clearly seen that, At each operation we are converting the exactly half of the elements, If value of max_frequency is even at that current operation otherwise we are converting (max_frequency+1)/2 elements as well as we are reducing the value of max_frequency in the same manner.Thus we can conclude the below provided algorithm to solve the problem.
Algorithm to solve the problem:
1. Create a variable let's say min_operations to store total number of minimum operations required for all sub-arrays.
2. For Each given sub-array follow the steps below:
- Count frequency of each element and store them in Hash-Map.
- Traverse the Hash-Map to obtain maximum frequency in a variable let's say max_frequency.
- Create and initialize counter variable to zero.
- Apply the below algorithm for obtaining minimum number of operations required.
while(max_frequency > 1)
{
if (isEven(max_frequency))
{
max_frequency/=2;
}
else
{
max_frequency = (max_frequency+1)/2;
}
counter++;
}
- On completing the loop add value of counter variable in min_operations.
3. After apply above algorithm on each given sub-array print the value of min_operations.
Below is the code to implement the approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Driver Function
int main()
{
// Input arr[]
int arr[10] = { 2, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
int arrlength = 10;
// start[] array holding start
// indices of sub-arrays
int start[2] = { 1, 6 };
int startlength = 2;
// end[] array holding end
// indices of sub-arrays
int end[2] = { 5, 10 };
int endlength = 2;
// Variable to hold total Minimum
// numbers of operations required
int min_operations = 0;
// Loop for traversing on given
// indices of sub-arrays sub-arrays
for (int i = 0; i < startlength; i++) {
// Start index of sub-array
int start_index = start[i];
// End index of sub-array
int end_index = end[i];
// HashMap for counting
// frequencies
unordered_map<int, int> map;
// Loop for traversing
// on sub-array
for (int j = start_index - 1; j < end_index; j++) {
// Obtaining and putting
// frequencies in map
map[arr[j]] == 0
? map[arr[j]] = 1
: map[arr[j]] = map[arr[j]] + 1;
}
// Variable to store
// max_frequency from map
int max_frequency = 0;
// Loop for traversing on map
// for (Map.Entry<Integer, Integer> set :
// map.entrySet())
for (auto set : map) {
// Updating variable
// max_frequency
max_frequency = set.second > max_frequency
? set.second
: max_frequency;
}
// Applying discussed algorithm
// in concept of approach
while (max_frequency > 1) {
// Updating max_frequency variable
max_frequency = max_frequency % 2 == 0
? max_frequency / 2
: (max_frequency + 1) / 2;
// Incrementing
// min_operations
min_operations++;
}
}
// Printing minimum numbers
// of required operations
cout << min_operations;
return 0;
}
// This code is contributed by akashish__
Java
// Java code to implement the approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Driver Function
public static void main(String args[])
{
// Input arr[]
int[] arr = { 2, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
// start[] array holding start
// indices of sub-arrays
int[] start = { 1, 6 };
// end[] array holding end
// indices of sub-arrays
int[] end = { 5, 10 };
// Variable to hold total Minimum
// numbers of operations required
int min_operations = 0;
// Loop for traversing on given
// indices of sub-arrays sub-arrays
for (int i = 0; i < start.length; i++) {
// Start index of sub-array
int start_index = start[i];
// End index of sub-array
int end_index = end[i];
// HashMap for counting
// frequencies
HashMap<Integer, Integer> map = new HashMap<>();
// Loop for traversing
// on sub-array
for (int j = start_index - 1; j < end_index;
j++) {
// Obtaining and putting
// frequencies in map
map.put(arr[j], map.get(arr[j]) == null
? 1
: map.get(arr[j]) + 1);
}
// Variable to store
// max_frequency from map
int max_frequency = 0;
// Loop for traversing on map
for (Map.Entry<Integer, Integer> set :
map.entrySet()) {
// Updating variable
// max_frequency
max_frequency
= set.getValue() > max_frequency
? set.getValue()
: max_frequency;
}
// Applying discussed algorithm
// in concept of approach
while (max_frequency > 1) {
// Updating max_frequency variable
max_frequency
= max_frequency % 2 == 0
? max_frequency / 2
: (max_frequency + 1) / 2;
// Incrementing
// min_operations
min_operations++;
}
}
// Printing minimum numbers
// of required operations
System.out.println(min_operations);
}
}
Python3
# Python code to implement the approach
# Driver Function
#Input arr[]
arr = [2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
arrlength = 10
# start[] array holding start
# indices of sub-arrays
start = [1, 6]
startlength = 2
# end[] array holding end
# indices of sub-arrays
end = [5, 10]
endlength = 2
# Variable to hold total Minimum
# numbers of operations required
min_operations = 0
# Loop for traversing on given
# indices of sub-arrays sub-arrays
for i in range(startlength):
# Start index of sub-array
start_index = start[i]
# End index of sub-array
end_index = end[i]
# HashMap for counting
# frequencies
map = dict()
# Loop for traversing
# on sub-array
for j in range(start_index-1,end_index):
# Obtaining and putting
# frequencies in map
if arr[j] in map.keys():
map[arr[j]] = map[arr[j]] + 1
else:
map[arr[j]] = 1
# Variable to store
# max_frequency from map
max_frequency = 0
# Loop for traversing on map
for key,value in map.items():
# Updating variable
# max_frequency
max_frequency = value if value>max_frequency else max_frequency
# Applying discussed algorithm
# in concept of approach
while(max_frequency > 1):
# Updating max_frequency variable
max_frequency=max_frequency//2 if max_frequency%2==0 else (max_frequency+1)//2
# Incrementing
# min_operations
min_operations=min_operations+1
# Printing minimum numbers
# of required operations
print(min_operations)
# This code is contributed by Aman Kumar.
C#
// Include namespace system
using System;
using System.Collections.Generic;
using System.Collections;
public class GFG
{
// Driver Function
public static void Main(String[] args)
{
// Input arr[]
int[] arr = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3};
// start[] array holding start
// indices of sub-arrays
int[] start = {1, 6};
// end[] array holding end
// indices of sub-arrays
int[] end = {5, 10};
// Variable to hold total Minimum
// numbers of operations required
var min_operations = 0;
// Loop for traversing on given
// indices of sub-arrays sub-arrays
for (int i = 0; i < start.Length; i++)
{
// Start index of sub-array
var start_index = start[i];
// End index of sub-array
var end_index = end[i];
// HashMap for counting
// frequencies
var map = new Dictionary<int, int>();
// Loop for traversing
// on sub-array
for (int j = start_index - 1; j < end_index; j++)
{
// Obtaining and putting
// frequencies in map
map[arr[j]] = !map.ContainsKey(arr[j]) ? 1 : map[arr[j]] + 1;
}
// Variable to store
// max_frequency from map
var max_frequency = 0;
// Loop for traversing on map
foreach (KeyValuePair<int, int> entry in map)
{
// Updating variable
// max_frequency
max_frequency = entry.Value > max_frequency ? entry.Value : max_frequency;
}
// Applying discussed algorithm
// in concept of approach
while (max_frequency > 1)
{
// Updating max_frequency variable
max_frequency = max_frequency % 2 == 0 ? (int)(max_frequency / 2) : (int)((max_frequency + 1) / 2);
// Incrementing
// min_operations
min_operations++;
}
}
// Printing minimum numbers
// of required operations
Console.WriteLine(min_operations);
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// Driver Function
// Input arr[]
let arr = [2, 2, 2, 2, 2, 3, 3, 3, 3, 3];
let arrlength = 10;
// start[] array holding start
// indices of sub-arrays
let start = [1, 6];
let startlength = 2;
// end[] array holding end
// indices of sub-arrays
let end = [5, 10];
let endlength = 2;
// Variable to hold total Minimum
// numbers of operations required
let min_operations = 0;
// Loop for traversing on given
// indices of sub-arrays sub-arrays
for (let i = 0; i < startlength; i++) {
// Start index of sub-array
let start_index = start[i];
// End index of sub-array
let end_index = end[i];
// HashMap for counting
// frequencies
let map = {};
for (let j = start_index - 1; j < end_index; j++) {
// Obtaining and putting
// frequencies in map
map[arr[j]] = 0;
}
// Loop for traversing
// on sub-array
for (let j = start_index - 1; j < end_index; j++) {
// Obtaining and putting
// frequencies in map
map[arr[j]] == 0
? map[arr[j]] = 1
: map[arr[j]] = map[arr[j]] + 1;
}
// Variable to store
// max_frequency from map
let max_frequency = 0;
// Loop for traversing on map
for (const [key, value] of Object.entries(map)) {
max_frequency = value > max_frequency
? value
: max_frequency;
}
// Applying discussed algorithm
// in concept of approach
while (max_frequency > 1) {
// Updating max_frequency variable
max_frequency = max_frequency % 2 == 0
? Math.floor(max_frequency / 2)
: Math.floor((max_frequency + 1) / 2);
// Incrementing
// min_operations
min_operations++;
}
}
// Printing minimum numbers
// of required operations
console.log(min_operations);
// This code is contributed by akashish__
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Linked List Data Structure A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read