Skip to content
Related Articles

Related Articles

Minimize Array partitions such that an element is repeated atmost once in each partition

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 25 Mar, 2022
Improve Article
Save Article

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}
Output: { {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 conditions
void findMinimumGroups(int a[], int n)
{
    map<int, int> m;
 
    // 2D vector to store 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 element 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 Code
int main()
{
    int arr[] = { 1, 2, 1, 1, 1, 1, 1, 2, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findMinimumGroups(arr, N);
}


Python3




# Python code for the above approach
 
# Function to find minimum groups
# formed with given conditions
def findMinimumGroups(a, n):
    m = dict()
 
    # 2D vector to store groups
    v = []
    c = 0
 
    v1 = []
 
    to = 0
 
    i = 0
    while(i < n):
 
        v1.append(a[i])
 
        # Store frequency
        if (a[i] in m):
            m[a[i]] = m[a[i]]+1
 
        else:
            m[a[i]] = 1
 
        # Counting number of groups
        if (m[a[i]] >= 2):
 
            if(to or m[a[i]] == 3):
                c += 1
 
                # If element found again
                # append in 2d vector
                m.clear()
                v1.pop()
                v.append(v1)
                v1 = []
                to = 0
                i -= 1
            else:
                to = 1
 
        elif (i == n - 1):
            c += 1
            v.append(v1)
        i += 1
 
    for i in range(len(v)):
 
        for j in range(len(v[i])):
             
            print(v[i][j], end = " ")
 
        print()
 
# Driver Code
arr = [1, 2, 1, 1, 1, 1, 1, 2, 3]
N = len(arr)
 
# Function Call
findMinimumGroups(arr, N)
 
# This code is contributed by shinjanpatra


Javascript




<script>
      // JavaScript code for the above approach
 
      // Function to find minimum groups
      // formed with given conditions
      function findMinimumGroups(a, n) {
          let m = new Map();
 
          // 2D vector to store groups
          let v = [];
          let c = 0;
 
          let v1 = [];
 
          let to = 0;
 
          for (let i = 0; i < n; i++) {
              v1.push(a[i]);
 
              // Store frequency
              if (m.has(a[i])) {
                  m.set(a[i], m.get(a[i]) + 1)
              }
              else {
                  m.set(a[i], 1)
              }
 
              // Counting number of groups
              if (m.get(a[i]) >= 2) {
 
                  if (to || m.get(a[i]) == 3) {
                      c++;
 
                      // If element found again
                      // push in 2d vector
                      m.clear();
                      v1.pop();
                      v.push(v1);
                      v1 = [];
                      to = 0;
                      i--;
                  }
                  else
                      to = 1;
              }
 
              else if (i == n - 1) {
                  c++;
                  v.push(v1);
              }
          }
 
          for (let i = 0; i < v.length; i++) {
 
              for (let j = 0; j < v[i].length; j++) {
                  document.write(v[i][j] + " ");
              }
              document.write('<br>')
          }
      }
 
      // Driver Code
      let arr = [1, 2, 1, 1, 1, 1, 1, 2, 3];
      let N = arr.length;
 
      // Function Call
      findMinimumGroups(arr, N);
 
// This code is contributed by Potta Lokesh
  </script>


Output

1 2 1 
1 1 
1 1 2 3 

Time Complexity: O(N) 
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!