-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_single.cpp
More file actions
61 lines (45 loc) · 1.27 KB
/
find_single.cpp
File metadata and controls
61 lines (45 loc) · 1.27 KB
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
57
58
59
60
61
//
// Created by Mayank Parasar on 2020-02-02.
//
/*
* Given an array of integers, arr, where all numbers occur twice except one number which occurs once,
* find the number. Your solution should ideally be O(n) time and use constant extra space.
Example:
Input: arr = [7, 3, 5, 5, 4, 3, 4, 8, 8]
Output: 7
*/
#include <iostream>
#include <vector>
using namespace std;
int findSingle(vector<int>& arr, vector<int>& v, int min) { // this is O(n) in computation and O(n) in space
for(auto i : arr) {
if(v[i-min] == -1)
v[i-min] = i;
else
v[i-min] = -1;
}
// now traverse the v-vector and return the first non '-1' number.
for(auto i : v){
if(i != -1)
return i;
}
}
// this is constant space and O(n) complexity
int findSingle_XOR(vector<int>& arr) {
int res = 0;
for(auto i : arr) {
res = res ^ i;
}
return res;
}
int main() {
vector<int> arr = {7, 3, 5, 5, 4, 3, 4, 8, 8};
// considering we know the min and max of this array
// sparsity of number can be dealth with another level
// of indirection.
vector<int> v(6, -1); // '3' maps to 0 and '8' maps to 5 index
cout << findSingle(arr, v, 3);
cout << endl;
cout<< findSingle_XOR(arr);
return 0;
}