forked from Ritesh25696/interviewBit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Repeat and Missing Number Array
56 lines (43 loc) · 1.37 KB
/
Repeat and Missing Number Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Note that in your output A should precede B.
Example:
Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4
// Space Complexity = 0(n)
vector<int> Solution::repeatedNumber(const vector<int> &A) {
vector<int> B(A.size()+1,0);
vector<int> result;
for(int i=0 ; i<A.size() ; i++){
if(B[A[i]] == 0){
B[A[i]] = 1;
}
else {
result.push_back(A[i]);
}
}
for(int i=1 ; i<B.size() ; i++){
if(B[i] == 0){
result.push_back(i);
}
}
B.erase();
return result;
}
// uses no extra memory
long long int len = A.size();
long long int sumOfN = (len * (len+1) ) /2, sumOfNsq = (len * (len +1) *(2*len +1) )/6;
long long int missingNumber1=0, missingNumber2=0;
for(int i=0;i<A.size(); i++){
sumOfN -= (long long int)A[i];
sumOfNsq -= (long long int)A[i]*(long long int)A[i];
}
missingNumber1 = (sumOfN + sumOfNsq/sumOfN)/2;
missingNumber2= missingNumber1 - sumOfN;
vector <int> ans;
ans.push_back(missingNumber2);
ans.push_back(missingNumber1);
return ans;