VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-number-ascending-order-contains-1-2-3-digits/

⇱ Print number in ascending order which contains 1, 2 and 3 in their digits. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print number in ascending order which contains 1, 2 and 3 in their digits.

Last Updated : 9 Nov, 2022

Given an array of numbers, the task is to print those numbers in ascending order separated by commas that have 1, 2, and 3 in their digits. If no number containing digits 1, 2, and 3 is present then print -1.

Examples:

Input : numbers[] = {123, 1232, 456, 234, 32145}
Output : 123, 1232, 32145

Input : numbers[] = {9821, 627183, 12, 1234}
Output : 1234, 627183

Input : numbers[] = {12, 232, 456, 234}
Output : -1

First finding all the number in form of array which contains 1, 2 & 3 then sort the number according to 1, 2 and 3 and then print it.

Follow the steps below to implement the above idea:

  • Iterate over the given array numbers[] and check if the number is valid or not.
    • For checking the validity of a number:
      • Take three variables countOnes, countTwo, countThee, and initialize to 0.
      • Increment the value for the above variables accordingly, if found.
    • Finally, Check if all the above three variables contain some value, then return true.
    • Otherwise, return false.
  • If the number is valid then push the number into array oneTwoThree[].
  • Sort the array and print the result.

Below is the implementation of the above approach:


Output
123, 1232, 32145

Time Complexity: O(N log(N)), where N is the length of the given number.
Auxiliary Space: O(N) 

Please suggest if someone has a better solution that is more efficient in terms of space and time.

Comment
Article Tags:
Article Tags: