Sort by Digit Product
MediumPractice library · +20 XPsortingcustom sortingsorting then scanning
Given N integers, sort them in non-decreasing order based on the product of their digits. If two numbers have the same digit product, the one that appears earlier in the original input should come first in the sorted output. Print the sorted sequence.
Input
The first line contains an integer N. The second line contains N space-separated integers.
Output
Print N space-separated integers, the sorted sequence.
Constraints
1 <= N <= 200000. Each integer is between 0 and 10^9. The integers are distinct.
Time limit 2 s (native code; slower languages get more)Memory 256 MB14 hidden tests
Example 1
Input
5 123 40 24 111 5
Output
40 111 5 123 24
Products: 1*2*3=6, 4*0=0, 2*4=8, 1*1*1=1, 5=5. Sorted by product: 40(0), 111(1), 5(5), 123(6), 24(8).
Example 2
Input
4 9 18 81 72
Output
18 81 9 72
Products: 9, 1*8=8, 8*1=8, 7*2=14. Sorted by product: 18(8), 81(8), 9(9), 72(14). 18 comes before 81 due to original order.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 123 40 24 111 5
Example 2 input
4 9 18 81 72