# Group multiple occurrence of array elements ordered by first occurrence

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}
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 ` `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

## 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 `

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 hM = ``new` `HashMap(); ` ` `  `        ``// Traverse the array elements, and store count for every element ` `        ``// in HashMap ` `        ``for` `(``int` `i=``0``; i

## 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 `

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

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

2

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.