Skip to content
Related Articles

Related Articles

Improve Article

Group multiple occurrence of array elements ordered by first occurrence

  • Difficulty Level : Easy
  • Last Updated : 15 Jun, 2021

Given an unsorted array with repetitions, the task is to group multiple occurrence of individual elements. The grouping should happen in a way that the order of first occurrences of all elements is maintained.
Examples: 
 

Input: arr[] = {5, 3, 5, 1, 3, 3}
Output:        {5, 5, 3, 3, 3, 1}

Input: arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}
Output:        {4, 4, 4, 6, 6, 9, 9, 2, 3, 10}

 

Simple Solution is to use nested loops. The outer loop traverses array elements one by one. The inner loop checks if this is first occurrence, if yes, then the inner loop prints it and all other occurrences. 
 

C++




// A simple C++ program to group multiple occurrences of individual
// array elements
#include<bits/stdc++.h>
using namespace std;
 
// A simple method to group all occurrences of individual elements
void groupElements(int arr[], int n)
{
    // Initialize all elements as not visited
    bool *visited = new bool[n];
    for (int i=0; i<n; i++)
        visited[i] = false;
 
    // Traverse all elements
    for (int i=0; i<n; i++)
    {
        // Check if this is first occurrence
        if (!visited[i])
        {
            // If yes, print it and all subsequent occurrences
            cout << arr[i] << " ";
            for (int j=i+1; j<n; j++)
            {
                if (arr[i] == arr[j])
                {
                    cout << arr[i] << " ";
                    visited[j] = true;
                }
            }
        }
    }
 
    delete [] visited; 
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4};
    int n = sizeof(arr)/sizeof(arr[0]);
    groupElements(arr, n);
    return 0;
}

Java




// A simple Java program to group
// multiple occurrences of individual
// array elements
 
class GFG
{
 
    // A simple method to group all occurrences
    // of individual elements
    static void groupElements(int arr[], int n)
    {
         
        // Initialize all elements as not visited
        boolean visited[] = new boolean[n];
        for (int i = 0; i < n; i++)
        {
            visited[i] = false;
        }
 
        // Traverse all elements
        for (int i = 0; i < n; i++)
        {
             
            // Check if this is first occurrence
            if (!visited[i])
            {
                 
                // If yes, print it and all
                // subsequent occurrences
                System.out.print(arr[i] + " ");
                for (int j = i + 1; j < n; j++)
                {
                    if (arr[i] == arr[j])
                    {
                        System.out.print(arr[i] + " ");
                        visited[j] = true;
                    }
                }
            }
        }
    }
 
    /* Driver code */
    public static void main(String[] args)
    {
        int arr[] = {4, 6, 9, 2, 3, 4,
                        9, 6, 10, 4};
        int n = arr.length;
        groupElements(arr, n);
    }
}
 
// This code is contributed by Rajput-JI

Python3




# A simple Python 3 program to
# group multiple occurrences of
# individual array elements
 
# A simple method to group all
# occurrences of individual elements
def groupElements(arr, n):
 
    # Initialize all elements
    # as not visited
    visited = [False] * n
    for i in range(0, n):
        visited[i] = False
 
    # Traverse all elements
    for i in range(0, n):
     
        # Check if this is
        # first occurrence
        if (visited[i] == False):
         
            # If yes, print it and
            # all subsequent occurrences
            print(arr[i], end = " ")
            for j in range(i + 1, n):
             
                if (arr[i] == arr[j]):
                 
                    print(arr[i], end = " ")
                    visited[j] = True
             
# Driver Code
arr = [4, 6, 9, 2, 3,
       4, 9, 6, 10, 4]
n = len(arr)
groupElements(arr, n)
 
# This code is contributed
# by Smitha

C#




// A simple C# program to group
// multiple occurrences of individual
// array elements
using System;
 
class GFG
{
 
    // A simple method to group all occurrences
    // of individual elements
    static void groupElements(int []arr, int n)
    {
         
        // Initialize all elements as not visited
        bool []visited = new bool[n];
        for (int i = 0; i < n; i++)
        {
            visited[i] = false;
        }
 
        // Traverse all elements
        for (int i = 0; i < n; i++)
        {
             
            // Check if this is first occurrence
            if (!visited[i])
            {
                 
                // If yes, print it and all
                // subsequent occurrences
                Console.Write(arr[i] + " ");
                for (int j = i + 1; j < n; j++)
                {
                    if (arr[i] == arr[j])
                    {
                        Console.Write(arr[i] + " ");
                        visited[j] = true;
                    }
                }
            }
        }
    }
 
    /* Driver code */
    public static void Main(String[] args)
    {
        int []arr = {4, 6, 9, 2, 3, 4,
                        9, 6, 10, 4};
        int n = arr.Length;
        groupElements(arr, n);
    }
}
 
// This code is contributed by PrinciRaj1992

Javascript




<script>
 
// Javascript program to group
// multiple occurrences of individual
// array elements
 
    // A simple method to group all occurrences
    // of individual elements
    function groupElements(arr, n)
    {
           
        // Initialize all elements as not visited
        let visited = Array(n).fill(0);
        for (let i = 0; i < n; i++)
        {
            visited[i] = false;
        }
   
        // Traverse all elements
        for (let i = 0; i < n; i++)
        {
               
            // Check if this is first occurrence
            if (!visited[i])
            {
                   
                // If yes, prlet it and all
                // subsequent occurrences
                document.write(arr[i] + " ");
                for (let j = i + 1; j < n; j++)
                {
                    if (arr[i] == arr[j])
                    {
                        document.write(arr[i] + " ");
                        visited[j] = true;
                    }
                }
            }
        }
    }
 
 
// Driver program
 
      let arr = [ 4, 6, 9, 2, 3, 4,
                        9, 6, 10, 4];
        let n = arr.length;
        groupElements(arr, n);
       
</script>

Output: 

4 4 4 6 6 9 9 2 3 10

Time complexity of the above method is O(n2). 
Binary Search Tree based Method: The time complexity can be improved to O(nLogn) using self-balancing binary search tree like Red-Black Tree or AVL tree. Following is complete algorithm. 
1) Create an empty Binary Search Tree (BST). Every BST node is going to contain an array element and its count. 
2) Traverse the input array and do following for every element. 
……..a) If element is not present in BST, then insert it with count as 0. 
……..b) If element is present, then increment count in corresponding BST node. 
3) Traverse the array again and do following for every element. 
…….. If element is present in BST, then do following 
……….a) Get its count and print the element ‘count’ times. 
……….b) Delete the element from BST.
Time Complexity of the above solution is O(nLogn).
Hashing based Method: We can also use hashing. The idea is to replace Binary Search Tree with a Hash Map in above algorithm. 
Below is Implementation of hashing based solution. 
 



Java




/* Java program to group multiple occurrences of individual array elements */
import java.util.HashMap;
 
class Main
{
    // A hashing based method to group all occurrences of individual elements
    static void orderedGroup(int arr[])
    {
        // Creates an empty hashmap
        HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>();
 
        // Traverse the array elements, and store count for every element
        // in HashMap
        for (int i=0; i<arr.length; i++)
        {
           // Check if element is already in HashMap
           Integer prevCount = hM.get(arr[i]);
           if (prevCount == null)
                prevCount = 0;
            
           // Increment count of element element in HashMap
           hM.put(arr[i], prevCount + 1);
        }
 
        // Traverse array again
        for (int i=0; i<arr.length; i++)
        {
            // Check if this is first occurrence
            Integer count =  hM.get(arr[i]);    
            if (count != null)
            {
                // If yes, then print the element 'count' times
                for (int j=0; j<count; j++)
                   System.out.print(arr[i] + " ");
                 
                // And remove the element from HashMap.
                hM.remove(arr[i]);
            }
        }
    }
 
    // Driver method to test above method
    public static void main (String[] args)
    {
        int arr[] = {10, 5, 3, 10, 10, 4, 1, 3};
        orderedGroup(arr);
    }
}

Python3




