Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Find smallest number formed by inverting digits of given number N
Next article icon

Smallest number by rearranging digits of a given number

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of a given number. 

Examples: 

Input: n = 846903
Output: 304689

Input: n = 55010
Output: 10055

Input: n = -40505
Output: -55400

Steps to find the smallest number.  

  1. Count the frequency of each digit in the number.
  2. If it is a non-negative number then
    1. Place the smallest digit (except 0) at the left most of the required number. 
      and decrement the frequency of that digit by 1.
    2. Place all remaining digits in ascending order from left to right.
  3. Else if it is a negative number then
    1. Place the largest digit at the left most of the required number. and decrement the frequency of that digit by 1.
    2. Place all remaining digits in descending order from right to left.

This solution is based on counting sort. 

C++
// C++ program for finding smallest number // from digits of given number #include<iostream> using namespace std;  // function to find the smallest number int smallest(int num) {     // initialize frequency of each digit to Zero     int freq[10] = {0};            // Checking Number is positive or Negative     bool is_pos = (num>0);          // Getting the absolute value of num     num = abs(num);        // count frequency of each digit in the number     while (num)     {         int d = num % 10; // extract last digit         freq[d]++; // increment counting         num = num / 10; //remove last digit     }          int result = 0;          // If it is positive Number then it should be smallest       if(is_pos)      {       // Set the Leftmost digit to minimum except 0       for (int i = 1 ; i <= 9 ; i++)       {           if (freq[i])           {               result = i;               freq[i]--;               break;           }       }        // arrange all remaining digits       // in ascending order       for (int i = 0 ; i <= 9 ; i++)           while (freq[i]--)               result = result * 10 + i;     }     else  // If negative then number should be Largest     {       // Set the Leftmost digit to maximum        for (int i = 9 ; i >= 1 ; i--)       {          if (freq[i])          {             result = i;             freq[i]--;             break;          }       }              // arrange all remaining digits       // in descending order       for (int i = 9 ; i >=0 ; i--)          while (freq[i]--)             result = result * 10 + i;        // Negative number should be returned here       result = -result;      }     return result; }  // Driver Program int main() {     int num = 570107;     cout << smallest(num) << endl;        int num2 = -691005;     cout << smallest(num2);     return 0; } 
Java
import java.lang.Math;  // Java program for finding smallest number // from digits of given number public class GFG {      // function to find the smallest number     static int smallest(int num)     {         // initialize frequency of each digit to Zero         int[] freq = new int[10];                  // Checking Number is positive or Negative         boolean is_pos = (num>0);                  // Getting the absolute value of num         num = Math.abs(num);                // count frequency of each digit in the number         while (num > 0)         {             int d = num % 10; // extract last digit             freq[d]++; // increment counting             num = num / 10; //remove last digit         }              int result = 0;              // If it is positive Number then it should be smallest           if(is_pos)          {             // Set the LEFTMOST digit to minimum expect 0             for (int i = 1 ; i <= 9 ; i++)             {                     if (freq[i] != 0)                 {                         result = i;                         freq[i]--;                     break;                 }             }                   // arrange all remaining digits             // in ascending order             for (int i = 0 ; i <= 9 ; i++)                 while (freq[i]-- != 0)                     result = result * 10 + i;          }           else  // If negative then number should be Largest         {           // Set the Rightmost digit to maximum            for (int i = 9 ; i >= 1 ; i--)           {              if (freq[i] !=0)              {                 result = i;                 freq[i]--;                 break;              }           }            // arrange all remaining digits           // in descending order           for (int i = 9 ; i >=0 ; i--)              while (freq[i]-- != 0)                 result = result * 10 + i;            // Negative number should be returned here           result = -result;          }         return result;     }           // Driver Program     public static void main(String args[])     {         int num = 570107;         System.out.println(smallest(num));                  int num2 = -691005;         System.out.println(smallest(num2));     } } // This code is contributed by Sumit Ghosh 
Python
# Function to find the smallest number def smallest(lst):          # Here i is index and n is the number of the list     for i,n in enumerate(lst):                   # Checking for the first non-zero digit in the sorted list         if n != '0':                           # Remove and store the digit from the lst             tmp = lst.pop(i)             break          # Place the first non-zero digit at the starting     # and return the final number     return str(tmp) + ''.join(lst)    # Driver program if __name__ == '__main__':          # Converting the given numbers into string to form a list     lst = list(str(570107))     lst.sort()          # Calling the function using the above list     print (smallest(lst))      # This code is contributed by Mahendra Yadav 
C#
// C# program for finding smallest // number from digits of given  // number using System;  public class GFG {      // function to find the smallest     // number     static int smallest(int num)     {                  // initialize frequency of          // each digit to Zero         int[] freq = new int[10];              // count frequency of each          // digit in the number         while (num > 0)         {                          // extract last digit             int d = num % 10;                          // increment counting             freq[d]++;                          //remove last digit             num = num / 10;         }              // Set the LEFTMOST digit to          // minimum expect 0         int result = 0;         for (int i = 1 ; i <= 9 ; i++)         {             if (freq[i] != 0)             {                 result = i;                 freq[i]--;                 break;             }         }              // arrange all remaining digits         // in ascending order         for (int i = 0 ; i <= 9 ; i++)             while (freq[i]-- != 0)                 result = result * 10 + i;              return result;     }          // Driver Program     public static void Main()     {         int num = 570107;         Console.WriteLine(smallest(num));     } }  // This code is contributed by anuj_67. 
JavaScript
<script>  // Javascript program for finding smallest number  // from digits of given number   // function to find the smallest number  function smallest(num)  {      // initialize frequency of each digit to Zero      var freq = Array(10).fill(0);      // count frequency of each digit in the number      while (num)      {          var d = num % 10; // extract last digit          freq[d]++; // increment counting          num = parseInt(num / 10); //remove last digit      }       // Set the LEFTMOST digit to minimum expect 0      var result = 0;      for (var i = 1 ; i <= 9 ; i++)      {          if (freq[i])          {              result = i;              freq[i]--;              break;          }      }       // arrange all remaining digits      // in ascending order      for (var i = 0 ; i <= 9 ; i++)          while (freq[i]--)              result = result * 10 + i;       return result;  }   // Driver Program  var num = 570107;  document.write(smallest(num));   // This code is contributed by rutvik_56. </script> 
PHP
<?php // PHP program for finding smallest  // number from digits of given number  // function to find the smallest number function smallest($num) {     // initialize frequency of      // each digit to Zero     $freq = array_fill(0, 10, 0);      // count frequency of each      // digit in the number     while ($num)     {         $d = $num % 10; // extract last digit         $freq[$d]++; // increment counting         $num = (int)($num / 10); // remove last digit     }      // Set the LEFTMOST digit     // to minimum expect 0     $result = 0;     for ($i = 1 ; $i <= 9 ; $i++)     {         if ($freq[$i])         {             $result = $i;             $freq[$i]--;             break;         }     }      // arrange all remaining digits     // in ascending order     for ($i = 0 ; $i <= 9 ; $i++)         while ($freq[$i] > 0)         {             $result = $result * 10 + $i;             $freq[$i] -= 1;         }      return $result; }  // Driver Code $num = 570107; echo smallest($num);  // This code is contributed by mits ?> 

Output
100577 -965100

Time complexity: O(n), where n is the number of digits in the given number.

Space complexity: O(1), as only a constant amount of memory is used for the freq array.


Another Approach:Find smallest permutation of given number
 



Next Article
Find smallest number formed by inverting digits of given number N

A

Ajay Kumar Agrahari(aJy aGr)
Improve
Article Tags :
  • DSA
  • Mathematical
  • GE
  • number-digits
Practice Tags :
  • GE
  • Mathematical

Similar Reads

  • Largest number by rearranging digits of a given positive or negative number
    Given an integer N(positive or negative), the task is to find the maximum number that can be formed using all of the digits of this number. Examples: Input: -38290367Output: -20336789Explanation: As there is need to use all the digits, 0 cannot be the first digit because it becomes redundant at firs
    7 min read
  • Rearrange digits of a number to remove any subsequence of another given number
    Given two numeric strings N and K (K ? N), where digits of K are in non-decreasing order, the task is to rearrange digits of N such that K does not appear as a subsequence in N. If it is not possible to obtain such a permutation, print "-1". Otherwise print any such valid permutation of N. Examples:
    8 min read
  • Remove recurring digits in a given number
    Given a number as string, remove recurring digits from the given string. The changes must be made in-place. Expected time complexity O(n) and auxiliary space O(1).Examples: Input: num[] = "1299888833" Output: num[] = "12983" Input: num[] = "1299888833222" Output: num[] = "129832" We strongly recomme
    7 min read
  • Find smallest number formed by inverting digits of given number N
    Given an integer N, the task is to form a minimum possible positive number (>0) by inverting some digits of N. Inverting for a digit T is defined as subtracting it from 9 that is 9 - T. Note: The final number should not start from zero. Examples: Input:N = 4545Output: 4444Explanation:The minimum
    9 min read
  • Smallest n digit number divisible by given three numbers
    Given x, y, z and n, find smallest n digit number which is divisible by x, y and z. Examples: Input : x = 2, y = 3, z = 5 n = 4Output : 1020Input : x = 3, y = 5, z = 7 n = 2Output : Not possibleRecommended PracticeMighty DivisorTry It!Method: Brute-forceThe brute-force approach to solve this problem
    15+ min read
  • M-th smallest number having k number of set bits.
    Given two non-negative integers m and k. The problem is to find the m-th smallest number having k number of set bits.Constraints: 1 <= m, k.Examples: Input : m = 4, k = 2 Output : 9 (9)10 = (1001)2, it is the 4th smallest number having 2 set bits. Input : m = 6, k = 4 Output : 39 Approach: Follow
    6 min read
  • Find second smallest number from sum of digits and number of digits
    Given the sum of digits as S and the number of digits as D, the task is to find the second smallest number Examples: Input: S = 9, D = 2Output: 27Explanation: 18 is the smallest number possible with sum = 9 and total digits = 2, Whereas the second smallest is 27. Input: S = 16, D = 3Output: 178Expla
    8 min read
  • Smallest N digit number divisible by N
    Given a positive integers N, the task is to find the smallest N digit number divisible by N. Examples: Input: N = 2 Output: 10 Explanation: 10 is the smallest 2-digit number which is divisible by 2. Input: N = 3 Output: 102 Explanation: 102 is the smallest 3-digit number which is divisible by 3. Nai
    6 min read
  • Minimum number using set bits of a given number
    Given an unsigned number, find the minimum number that could be formed by using the bits of the given unsigned number. Examples : Input : 6 Output : 3 Binary representation of 6 is 0000....0110. Smallest number with same number of set bits 0000....0011. Input : 11 Output : 7 Simple Approach: 1. Find
    4 min read
  • Smallest multiple of a given number made of digits 0 and 9 only
    We are given an integer N. We need to write a program to find the least positive integer X made up of only digits 9's and 0's, such that, X is a multiple of N. Note: It is assumed that the value of X will not exceed 106. Examples: Input : N = 5 Output : X = 90 Explanation: 90 is the smallest number
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences