On the first row, we write a 0
. 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
.
Given row N
and index K
, return the K-th
indexed symbol in row N
. (The values of K
are 1-indexed.)
Examples:
Input: N = 1, K = 1
Output: 0
Input: N = 2, K = 1
Output: 0
Input: N = 2, K = 2
Output: 1
Input: N = 4, K = 5
Output: 1
Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001
Note:
Learn More →
class Solution:
def kthGrammar(self, N: int, K: int) -> int:
if N == 1:
return "0"
else:
row = self.kthGrammar(N-1, (K+1)//2)
if row == "0":
return "0" if (K%2)-1 == 0 else "1"
else:
return "1" if (K%2)-1 == 0 else "0"
class Solution:
def kthGrammar(self, N: int, K: int) -> int:
if N == 1:
# Base case:
return 0
else:
# General case:
if K % 2 == 0:
# even index of current level is opposite of parent level's [(K+1)//2]
return 0 if self.kthGrammar(N-1, (K+1)//2) else 1
else:
# odd index of current level is the same as parent level's [(K+1)//2]
return 1 if self.kthGrammar(N-1, (K+1)//2) else 0
https://leetcode.com/problems/find-k-closest-elements/ Naive def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: L = sorted([(abs(elt - x), elt) for elt in arr], key=lambda tup: tup[0]) return sorted([tup[1] for tup in L[:k]]) Opti
Sep 23, 2022Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack();
Jun 27, 2022Given a string containing just the characters $($, $)$, ${$, $}$, $[$ and $]$, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Jun 27, 2022Solution 1 Time complexity: O(n³) Space complexity: O(n) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return []
Apr 23, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up