Lexicographically Smallest Numeric String Having Odd Digit Counts



This article offers a thorough method for creating a lexicographically short N?length number string, where each digit must have an odd count. We offer an in?depth explanation of the problem statement, suggest a successful algorithmic strategy, and put it into practice using C++. The efficiency of the solution is revealed by the complexity analysis, and the accuracy and efficacy of the method are illustrated by an explanation using a test scenario

Problem Statement

Given a positive integer N, the task is to generate the smallest numeric string of size N which follows the lexicographical order, where each digit in the string must have an odd count. Let's delve into examples to get a better understanding

Example 1

Let the Input taken be N = 5, 
Output is equal to 11111

Comment The smallest string following lexicographical order is made up of the digit 1, which has an odd count.

Example 2

Let the Input taken be N = 6, 
Output is equal to 111112

Comment The lexicographically smallest string is made up of the digits 1 and 2, both of which have an odd count.

Approach/Algorithm

  • Define the 'generateSmallestNumericString' function that takes an integer N(length of the resulting string) as a parameter and returns a string(of length equals N).

  • Inside the function: Declare a string variable named resultString which is taken as empty so that generated string can be stored later.

  • Using the modulo operator (%), check whether N is even or odd:

    • If it is even ? Assign resultString with (N ? 1) occurrences of the digit '1' concatenated with the digit '2'. This guarantees that the resulting string meets the odd count requirement for each number by having (N?1) ones and a single digit 2 i.e. N?1 will give odd as N is even and the count of 2 being 1 is also odd, hence the condition is met.

    • If N is odd ? Assign the result with N occurrences of the digit '1'. This ensures that all digits in the resulting string are '1', satisfying the odd count requirement for each digit.

  • Finally, return the resulting smallest string.

Example

Now, let us implement the above approach in different programming languages: C, C++, Java, and Python

#include <stdio.h>
// Function to generate the lexicographically smallest numeric string with odd digit counts
void generateSmallestNumericString(int N, char resultString[]){
   // Check if N is even using the modulo operator (%)
   if (N % 2 == 0) {
      // If N is even: Assign the result with N - 1 occurrences of the digit '1'
      // and then concatenate it with the digit '2'.
      // This ensures that there are (N-1) ones and a single digit 2 in the resulting string,
      // satisfying the odd count requirement for each digit
      for (int i = 0; i < N - 1; i++) {
         resultString[i] = '1';
      }
      resultString[N - 1] = '2';
      resultString[N] = '\0';  // Null-terminate the string
   } else {
      // If N is odd: Assign result with N occurrences of the digit '1'
      // This ensures that all digits in the resulting string are '1',
      // satisfying the odd count requirement for each digit
      for (int i = 0; i < N; i++) {
         resultString[i] = '1';
      }
      resultString[N] = '\0';  // Null-terminate the string
   }
}
int main(){
   int N = 6;  // Desired size of the string
   char smallestString[N + 1];  // +1 for the null terminator

   // Call the function to generate the lexicographically smallest numeric string with odd digit counts
   generateSmallestNumericString(N, smallestString);

   // Print the result
   printf("Smallest String with length N = %d is: %s\n", N, smallestString);

   return 0;
}

Output

Smallest String with length N = 6 is: 111112
#include <iostream>
#include <string>
using namespace std;
string generateSmallestNumericString(int N) {
   string resultString = ""; // Variable to store the generated string
   // Check if N is even using the modulo operator (%)
   if (N % 2 == 0) {
      // If N is even: Assign the result with N - 1 occurrences of the digit '1' and then concatenate it with the digit '2'.
      // This ensures that there are (N-1) ones and a single digit 2 in the resulting string,
      // satisfying the odd count requirement for each digit
      resultString.append(N - 1, '1');
      resultString += '2';
   } else {
      // If N is odd: Assign result with N occurrences of the digit '1'
      // This ensures that all digits in the resulting string are '1,
      // satisfying the odd count requirement for each digit
      resultString.append(N, '1');
   }
   return resultString; // Return the generated string
}
int main() {
   int N = 6; // Desired size of the string
   string smallestString = generateSmallestNumericString(N);
   // Call the function to generate the lexicographically smallest numeric string with odd digit counts
   cout <<"Smallest String with length N= "<<N<<" is: "<<smallestString << endl;
   return 0;
}	  

Output

Smallest String with length N= 6 is: 111112
public class Main {
   public static String generateSmallestNumericString(int N) {
      StringBuilder resultString = new StringBuilder();  // Using StringBuilder for string concatenation
      // Check if N is even using the modulo operator (%)
      if (N % 2 == 0) {
         // If N is even: Assign the result with N - 1 occurrences of the digit '1'
         // and then concatenate it with the digit '2'.
         // This ensures that there are (N-1) ones and a single digit 2 in the resulting string,
         // satisfying the odd count requirement for each digit
         resultString.append("1".repeat(Math.max(0, N - 1)));
         resultString.append('2');
      } else {
         // If N is odd: Assign result with N occurrences of the digit '1'
         // This ensures that all digits in the resulting string are '1',
         // satisfying the odd count requirement for each digit
         resultString.append("1".repeat(Math.max(0, N)));
      }
      return resultString.toString(); // Return the generated string
   }
   public static void main(String[] args) {
      int N = 6; // Desired size of the string
      String smallestString = generateSmallestNumericString(N);
      // Call the function to generate the lexicographically smallest numeric string with odd digit counts
      System.out.println("Smallest String with length N = " + N + " is: " + smallestString);
   }
}

Output

Smallest String with length N = 6 is: 111112
def generate_smallest_numeric_string(N):
   # Variable to store the generated string
   result_string = ""
   # Check if N is even using the modulo operator (%)
   if N % 2 == 0:
      # If N is even: Assign the result with N - 1 occurrences of the digit '1'
      # and then concatenate it with the digit '2'.
      # This ensures that there are (N-1) ones and a single digit 2 in the resulting string,
      # satisfying the odd count requirement for each digit
      result_string += '1' * (N - 1)
      result_string += '2'
   else:
      # If N is odd: Assign result with N occurrences of the digit '1'
      # This ensures that all digits in the resulting string are '1',
      # satisfying the odd count requirement for each digit
      result_string += '1' * N
   return result_string
def main():
   # Desired size of the string
   N = 6
   # Call the function to generate the lexicographically smallest numeric string with odd digit counts
   smallest_string = generate_smallest_numeric_string(N)
   print(f"Smallest String with length N = {N} is: {smallest_string}")

if __name__ == "__main__":
   main()

Output

Smallest String with length N = 6 is: 111112

Complexity Analysis

Time Complexity The algorithm takes O(N) i.e. linear time, where N is the required string's length. When the length of the result string exceeds N, the loop stops iterating over the digits.

Space Complexity Since the length of the result string increases with N, the space complexity is also O(N)

Explanation Using a Test Case

Test case → N=6

The 'generateSmallestNumericString' function in the provided code accepts an integer N as an input and outputs a string that represents the lexicographically shortest N?length numeric string with an odd count of each digit.

We call the 'generateSmallestNumericString' method and pass N as the argument in the main function after setting N to 6. The variable smallestString will contain the returned string

In the generateSmallestNumericString function

  • Since N is even, so, (6 % 2 == 0), therefore the 'if' block will get executed.

  • The line resultString = string(N ? 1, '1') + '2'; creates a string with (N ? 1) occurrences of the digit '1' using the string constructor and then appends the digit '2' using the concatenation operator '+'.

  • Therefore, the resulting string is "111112", where the digit '1' has an odd count of 5 and the digit '2' has an odd count of 1, satisfying the conditions of the problem statement.

Hence, for the given test case i.e. N = 6, the lexicographically smallest numeric string with an odd count of each digit is "111112".

Conclusion

In this article, we covered a method for generating the lexicographically shortest N-character numeric string with an odd number of digits in each character. We offered a detailed explanation and a C++ implementation. The algorithm solves the issue successfully, and its time complexity is linear in relation to N. We may produce the desired string for any positive integer N by using this method.

Updated on: 2024-01-23T10:09:28+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements