Array elements that appear more than once using Iterative Comparison

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.

C++
#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int>
printAllRepeatingNumbers(std::vector<int>& arr)
{
    std::vector<int> res; // Create an empty vector to store
                          // the repeating numbers

    for (int i = 0; i < arr.size(); i++) {
        // Iterate over each element of the input array
        if (std::find(arr.begin(), arr.end(), arr[i])
                == arr.begin() + i
            && std::find(arr.rbegin(), arr.rend(), arr[i])
                   == arr.rbegin() + arr.size() - i - 1) {
            // Check if the current element is the first and
            // last occurrence If yes, it is not a repeating
            // number, so skip to the next element
            continue;
        }
        else {
            if (std::find(res.begin(), res.end(), arr[i])
                == res.end()) {
                // If the element is not the only
                // occurrence, check if it is already
                // present in the result vector If not, add
                // it to the result vector
                res.push_back(arr[i]);
            }
        }
    }

    return res; // Return the vector containing the
                // repeating numbers
}

int main()
{
    std::vector<int> input
        = { 1, 1, 2, 3, 4, 5, 3, 5, 1, 7, 7, 7 };
    std::vector<int> result
        = printAllRepeatingNumbers(input);

    std::cout << "[ ";
    for (int i = 0; i < result.size(); i++) {
        std::cout << result[i];
        if (i < result.size() - 1) {
            std::cout << ", ";
        }
    }
    std::cout << " ]" << std::endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    // Function to find and return all repeating numbers in
    // the array
    public static List<Integer>
    printAllRepeatingNumbers(int[] arr)
    {
        List<Integer> res
            = new ArrayList<>(); // Create a list to store
                                 // the repeating numbers
        Set<Integer> seen
            = new HashSet<>(); // Create a set to keep track
                               // of seen numbers

        for (int value : arr) {
            if (!seen.add(value)) {
                // If the number is already present in the
                // set, it's a repeating number
                if (!res.contains(value)) {
                    // Add the repeating number to the
                    // result list if it's not already
                    // present
                    res.add(value);
                }
            }
        }

        return res; // Return the list containing the
                    // repeating numbers
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 1, 2, 3, 4, 5, 3, 5, 1, 7, 7, 7 };
        List<Integer> result
            = printAllRepeatingNumbers(arr);
        System.out.println(
            "Repeating Numbers: "
            + result); // Output: [1, 3, 5, 7]
    }
}
Python3
def print_all_repeating_numbers(arr):
    res = []  # Create an empty list to store the repeating numbers

    for i in range(len(arr)):
        # Iterate over each element of the input list
        if arr.index(arr[i]) == i and arr[::-1].index(arr[i]) == len(arr) - i - 1:
            # Check if the current element is the first and last occurrence
            # If yes, it is not a repeating number, so skip to the next element
            continue
        else:
            if arr[i] not in res:
                # If the element is not the only occurrence,
                # check if it is already present in the result list
                # If not, add it to the result list
                res.append(arr[i])

    return res  # Return the list containing the repeating numbers


def main():
    input_list = [1, 1, 2, 3, 4, 5, 3, 5, 1, 7, 7, 7]
    result = print_all_repeating_numbers(input_list)

    print("[", end=" ")
    for i in range(len(result)):
        print(result[i], end="")
        if i < len(result) - 1:
            print(", ", end="")
    print(" ]")


if __name__ == "__main__":
    main()
JavaScript
// JavaScript program for the above approach
const printAllRepeatingNumbers = (arr) => {
    let res = []; // Create an empty array to store the repeating numbers

    arr.forEach((value, index) => {
        // Iterate over each element of the input array
        if (arr.indexOf(value) === index && arr.lastIndexOf(value) === index) {
            // Check if the current element is the first and last occurrence
            // If yes, it is not a repeating number, so return and skip to the next element
            return;
        } else {
            if (!res.includes(value)) {
                // If the element is not the only occurrence,
                // check if it is already present in the result array
                // If not, add it to the result array
                res.push(value);
            }
        }
    });

    return res; // Return the array containing the repeating numbers
};

console.log(printAllRepeatingNumbers([1, 1, 2, 3, 4, 5, 3, 5, 1, 7, 7, 7])); // Output: [1, 3, 5, 7]

// This code is contributed by Susobhan Akhuli

Output
[ 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.



Array elements that appear more than once

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 45

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

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

Similar Reads

Array elements that appear more than once using Naive approach:

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

Array elements that appear more than once using Hashing:

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

Array elements that appear more than once Using Built-in Python functions:

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

Array elements that appear more than once using Binary Search:

we can use binary search 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....

Array elements that appear more than once using Iterative Comparison:

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