tutorialcup
Find All Numbers Disappeared in an Array Leetcode Solution
Problem Statement
In this problem, we are given an array of integers. It contains elements ranging from 1 to N, where N = size of the array. However, there are some elements that have disappeared and some duplicates are present in their place. Our goal is to return an array of all such disappeared integers.
Example
Array = {1 , 2 , 5 , 6 , 2 , 5}
3 4
Array = {1 , 2 , 3 , 4}
n
Approach(Using HashSet)
We can mark every element in the array and then loop in the range: to check which elements have disappeared or are missing in the array. We use a hash set to store whether an integer has been marked or not.
Algorithm
- Initialize a hash set mark to store elements that are present.
- For every element i in the array:
- Add i to mark
- Initialize a List/vector result to store missing elements in the array
- For every element i in the range: :
- If i is not present in mark:
- Add it to result
- Return result
- Print the result
Implementation of Find All Numbers Disappeared in an Array Leetcode Solution
C++ Program
#include
using namespace std;
vector findDisappearedNumbers(vector &a)
{
unordered_set mark;
for(int &i : a)
mark.insert(i);
int N = a.size();
vector result;
for(int i = 1 ; i
www.tutorialcup.com/leetcode-solutions/find-all-numbers-d...
Find All Numbers Disappeared in an Array Leetcode Solution
Problem Statement
In this problem, we are given an array of integers. It contains elements ranging from 1 to N, where N = size of the array. However, there are some elements that have disappeared and some duplicates are present in their place. Our goal is to return an array of all such disappeared integers.
Example
Array = {1 , 2 , 5 , 6 , 2 , 5}
3 4
Array = {1 , 2 , 3 , 4}
n
Approach(Using HashSet)
We can mark every element in the array and then loop in the range: to check which elements have disappeared or are missing in the array. We use a hash set to store whether an integer has been marked or not.
Algorithm
- Initialize a hash set mark to store elements that are present.
- For every element i in the array:
- Add i to mark
- Initialize a List/vector result to store missing elements in the array
- For every element i in the range: :
- If i is not present in mark:
- Add it to result
- Return result
- Print the result
Implementation of Find All Numbers Disappeared in an Array Leetcode Solution
C++ Program
#include
using namespace std;
vector findDisappearedNumbers(vector &a)
{
unordered_set mark;
for(int &i : a)
mark.insert(i);
int N = a.size();
vector result;
for(int i = 1 ; i
www.tutorialcup.com/leetcode-solutions/find-all-numbers-d...