# Python3 program to group multiple
# occurrences of individual array elements
 
# A hashing based method to group
# all occurrences of individual elements
def orderedGroup(arr):
     
    # Creates an empty hashmap
    hM = {}
 
    # Traverse the array elements, and store
    # count for every element in HashMap
    for i in range(0, len(arr)):
         
        # Increment count of elements
        # in HashMap
        hM[arr[i]] = hM.get(arr[i], 0) + 1
         
    # Traverse array again
    for i in range(0, len(arr)):
         
        # Check if this is first occurrence
        count = hM.get(arr[i], None)    
        if count != None:
             
            # If yes, then print
            # the element 'count' times
            for j in range(0, count):
                print(arr[i], end = " ")
                 
            # And remove the element from HashMap.
            del hM[arr[i]]
 
# Driver Code
if __name__ == "__main__":
     
    arr = [10, 5, 3, 10, 10, 4, 1, 3]
    orderedGroup(arr)
     
# This code is contributed by Rituraj Jain

C#




// C# program to group multiple occurrences
// of individual array elements
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A hashing based method to group
// all occurrences of individual elements
static void orderedGroup(int []arr)
{
    // Creates an empty hashmap
    Dictionary<int,
               int> hM = new Dictionary<int,
                                        int>();
 
    // Traverse the array elements,
    // and store count for every element in HashMap
    for (int i = 0; i < arr.Length; i++)
    {
        // Check if element is already in HashMap
        int prevCount = 0;
        if (hM.ContainsKey(arr[i]))
                prevCount = hM[arr[i]];
             
        // Increment count of element element in HashMap
        if (hM.ContainsKey(arr[i]))
            hM[arr[i]] = prevCount + 1;
        else
            hM.Add(arr[i], prevCount + 1);
    }
 
    // Traverse array again
    for (int i = 0; i < arr.Length; i++)
    {
        // Check if this is first occurrence
        int count = 0;
        if (hM.ContainsKey(arr[i]))
            count = hM[arr[i]];
        if (count != 0)
        {
            // If yes, then print the
            // element 'count' times
            for (int j = 0; j < count; j++)
            Console.Write(arr[i] + " ");
             
            // And remove the element from HashMap.
            hM.Remove(arr[i]);
        }
    }
}
 
// Driver Code
public static void Main (String[] args)
{
    int []arr = {10, 5, 3, 10, 10, 4, 1, 3};
    orderedGroup(arr);
}
}
 
// This code is contributed by Princi Singh

Javascript




<script>
 
      // JavaScript program to group multiple occurrences
      // of individual array elements
      // A hashing based method to group
      // all occurrences of individual elements
      function orderedGroup(arr) {
        // Creates an empty hashmap
        var hM = {};
 
        // Traverse the array elements,
        // and store count for every element in HashMap
        for (var i = 0; i < arr.length; i++) {
          // Check if element is already in HashMap
          var prevCount = 0;
          if (hM.hasOwnProperty(arr[i])) prevCount = hM[arr[i]];
 
          // Increment count of element element in HashMap
          if (hM.hasOwnProperty(arr[i])) hM[arr[i]] = prevCount + 1;
          else hM[arr[i]] = prevCount + 1;
        }
 
        // Traverse array again
        for (var i = 0; i < arr.length; i++) {
          // Check if this is first occurrence
          var count = 0;
          if (hM.hasOwnProperty(arr[i])) count = hM[arr[i]];
          if (count !== 0) {
            // If yes, then print the
            // element 'count' times
            for (var j = 0; j < count; j++)
            document.write(arr[i] + " ");
 
            // And remove the element from HashMap.
            delete hM[arr[i]];
          }
        }
      }
 
      // Driver Code
      var arr = [10, 5, 3, 10, 10, 4, 1, 3];
      orderedGroup(arr);
       
</script>

Output: 

10 10 10 5 3 3 4 1 

Time Complexity of the above hashing based solution is Θ(n) under the assumption that insert, search and delete operations on HashMap take O(1) time.
Below is a related problem for strings. 
Group all occurrences of characters according to first appearance
This article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :