Lexicographically smallest numeric string having odd digit counts
Last Updated :
07 Feb, 2023
Given a positive integer N, the task is to generate a lexicographically smallest numeric string of size N having an odd count of each digit.
Examples:
Input: N = 4
Output: 1112
Explanation:
Digit 1 and 2 both have an even count and is the lexicographically smallest string possible.
Input: N = 5
Output: 11111
Explanation:
Digit 1 has an odd count and is the lexicographically smallest string possible.
Approach: The given problem can be solved based on the observation that if the value of N is even, then the resulting string contains 1s, (N – 1) number of times followed by a single 2 is the smallest lexicographic string possible. Otherwise, the resulting string contains 1s, N number of times is the smallest lexicographic string possible.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
string genString( int N)
{
string ans = "" ;
if (N % 2 == 0) {
ans = string(N - 1, '1' ) + '2' ;
}
else {
ans = string(N, '1' );
}
return ans;
}
int main()
{
int N = 5;
cout << genString(N);
return 0;
}
|
Python3
def genString(N):
ans = ""
if (N % 2 = = 0 ) :
ans = " ".join(" 1 " for i in range (N - 1 ))
ans = ans + "2"
else :
ans = " ".join(" 1 " for i in range (N))
return ans
if __name__ = = "__main__" :
N = 5
print (genString(N))
|
C#
using System;
class GFG {
static string genString( int N)
{
string ans = "" ;
if (N % 2 == 0) {
for ( int i = 0; i < N - 1; i++)
ans += '1' ;
ans += '2' ;
}
else {
for ( int i = 0; i < N; i++)
ans += '1' ;
}
return ans;
}
public static void Main()
{
int N = 5;
Console.WriteLine(genString(N));
}
}
|
Javascript
<script>
function genString(N)
{
let ans = "" ;
if (N % 2 == 0) {
ans = '1' .repeat(N - 1) + '2' ;
}
else {
ans = '1' .repeat(N);
}
return ans;
}
let N = 5;
document.write(genString(N));
</script>
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static String genString( int N) {
String ans = "" ;
if (N % 2 == 0 ) {
ans = new String( new char [N - 1 ]).replace( "\0" , "1" ) + "2" ;
}
else {
ans = new String( new char [N]).replace( "\0" , "1" );
}
return ans;
}
public static void main(String[] args) {
int N = 5 ;
System.out.println(genString(N));
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...