Given a positive integer N, the task is to find the lexicographically largest string consisting of lower-case English alphabets such that the sum of the characters of the string equals N where ‘a’ = 1, ‘b’ = 2, ‘c’ = 3, ….. , and ‘z’ = 26.
Examples:
Input: N = 30
Output: zd
Explanation:
The lexicographically largest string formed is “zd” whose sum of position of characters is (26 + 4) = 30(= N).
Input: N = 14
Output: n
Approach: To make lexicographically the largest string, the idea is to print the character z, N/26 number of times and then the character at (N%26 + 1)th position in the English alphabets. Follow the steps below to solve the problem:
- Initialize a string, say ans, that stores the required lexicographically largest string.
- Iterate until N is at least 26 and perform the following steps:
- Add the character z to the string ans.
- Decrement the value of N by 26.
- Add the value of char(N + ‘a’) to the string ans.
- After completing the above steps, print the value of ans as the resultant string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string getString( int N)
{
string ans = "" ;
while (N >= 26) {
ans += 'z' ;
N -= 26;
}
ans += char (N + 'a' - 1);
return ans;
}
int main()
{
int N = 30;
cout << getString(N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
static String getString( int N)
{
String ans = "" ;
while (N >= 26 ) {
ans += 'z' ;
N -= 26 ;
}
ans += ( char )(N + 'a' - 1 );
return ans;
}
public static void main(String[] args)
{
int N = 30 ;
System.out.print(getString(N));
}
}
|
Python3
def getString(N):
ans = ""
while (N > = 26 ):
ans + = 'z'
N - = 26
ans + = chr (N + ord ( 'a' ) - 1 )
return ans
if __name__ = = '__main__' :
N = 30
print (getString(N))
|
C#
using System;
public class GFG {
static string getString( int N)
{
string ans = "" ;
while (N >= 26) {
ans += 'z' ;
N -= 26;
}
ans += ( char )(N + 'a' - 1);
return ans;
}
public static void Main( string [] args)
{
int N = 30;
Console.WriteLine(getString(N));
}
}
|
Javascript
<script>
function getString(N){
let ans = ""
while (N >= 26){
ans += 'z'
N -= 26
}
ans += String.fromCharCode(N + 'a' .charCodeAt(0) - 1)
return ans
}
let N = 30
document.write(getString(N))
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)