-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0779-Kth_Symbol_in_Grammar.cpp
More file actions
106 lines (95 loc) · 2.37 KB
/
0779-Kth_Symbol_in_Grammar.cpp
File metadata and controls
106 lines (95 loc) · 2.37 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*******************************************************************************
* 0779-Kth_Symbol_in_Grammar.cpp
* Billy.Ljm
* 25 October 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/k-th-symbol-in-grammar/
*
* We build a table of n rows (1-indexed). We start by writing 0 in the 1st row.
* Now in every subsequent row, we look at the previous row and replace each
* occurrence of 0 with 01, and each occurrence of 1 with 10.
*
* For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row
* is 0110.
*
* Given two integer n and k, return the kth (1-indexed) symbol in the nth row
* of a table of n rows.
*
* ===========
* My Approach
* ===========
* We can think of the table as a binary tree; if the node is 0, then its left
* children is 0 and right children is 1. Then, we just have to traverse the
* one specific branch corresponding to the k-th element
*
* This has a time complexity of O(n), and space complexity of O(1), where n is
* the number of row / layers of replacements.
******************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
int kthGrammar(int n, int k) {
bool curr = 0; // current node value
int start = 0, end = pow(2, n - 1), mid; // range of index being expanded
// expand binary tree
while (end - start > 1) {
mid = (start + end) / 2;
cout << mid << endl;
if (k > mid) {
curr = !curr;
start = mid;
}
else {
curr = curr;
end = mid;
}
}
// find last node
if (k - 1 == start) return curr;
else return !curr;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
int n, k;
// test case 1
n = 1;
k = 1;
std::cout << "kthGrammar(" << n << "," << k << ") = ";
std::cout << sol.kthGrammar(n, k) << std::endl;
// test case 2
n = 2;
k = 1;
std::cout << "kthGrammar(" << n << "," << k << ") = ";
std::cout << sol.kthGrammar(n, k) << std::endl;
// test case 3
n = 2;
k = 2;
std::cout << "kthGrammar(" << n << "," << k << ") = ";
std::cout << sol.kthGrammar(n, k) << std::endl;
return 0;
}