![]() |
VOOZH | about |
Given an integer array, print all repeating elements (Elements that appear more than once) in the array. The output should contain elements according to their first occurrences.
Examples:
Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}
Output: 10 45Input: arr[] = {1, 2, 3, 4, 2, 5}
Output:2Input: arr[] = {1, 1, 1, 1, 1}
Output: 1
We iterate through the array using two nested loops to compare each element with every other element in the array. If an element appears more than once, we insert it into the set. The repeating variable is used to keep track of whether an element has already been inserted into the set. Once a repeating element is found, we break out of the inner loop to avoid inserting it multiple times.
Finally, we print the contents of the set to get the repeating elements in the order of their first occurrence.
Below is the implementation of the above approach:
10 45
Time Complexity: O(n^2) .
Auxiliary Space: O(k), where k is the number of repeating element .
The idea is to use Hashing to solve this in O(n) time on average. We store elements and their counts in a hash table. After storing counts, we traverse input array again and print those elements whose counts are more than once. To make sure that every output element is printed only once, we set count as 0 after printing the element.
Below is the implementation of the above approach:
10 45
Time Complexity:O(n) under the assumption that hash insert and search functions work in O(1) time.
Auxiliary Space: O(n), where n represents the size of the given array.
- Count all the frequencies of all elements using Counter() function.
- Traverse in this frequency dictionary and print all keys whose value is greater than 1.
Below is the implementation of above approach:
10 45
Time complexity: O(n), where n is the number of elements in the input array arr.
Auxiliary Space: O(n), where n represents the size of the given array.
we can use lower_bound function to find first occurrence of arr[i] and Upper_bound function to find last occurrence of x and if the last_index-first_ind+1>1 means , arr[i] has more than one frequency.
Below is the implementation of above approach:
10 45
Time Complexity: O(n*log2n), Take log2n for binary search function(upper and lower bound)
Auxiliary Space: O(1)
In this approach, the code iterates over an array and identifies the repeating numbers by comparing the index of each element with its first and last occurrence. It returns an array containing only the unique repeating numbers.
[ 1, 3, 5, 7 ]
Time Complexity: O(n^2), where n is the length of the input array.
Auxiliary Space: O(m), where m is the number of unique repeating numbers in the input array.