- Related Questions & Answers
- Average numbers in array in C Programming
- Add minimum number to an array so that the sum becomes even in C programming
- C Program to Multiply two Floating Point Numbers?
- C program to find the length of a string?
- Sum triangle from an array in C programming
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of first n natural numbers in C Program
- How to find the unicode category for a given character in Java?
- How to find the number of days in a month of a particular year in Java?
- Sum of squares of first n natural numbers in C Program?
- Sum of squares of the first n even numbers in C Program
- To find sum of even factors of a number in C++ Program?
- 5 Different methods to find the length of a string in C++?
- A Boolean Array Puzzle in C?
- A shorthand array notation in C for repeated values?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array of n elements. Some elements appear twice and other appear once. Elements are in range 1 <= A[i] <= n. We have to find those elements that are not present in the array. The constraint is that we have to solve this problem without using extra space, and time will be O(n).

So if the array is [4, 3, 2, 7, 8, 2, 3, 1], then result will be [5, 6]

To solve this, we will follow these steps −

- let n is the size of the array
- for i in range 0 to n – 1
- x := |A[i]| - 1
- if A[x] > 0, then A[x] := - A[x]

- define answer as an array
- for i in range 0 to n – 1
- if A[i] > 0, then add i + 1 into the answer

- return the answer

Let us see the following implementation to get better understanding −

class Solution { public: vector<int> findDisappearedNumbers(vector<int>& v) { int n = v.size(); for(int i = 0;i < n; i++){ int x = abs(v[i]) - 1; if(v[x] > 0) v[x] = -v[x]; } vector <int> ans; for(int i = 0; i < n; i++){ if(v[i]>0)ans.push_back(i+1); } return ans; } };

[4,3,2,7,8,2,3,1]

[5,6]

Advertisements