Skip to content

Commit c95626b

Browse files
committed
Add solution #779
1 parent c0d7718 commit c95626b

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,7 @@
589589
775|[Global and Local Inversions](./0775-global-and-local-inversions.js)|Medium|
590590
777|[Swap Adjacent in LR String](./0777-swap-adjacent-in-lr-string.js)|Medium|
591591
778|[Swim in Rising Water](./0778-swim-in-rising-water.js)|Hard|
592+
779|[K-th Symbol in Grammar](./0779-k-th-symbol-in-grammar.js)|Medium|
592593
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
593594
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
594595
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 779. K-th Symbol in Grammar
3+
* https://leetcode.com/problems/k-th-symbol-in-grammar/
4+
* Difficulty: Medium
5+
*
6+
* We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every
7+
* subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and
8+
* each occurrence of 1 with 10.
9+
*
10+
* - For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
11+
*
12+
* Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
13+
*/
14+
15+
/**
16+
* @param {number} n
17+
* @param {number} k
18+
* @return {number}
19+
*/
20+
var kthGrammar = function(n, k) {
21+
if (n === 1) return 0;
22+
23+
const length = 1 << (n - 1);
24+
const mid = length / 2;
25+
26+
if (k <= mid) {
27+
return kthGrammar(n - 1, k);
28+
} else {
29+
return 1 - kthGrammar(n - 1, k - mid);
30+
}
31+
};

0 commit comments

Comments
 (0)