The Wayback Machine - https://web.archive.org/web/20210929163455/https://www.geeksforgeeks.org/lexicographically-smallest-numeric-string-having-odd-digit-counts/
Skip to content
Related Articles

Related Articles

Improve Article

Lexicographically smallest numeric string having odd digit counts

  • Last Updated : 29 Sep, 2021

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




// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to construct lexicographically
// smallest numeric string having an odd
// count of each characters
string genString(int N)
{
    // Stores the resultant string
    string ans = "";
  
    // If N is even
    if (N % 2 == 0) {
        ans = string(N - 1, '1') + '2';
    }
  
    // Otherwise
    else {
        ans = string(N, '1');
    }
  
    return ans;
}
  
// Driver code
int main()
{
    int N = 5;
    cout << genString(N);
  
    return 0;
}
Output:
11111

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :