Skip to content

Commit 374ab8f

Browse files
authored
Create the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.py
1 parent 1609183 commit 374ab8f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def getHappyString(self, n, k):
6+
"""
7+
:type n: int
8+
:type k: int
9+
:rtype: str
10+
"""
11+
base = 2**(n-1)
12+
if k > 3*base:
13+
return ""
14+
result = [chr(ord('a')+(k-1)//base)]
15+
while base > 1:
16+
k -= (k-1)//base*base
17+
base //= 2
18+
result.append(('a' if result[-1] != 'a' else 'b') if (k-1)//base == 0 else
19+
('c' if result[-1] != 'c' else 'b'))
20+
return "".join(result)

0 commit comments

Comments
 (0)