Given an array arr[] of integer elements, the task is to arrange them in such a way that these numbers form the smallest possible number.
For example, if the given array is {5, 6, 2, 9, 21, 1} then the arrangement will be 1212569.
Examples:
Input: arr[] = {5, 6, 2, 9, 21, 1}
Output: 1212569Input: arr[] = {1, 2, 1, 12, 33, 211, 50}
Output: 111221123350
Approach: If all the given numbers are of at most one digit then the simple approach is sorting all numbers in ascending order. But if there is some number which have more than a single-digit then this approach will not work.
Therefore, we have to sort the array by comparing any two elements in the following way:
If the elements are A and B, then compare (A + B) with (B + A) where + represents concatenation.
Below is the implementation of the above approach:
// C++ implementation of the approach #include <algorithm> #include <iostream> using namespace std;
// Utility function to print // the contents of an array void printArr( int arr[], int n)
{ for ( int i = 0; i < n; i++)
cout << arr[i];
} // A comparison function that return true // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return true if // we pass 12 and 24 as arguments. // This function will be used by sort() function bool compare( int num1, int num2)
{ // to_string function is predefined function
// to convert a number in string
// Convert first number to string format
string A = to_string(num1);
// Convert second number to string format
string B = to_string(num2);
// Check if 'AB' is smaller or 'BA'
// and return bool value since
// comparison operator '<=' returns
// true or false
return (A + B) <= (B + A);
} // Function to print the arrangement // with the smallest value void printSmallest( int N, int arr[])
{ // If we pass the name of the comparison
// function it will sort the array
// according to the compare function
sort(arr, arr + N, compare);
// Print the sorted array
printArr(arr, N);
} // Driver code int main()
{ int arr[] = { 5, 6, 2, 9, 21, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
printSmallest(N, arr);
return 0;
} |
// Java implementation of the approach class GFG
{ // Utility function to print
// the contents of an array
public static void printArr( int [] arr, int n)
{
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i]);
}
// A comparison function that return negative
// if 'AB' is smaller than 'BA' when
// we concatenate two numbers 'A' and 'B'
// For example, it will return negative value if
// we pass 12 and 24 as arguments.
// This function will be used during sort
public static int compare( int num1, int num2)
{
// toString function is predefined function
// to convert a number in string
// Convert first number to string format
String A = Integer.toString(num1);
// Convert second number to string format
String B = Integer.toString(num2);
// Check if 'AB' is smaller or 'BA'
// and return integer value
return (A+B).compareTo(B+A);
}
// Function to print the arrangement
// with the smallest value
public static void printSmallest( int N, int [] arr)
{
// Sort using compare function which
// is defined above
for ( int i = 0 ; i < N; i++)
{
for ( int j = i + 1 ; j < N; j++)
{
if (compare(arr[i], arr[j]) > 0 )
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Print the sorted array
printArr(arr, N);
}
// Driver code
public static void main(String[] args)
{
int [] arr = { 5 , 6 , 2 , 9 , 21 , 1 };
int N = arr.length;
printSmallest(N, arr);
}
} // This code is contributed by // sanjeev2552 |
# Python3 implementation of the approach # Utility function to print # the contents of an array def printArr(arr, n):
for i in range ( 0 , n):
print (arr[i], end = "")
# A comparison function that return true # if 'AB' is smaller than 'BA' when # we concatenate two numbers 'A' and 'B' # For example, it will return true if # we pass 12 and 24 as arguments. # This function will be used by sort() function def compare(num1, num2):
# Convert first number to string format
A = str (num1)
# Convert second number to string format
B = str (num2)
# Check if 'AB' is smaller or 'BA'
# and return bool value since
# comparison operator '<=' returns
# true or false
return int (A + B) < = int (B + A)
def sort(arr):
for i in range ( len (arr)):
for j in range (i + 1 , len (arr)):
if compare(arr[i], arr[j]) = = False :
arr[i], arr[j] = arr[j], arr[i]
# Function to print the arrangement # with the smallest value def printSmallest(N, arr):
# If we pass the name of the comparison
# function it will sort the array
# according to the compare function
sort(arr)
# Print the sorted array
printArr(arr, N)
# Driver code if __name__ = = "__main__" :
arr = [ 5 , 6 , 2 , 9 , 21 , 1 ]
N = len (arr)
printSmallest(N, arr)
# This code is contributed by Rituraj Jain |
// C# implementation for above approach using System;
class GFG
{ // Utility function to print
// the contents of an array
public static void printArr( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
Console.Write(arr[i]);
}
// A comparison function that return negative
// if 'AB' is smaller than 'BA' when
// we concatenate two numbers 'A' and 'B'
// For example, it will return negative value if
// we pass 12 and 24 as arguments.
// This function will be used during sort
public static int compare( int num1, int num2)
{
// toString function is predefined function
// to convert a number in string
// Convert first number to string format
String A = num1.ToString();
// Convert second number to string format
String B = num2.ToString();
// Check if 'AB' is smaller or 'BA'
// and return integer value
return (A+B).CompareTo(B+A);
}
// Function to print the arrangement
// with the smallest value
public static void printSmallest( int N, int [] arr)
{
// Sort using compare function which
// is defined above
for ( int i = 0; i < N; i++)
{
for ( int j = i + 1; j < N; j++)
{
if (compare(arr[i], arr[j]) > 0)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Print the sorted array
printArr(arr, N);
}
// Driver code
public static void Main(String[] args)
{
int [] arr = { 5, 6, 2, 9, 21, 1 };
int N = arr.Length;
printSmallest(N, arr);
}
} // This code is contributed by Rajput-Ji |
<script> // Javascript implementation of the approach
// Utility function to print
// the contents of an array
function printArr(arr,n)
{
for (let i = 0; i < n; i++)
document.write(arr[i]);
}
// A comparison function that return true
// if 'AB' is smaller than 'BA' when
// we concatenate two numbers 'A' and 'B'
// For example, it will return true if
// we pass 12 and 24 as arguments.
// This function will be used by sort() function
function compare(num1,num2)
{
// to_string function is predefined function
// to convert a number in string
// Convert first number to string format
let A = num1.toString();
// Convert second number to string format
let B = num2.toString();
// Check if 'AB' is smaller or 'BA'
// and return bool value since
// comparison operator '<=' returns
// true or false
return (A + B).localeCompare(B + A);
}
// Function to print the arrangement
// with the smallest value
function printSmallest(N,arr)
{
// If we pass the name of the comparison
// function it will sort the array
// according to the compare function
// Sort using compare function which
// is defined above
for (let i = 0; i < N; i++)
{
for (let j = i + 1; j < N; j++)
{
if (compare(arr[i], arr[j]) > 0)
{
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Print the sorted array
printArr(arr,N);
}
// Driver code
let arr = [ 5, 6, 2, 9, 21, 1 ];
let N = arr.length;
printSmallest(N,arr);
</script> |
<?php // PHP implementation of the approach // Utility function to print // the contents of an array function printArr( $arr , $n )
{ for ( $i = 0; $i < $n ; $i ++)
echo $arr [ $i ];
} // A comparison function that return true // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return true if // we pass 12 and 24 as arguments. // This function will be used by sort() function function compare( $num1 , $num2 )
{ // to_string function is predefined function
// to convert a number in string
// Convert first number to string format
$A = (string) $num1 ;
// Convert second number to string format
$B = (string) $num2 ;
// Check if 'AB' is smaller or 'BA'
// and return bool value since
// comparison operator '<=' returns
// true or false
if ((int)( $A . $B ) <= (int)( $B . $A ))
{
return true;
}
else
return false;
} function sort_arr( $arr )
{ for ( $i = 0; $i < count ( $arr ) ; $i ++)
{
for ( $j = $i + 1; $j < count ( $arr ) ; $j ++)
{
if (compare( $arr [ $i ], $arr [ $j ]) == false)
{
$temp = $arr [ $i ] ;
$arr [ $i ] = $arr [ $j ] ;
$arr [ $j ] = $temp ;
}
}
}
return $arr ;
}
// Function to print the arrangement // with the smallest value function printSmallest( $N , $arr )
{ // If we pass the name of the comparison
// function it will sort the array
// according to the compare function
$arr = sort_arr( $arr );
// Print the sorted array
printArr( $arr , $N );
} // Driver code
$arr = array (5, 6, 2, 9, 21, 1 );
$N = count ( $arr );
printSmallest( $N , $arr );
// This code is contributed by Ryuga
?> |
1212569
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Approach 2: Implementing a custom quicksort algorithm
Another way to solve the problem is to implement a custom quicksort algorithm that uses the same comparison function as in approach 1. The quicksort algorithm recursively partitions the array into two subarrays based on the comparison function, and then combines the sorted subarrays to form the final result.
#include <iostream> #include <vector> #include <string> using namespace std;
bool compare(string a, string b) {
return (a+b) < (b+a);
} int partition(vector<string>& arr, int low, int high) {
string pivot = arr[high];
int i = low - 1;
for ( int j = low; j <= high - 1; j++) {
if (compare(arr[j], pivot)) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[high]);
return i+1;
} void quicksort(vector<string>& arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
} string smallestNumber(vector< int >& nums) {
vector<string> numStrs;
for ( int num : nums) {
numStrs.push_back(to_string(num));
}
quicksort(numStrs, 0, numStrs.size()-1);
string result = "" ;
for (string numStr : numStrs) {
result += numStr;
}
return result;
} int main() {
vector< int > nums = { 5, 6, 2, 9, 21, 1 };
cout << smallestNumber(nums) << endl; // Output: 3033459
return 0;
} |
import java.util.Arrays;
public class SmallestNumber {
public static boolean compare(String a, String b) {
return (a + b).compareTo(b + a) < 0 ;
}
public static int partition(String[] arr, int low, int high) {
String pivot = arr[high];
int i = low - 1 ;
for ( int j = low; j <= high - 1 ; j++) {
if (compare(arr[j], pivot)) {
i++;
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
String temp = arr[i + 1 ];
arr[i + 1 ] = arr[high];
arr[high] = temp;
return i + 1 ;
}
public static void quicksort(String[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1 );
quicksort(arr, pi + 1 , high);
}
}
public static String smallestNumber( int [] nums) {
String[] numStrs = new String[nums.length];
for ( int i = 0 ; i < nums.length; i++) {
numStrs[i] = String.valueOf(nums[i]);
}
quicksort(numStrs, 0 , numStrs.length - 1 );
StringBuilder result = new StringBuilder();
for (String numStr : numStrs) {
result.append(numStr);
}
return result.toString();
}
public static void main(String[] args) {
int [] nums = { 5 , 6 , 2 , 9 , 21 , 1 };
System.out.println(smallestNumber(nums)); // Output: 3033459
}
} |
def compare(a, b):
return (a + b) < (b + a)
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range (low, high):
if compare(arr[j], pivot):
i + = 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1 ], arr[high] = arr[high], arr[i + 1 ]
return i + 1
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi - 1 )
quicksort(arr, pi + 1 , high)
def smallestNumber(nums):
numStrs = [ str (num) for num in nums]
quicksort(numStrs, 0 , len (numStrs) - 1 )
result = "".join(numStrs)
return result
if __name__ = = "__main__" :
nums = [ 5 , 6 , 2 , 9 , 21 , 1 ]
print (smallestNumber(nums)) # Output: 3033459
|
using System;
using System.Collections.Generic;
class Program {
// Function to compare two strings based on their
// concatenated values
static bool Compare( string a, string b)
{
return (a + b).CompareTo(b + a) < 0;
}
// Function to partition the array for quicksort
static int Partition(List< string > arr, int low,
int high)
{
string pivot = arr[high];
int i = low - 1;
for ( int j = low; j <= high - 1; j++) {
if (Compare(arr[j], pivot)) {
i++;
Swap(arr, i, j);
}
}
Swap(arr, i + 1, high);
return i + 1;
}
// Function to perform quicksort on the array
static void QuickSort(List< string > arr, int low,
int high)
{
if (low < high) {
int pi = Partition(arr, low, high);
QuickSort(arr, low, pi - 1);
QuickSort(arr, pi + 1, high);
}
}
// Function to find the smallest number by concatenating
// array elements
static string SmallestNumber(List< int > nums)
{
List< string > numStrs = new List< string >();
foreach ( int num in nums)
{
numStrs.Add(num.ToString());
}
QuickSort(numStrs, 0, numStrs.Count - 1);
string result = "" ;
foreach ( string numStr in numStrs)
{
result += numStr;
}
return result;
}
// Function to swap two elements in a list
static void Swap(List< string > arr, int i, int j)
{
string temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Main function to test the SmallestNumber function
static void Main()
{
List< int > nums = new List< int >{ 5, 6, 2, 9, 21, 1 };
Console.WriteLine(
SmallestNumber(nums)); // Output: 3033459
}
} |
// Function to compare two strings for sorting function compare(a, b) {
return (a + b) < (b + a);
} // Function to perform partitioning for quicksort function partition(arr, low, high) {
const pivot = arr[high];
let i = low - 1;
// Iterate through the array
for (let j = low; j <= high - 1; j++) {
// Check if arr[j] is less than pivot
if (compare(arr[j], pivot)) {
i++;
// Swap arr[i] and arr[j]
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
// Swap arr[i+1] and arr[high]
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
} // Function to implement quicksort algorithm function quicksort(arr, low, high) {
if (low < high) {
const pi = partition(arr, low, high);
// Recursively sort elements before and after partition
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
} // Function to find the smallest number by sorting array of integers function smallestNumber(nums) {
// Convert integers to strings for sorting
const numStrs = nums.map(num => String(num));
// Sort the strings using custom comparison function
quicksort(numStrs, 0, numStrs.length - 1);
// Concatenate sorted strings to form the result
const result = numStrs.join( '' );
return result;
} // Test case const nums = [5, 6, 2, 9, 21, 1]; console.log(smallestNumber(nums)); // Output: 3033459
|
1212569
Time Complexity: O(nlogn)
Auxiliary Space: O(n)