Naive Approach: One easy way to solve this problem is use comparison-based sorting on all numbers, stored as strings. If the compared strings are of different length sort them on the basis of small length first. If the lengths are same, use compare function to find the first biggest non-matching character and deduce whether it belongs to first or second string and sort them whose first non-matching character’s ASCII value is smaller.
This way we will get final vector which has increasingly sorted strings on the basis of its numeral representation. The first string will be smallest and last string will be largest.
Time Complexity: O(N*M*log N)
O(N*log N) to sort the array
O(M) to compare two numbers digit by digit when their lengths are equal
Auxiliary Space: O(1)
Efficient Approach: To solve the problem efficiently follow the below idea:
This approach is similar to finding the biggest and smallest number in a numeral vector. The only difference is that there is need to check if the length of string as well since strings with big length will always form a bigger number than one with smaller length.
For Example: “3452” with length 4 will always be greater than “345” with length 3. Similar is the case for smallest string.
Follow the steps to solve the problem:
Initialize minLen to maximum possible number and maxLen to minimum number possible. Here minLen and maxLen represents length of smallest number and biggest number found till now.
Traverse all strings one by one with i.
Find the length of current string as numLen.
If minLen > numLen assign minLen to numLen and smallest number as numbers[i]. Similarly If maxLen < numLen assign maxLen to numLen and biggest number as numbers[i].
If minLen == numLen and maxLen == numLen then compare smallest number and biggest number found till now with the numbers[i]. The number with first greater non-matching character will be bigger and other will be smaller.
Return the pair of smallest and biggest number as the final answer.
Below is the implementation of the above mentioned approach:
Please Login to comment...