Minimize Array partitions such that an element is repeated atmost once in each partition
Given an array arr[] consisting of positive integers. The task is to minimize the contiguous groups formed if each element from arr[] can be a part of atmost one group, and a number can be repeated only once.
Examples:
Input: arr[] = {1, 2, 1, 1, 1, 1, 1, 2, 3}
Outptut: { {1, 2, 1}, {1, 1}, {1, 1, 2, 3} }
Explanation: Following are the groups formed with given conditions.
In 1 2 1, 1 repeats 1 times.
In 1 1, 1 repeats 1 times.
In 1 1 2 3, 1 repeats 1 times.
Therefore, in total there are three groups formed, which is minimum possible.Input: arr[] = {1, 1}
Output: { {1, 1} }
Approach: This problem can be solved by using HashMaps. Follow the steps below to solve the given problem.
- Take a variable say, count = 0 for storing the number of groups formed and a 2D vector for storing groups.
- Traverse the array arr[] and start storing the frequency of array elements in a map and storing the current element in the vector.
- Whenever the frequency of any element becomes 2, take a flag variable to track one number with frequency 2 has encountered before and just move forward. Use that flag variable to break any group and increment the count variable and push the vector in 2D vector and clear the whole temporary vector and map.
- Now print the 2D vector as the required answer.
Below is the implementation of the above approach:
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum groups// formed with given conditionsvoid findMinimumGroups(int a[], int n){ map<int, int> m; // 2D vector to stor groups vector<vector<int> > v; int c = 0; vector<int> v1; bool to = 0; for (int i = 0; i < n; i++) { v1.push_back(a[i]); // Store frequency m[a[i]]++; // Counting number of groups if (m[a[i]] >= 2) { if (to or m[a[i]] == 3) { c++; // If elelemnt found again // push in 2d vector m.clear(); v1.pop_back(); v.push_back(v1); v1.clear(); to = 0; i--; } else to = 1; } else if (i == n - 1) { c++; v.push_back(v1); } } for (int i = 0; i < v.size(); i++) { for (int j = 0; j < v[i].size(); j++) { cout << v[i][j] << " "; } cout << endl; }} // Driver Codeint main(){ int arr[] = { 1, 2, 1, 1, 1, 1, 1, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findMinimumGroups(arr, N);} |
3 1 2 1 1 1 1 1 1 2 3
Time Complexity: O(N)
Auxiliary Space: O(N)


