@@ -6,7 +6,82 @@ class Solution {
6
6
string findDifferentBinaryString (vector<string>& nums) {
7
7
string result;
8
8
for (int i = 0 ; i < size (nums); ++i) {
9
- result.push_back ((nums[i][i] == ' 0' ) ? : ' 1' : ' 0' );
9
+ result.push_back ((nums[i][i] == ' 0' ) ? ' 1' : ' 0' );
10
+ }
11
+ return result;
12
+ }
13
+ };
14
+
15
+ // Time: O(k * n) = O(n^2), k is len(nums)
16
+ // , n is len(nums[0])
17
+ // Space: O(k) = O(n)
18
+ class Solution2 {
19
+ public:
20
+ string findDifferentBinaryString (vector<string>& nums) {
21
+ const int n = size (nums[0 ]);
22
+ unordered_set<int > lookup;
23
+ for (const auto & x : nums) { // Time: O(k * n) = O(n^2)
24
+ lookup.emplace (to_decimal (x));
25
+ }
26
+ const int total = 1 << n;
27
+ for (int i = 0 ; i < total; ++i) { // Time: O(k + n) = O(n)
28
+ if (!lookup.count (i)) {
29
+ return to_binary (i, n);
30
+ }
31
+ }
32
+ return " " ;
33
+ }
34
+
35
+ private:
36
+ int to_decimal (const string& num) { // Time: O(n)
37
+ return accumulate (cbegin (num), cend (num), 0 ,
38
+ [](const auto & total, const auto & x) {
39
+ return total * 2 + (x - ' 0' );
40
+ });
41
+ }
42
+
43
+ string to_binary (int num, int n) { // Time: O(n)
44
+ string result;
45
+ for (int basis = 1 << (n - 1 ); basis; basis >>= 1 ) {
46
+ result.push_back ((num & basis) ? ' 1' : ' 0' );
47
+ }
48
+ return result;
49
+ }
50
+ };
51
+
52
+ // Time: O(k * n + n * 2^n) = O(n * 2^n), k is len(nums)
53
+ // , n is len(nums[0])
54
+ // Space: O(k) = O(1) ~ O(2^n)
55
+ class Solution_Extra {
56
+ public:
57
+ vector<string> findAllDifferentBinaryStrings (vector<string>& nums) {
58
+ const int n = size (nums[0 ]);
59
+ unordered_set<int > lookup;
60
+ for (const auto & x : nums) { // Time: O(k * n) = O(n * 2^n)
61
+ lookup.emplace (to_decimal (x));
62
+ }
63
+ vector<string> result;
64
+ const int total = 1 << n;
65
+ for (int i = 0 ; i < total; ++i) { // Time: O(2^n + n * (2^n - k))
66
+ if (!lookup.count (i)) {
67
+ result.emplace_back (to_binary (i, n));
68
+ }
69
+ }
70
+ return result;
71
+ }
72
+
73
+ private:
74
+ int to_decimal (const string& num) { // Time: O(n)
75
+ return accumulate (cbegin (num), cend (num), 0 ,
76
+ [](const auto & total, const auto & x) {
77
+ return total * 2 + (x - ' 0' );
78
+ });
79
+ }
80
+
81
+ string to_binary (int num, int n) { // Time: O(n)
82
+ string result;
83
+ for (int basis = 1 << (n - 1 ); basis; basis >>= 1 ) {
84
+ result.push_back ((num & basis) ? ' 1' : ' 0' );
10
85
}
11
86
return result;
12
87
}
0 commit comments