[
string
math
greedy
]
BinarySearch 0842 Lexicographically Smallest String of Distance K
Problem statement
https://binarysearch.com/problems/Lexicographically-Smallest-String-of-Distance-K/
Solution
Equal to Leetcode 1663. Smallest String With A Given Numeric Value (but change n
and k
).
Complexity
Time and space is O(n)
, because we need go construct the string.
Code
class Solution:
def solve(self, k, n):
p = max(0, (26*n - k - 1)//25)
q = k - 26*n + 25*p + 26
return "a"*p + chr(96 + q) + "z"*(n-p-1)