Find the string of length N according to the given conditions
Last Updated :
29 Jan, 2024
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:
- Where the Cumulative sum of the string is: For each character add 2pos into the sum. Where pos is equivalent to the position of the character in the alphabet series. For example: a = 0, b = 1, c = 2 . . . . z = 25.
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:
- Create an array let say Power[] of length 26.
- Run a loop and initialize 2's power into Power[] from 20 to 225
- Create a StringBuilder let say Sb
- If (N > K), append "-1" to Sb
- Else if (N == K) append 'a' to Sb N times.
- Else if (N < K),
- Find the highest power of 2 that is less than or equal to K and store it in a variable, P.
- While (N > 0)
- Initialize remk with (K - Power[P])
- If(remk < (N - 1)), decrease P by 1
- Else, append character corresponding to P to sb, decrease N by 1 and update K = remK
- If (K > 0)
- Output Sb.
Code to implement the approach:
C++
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
// Function to solve the problem
void solve(int N, int K) {
// Array for storing powers of 2
int power[26];
// Loop for initializing powers of 2 in array
for (int i = 0; i < 26; i++) {
power[i] = pow(2, i);
}
// StringBuilder equivalent in C++ is string
string sb = "";
// Condition for no possible string
if (N > K) {
sb = "-1";
}
// Condition for creating string with 'a' repeated K times
else if (N == K) {
for (int i = 0; i < N; i++) {
sb += 'a';
}
}
// Condition for other cases
else {
int i = 0;
while (i < 26) {
if (power[i] == K || power[i] > K) {
break;
}
i++;
}
int P = i - 1;
while (N > 0) {
int remk = K - power[P];
if (remk < N - 1) {
P--;
}
else {
sb += (char)(97 + P);
N--;
K = remk;
}
}
if (K > 0) {
sb = "-1";
}
}
// Printing the required string
cout << sb << endl;
}
// Driver code
int main() {
int N = 5;
int K = 13;
solve(N, K);
return 0;
}
// This code is contributed by shivamgupta0987654321
Java
// Java code to implement the approach
import java.util.*;
// Driver class
public class GFG {
// Driver function
public static void main(String[] args)
{
// Inputs
int N = 5;
int K = 13;
// Function call
solve(N, K);
}
public static void solve(int N, int K)
{
// Array for storing powers of 2
int power[] = new int[26];
// Loop for initializing
// powers of 2 in array
for (int i = 0; i < power.length; i++) {
power[i] = (int)Math.pow(2, i);
}
// StringBuilder to hold String
// Manipulations
StringBuilder sb = new StringBuilder();
/*In such conditions no
String is possible
to create*/
if (N > K) {
sb.append("-1");
}
// In such case only
// String possible string
// is: character 'a' K times
else if (N == K) {
for (int i = 0; i < N; i++) {
sb.append("a");
}
}
// In cases like (N<K), we will add characters
// starting from the beginning
else {
int i = 0;
for (i = 0; i < power.length; i++) {
if (power[i] == K || power[i] > K) {
break;
}
}
int P = i - 1;
while (N > 0) {
int remk = K - power[P];
if (remk < N - 1) {
P--;
}
else {
sb.append((char)(97 + P));
N--;
K = remk;
}
}
if (K > 0) {
sb = new StringBuilder();
sb.append("-1");
}
}
// Printing the required String
System.out.println(sb.toString());
}
}
Python3
# Function to solve the problem
def solve(N, K):
# Array for storing powers of 2
power = [2**i for i in range(26)]
# StringBuilder to hold String Manipulations
sb = []
# In such conditions no String is possible to create
if N > K:
sb.append("-1")
# In such case only String possible string is: character 'a' K times
elif N == K:
sb.append("a" * N)
# In cases like (N < K), we will add characters starting from the beginning
else:
i = 0
while i < len(power):
if power[i] == K or power[i] > K:
break
i += 1
P = i - 1
while N > 0:
remk = K - power[P]
if remk < N - 1:
P -= 1
else:
sb.append(chr(97 + P))
N -= 1
K = remk
if K > 0:
sb = ["-1"]
print("".join(sb))
# Driver function
def main():
# Inputs
N = 5
K = 13
# Function call
solve(N, K)
# Driver code
if __name__ == "__main__":
main()
C#
using System;
using System.Text;
public class GFG
{
// Driver function
public static void Main(string[] args)
{
// Inputs
int N = 5;
int K = 13;
// Function call
Solve(N, K);
}
public static void Solve(int N, int K)
{
// Array for storing powers of 2
int[] power = new int[26];
// Loop for initializing
// powers of 2 in array
for (int i = 0; i < power.Length; i++)
{
power[i] = (int)Math.Pow(2, i);
}
// StringBuilder to hold String
// Manipulations
StringBuilder sb = new StringBuilder();
/*In such conditions no
String is possible
to create*/
if (N > K)
{
sb.Append("-1");
}
// In such case only
// String possible string
// is: character 'a' K times
else if (N == K)
{
for (int i = 0; i < N; i++)
{
sb.Append("a");
}
}
// In cases like (N<K), we will add characters
// starting from the beginning
else
{
int i = 0;
for (i = 0; i < power.Length; i++)
{
if (power[i] == K || power[i] > K)
{
break;
}
}
int P = i - 1;
while (N > 0)
{
int remk = K - power[P];
if (remk < N - 1)
{
P--;
}
else
{
sb.Append((char)(97 + P));
N--;
K = remk;
}
}
if (K > 0)
{
sb = new StringBuilder();
sb.Append("-1");
}
}
// Printing the required String
Console.WriteLine(sb.ToString());
}
}
// This code is contributed by shivamgupta0987654321
JavaScript
// JavaScript Implementation
function solve(N, K) {
const power = [];
for (let i = 0; i < 26; i++) {
power[i] = Math.pow(2, i);
}
let sb = "";
if (N > K) {
sb = "-1";
} else if (N === K) {
for (let i = 0; i < N; i++) {
sb += 'a';
}
} else {
let i = 0;
while (i < 26) {
if (power[i] === K || power[i] > K) {
break;
}
i++;
}
let P = i - 1;
while (N > 0) {
const remk = K - power[P];
if (remk < N - 1) {
P--;
} else {
sb += String.fromCharCode(97 + P);
N--;
K = remk;
}
}
if (K > 0) {
sb = "-1";
}
}
console.log(sb);
}
const N = 5;
const K = 13;
solve(N, K);
// This code is contributed by Tapesh(tapeshdu420)
Time Complexity: O(N), where N is the length of the output string
Auxiliary Space: O(26) ~ O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read