![]() |
VOOZH | about |
Given an array arr[] of integers of size n, where each element is in the range 1 to n and each element can occur at most twice, find all elements that appear twice in the array.
Examples:
Input: arr[] = [2, 3, 1, 2, 3]
Output: [2, 3]
Explanation: 2 and 3 occur twice in the given array.Input: arr[] = [3, 1, 2]
Output: []
Explanation: There is no repeating element in the array, so the output is empty.
Table of Content
The main Idea is to iterate through each element and check if it already exists in the result. If not, we scan the rest of the array to see if it appears again. If it does, we add it to the result.
2 3
The main Idea is to traverse the array once and count the occurrences of each element using a frequency array. Then, we iterate through the array to collect elements whose frequency 2, indicating they are duplicates.
3 2
The main Idea is to iterate over the array and use the value of each element as an index (after subtracting 1). If the element at that index is positive, we negate it to mark the number as visited. If it's already negative, it means we've seen it before, so we add it to the result. This avoids extra space and works in linear time.
Step by step approach:
2 3