![]() |
VOOZH | about |
Given two integers N and K. Then your task is to output the string of length N such that the cumulative sum of the string is equal to K:
Note: If no such string is possible then output -1. If there are multiple answers, then print any of them.
Examples:
Input: N = 5, K = 13
Output: dbaaa
Explanation: The value of Z for d, b and a are 3, 1 and 0. Then cumulative sum of dbaaa is: (23) + (21) + (3*(20)) = 8 + 2 + 3 = 13. So both conditions met, length of output string is N = 5 and cumulative sum is K = 13.Input: N = 4, K = 3
Output: -1
Explanation: It can be verified that no such string is possible.
Approach: Implement the idea to solve the problem
The problem is based on the Greedy logic and some observation. The problem can be divided into sub-parts as:
- If (N > K)
- No string of length N is possible in such cases. Because Minimum power of 2 is 1 so we need the cumulative sum to be at least equal to N.
- If (N == K)
- The answer will be a string of length N with all characters equal to 'a'.
- If (N < K)
- Define an array let say power[], which is initialized to store the powers of 2.
- Find the highest power of 2 that is less than or equal to K and store it in a variable let say P.
- While there are still characters left to add (N > 0), calculate the remaining value of K after subtracting the current power of 2 (remk = K - power[P]). If this remaining value is less than the number of characters left to add minus one (remk < N - 1), it decreases P by 1. Otherwise, it adds a character corresponding to the current power of 2 to the string, decreases N by 1, and updates K to the remaining value.
- If there's still a remaining value after all characters have been added (K > 0), it means a string couldn't be formed, so -1 is returned, else return the answer string.
Steps were taken to solve the problem:
Code to implement the approach:
dbaaa
Time Complexity: O(N), where N is the length of the output string
Auxiliary Space: O(26) ~ O(1)