Leetcode 779: K-th Symbol in Grammar

grid47
grid47
Exploring patterns and algorithms
Aug 21, 2024 5 min read

A sequence where the kth symbol is found, glowing softly as it is located.
Solution to LeetCode 779: K-th Symbol in Grammar Problem

We build a sequence of rows starting with the string ‘0’ in the first row. For each subsequent row, every occurrence of ‘0’ from the previous row is replaced with ‘01’, and every occurrence of ‘1’ is replaced with ‘10’. Given two integers n and k, return the k-th (1-indexed) symbol in the n-th row.
Problem
Approach
Steps
Complexity
Input: The input consists of two integers n and k, where n represents the row number and k represents the position of the symbol in that row.
Example: Input: n = 3, k = 4
Constraints:
• 1 <= n <= 30
• 1 <= k <= 2^n - 1
Output: The output is the k-th (1-indexed) symbol in the n-th row of the sequence.
Example: Output: 1
Constraints:
• The output must be either 0 or 1, depending on the symbol at position k in row n.
Goal: The goal is to determine the k-th symbol in the n-th row without explicitly constructing the entire row.
Steps:
• If n is 1, return 0 (base case).
• If k is even, recursively find the symbol in the previous row at the index k / 2, and invert it.
• If k is odd, recursively find the symbol in the previous row at the index (k + 1) / 2, and return it as is.
Goal: The solution must handle large values of n and k efficiently. We cannot construct the entire row for large n due to exponential growth in size.
Steps:
• n is guaranteed to be at most 30, meaning we can handle 2^n symbols.
• k must be a valid index for the n-th row, i.e., 1 <= k <= 2^n - 1.
Assumptions:
• Both n and k are valid inputs, with k within the range for the n-th row.
Input: Example 1: Input: n = 1, k = 1
Explanation: The first row is '0', so the 1st symbol is '0'.

Input: Example 2: Input: n = 3, k = 4
Explanation: Row 3 is '0110', and the 4th symbol is '1'.

Input: Example 3: Input: n = 2, k = 2
Explanation: Row 2 is '01', and the 2nd symbol is '1'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus