Problem 140476 · hard · Phase 01 Prerequisites & Setup

Sort, Subtract, Repeat

loops · digits · lists · cycle detection

Fix a digit count width. Every value is written with exactly width digits, padding with leading zeros (with width = 4, the value 378 is written 0378). One step turns a value x into big - small, where big is the number formed by the digits of x in descending order and small is the number formed by the same digits in ascending order (leading zeros allowed).

Starting from x0 = n, keep stepping: x1, x2, ... Because there are only finitely many values, some value must eventually come back. Let k be the first index such that xk equals an earlier value xj. Write sort_subtract(n, width) that returns the list [j, k - j]: how many steps it takes before the repeating loop is entered, and how long that loop is.

Examples

Input:  n = 3524, width = 4
Output: [3, 1]
Explanation: 3524 -> 3087 -> 8352 -> 6174 -> 6174. x4 equals x3.

Input:  n = 53, width = 2
Output: [2, 5]
Explanation: 53 -> 18 -> 63 -> 27 -> 45 -> 09 -> 81 -> 63. x7 equals x2.

Input:  n = 2222, width = 4
Output: [1, 1]
Explanation: 2222 -> 0000 -> 0000.

Constraints

  • 1 <= width <= 9
  • 0 <= n < 10**width

Goals

  • Build the largest and smallest arrangement of a number's digits
  • Keep a history list to notice when a process repeats
  • Measure both the lead-in and the length of a repeating loop
Starting Python…