Open In App

Find the string of length N according to the given conditions

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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)
      • Append “-1” to sb
  • 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)


Output

dbaaa

Time Complexity: O(N), where N is the length of the output string
Auxiliary Space: O(26) ~ O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads