- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find duplicate in an array in O(n) and by using O(1) extra space in C++
Suppose we have a list of numbers from 0 to n-1. A number can be repeated as many as a possible number of times. We have to find the repeating numbers without taking any extra space. If the value of n = 7, and list is like [5, 2, 3, 5, 1, 6, 2, 3, 4, 5]. The answer will be 5, 2, 3.
To solve this, we have to follow these steps −
- for each element e in the list, do the following steps −
- sign := A[absolute value of e]
- if the sign is positive, then make it negative
- Otherwise, it is a repetition.
Example
#include<iostream> #include<cmath> using namespace std; void findDuplicates(int arr[], int size) { for (int i = 0; i < size; i++) { if (arr[abs(arr[i])] >= 0) arr[abs(arr[i])] *= -1; else cout << abs(arr[i]) << " "; } } int main() { int arr[] = {5, 2, 3, 5, 1, 6, 2, 3, 4, 1}; int n = sizeof(arr)/sizeof(arr[0]); findDuplicates(arr, n); }
Output
5 2 3 1
- Related Articles
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Count frequencies of all elements in array in O(1) extra space and O(n) time in C++
- Rearrange positive and negative numbers in O(n) time and O(1) extra space in C++
- Find the maximum repeating number in O(n) time and O(1) extra space in Python
- Print n x n spiral matrix using O(1) extra space in C Program.
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Find median of BST in O(n) time and O(1) space in C++
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Rearrange array in alternating positive & negative items with O(1) extra space in C++
- Find median of BST in O(n) time and O(1) space in Python
- Find duplicates in constant array with elements 0 to N-1 in O(1) space in C++
- Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space using C++
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++
- A product array puzzle (O(1) Space) in C++?

Advertisements