Ctrl K

Divide Down to Sorted Order

Medium
You are given an array of positive integers values. A proper divisor of x is a positive divisor strictly smaller than x (for 12 these are 1, 2, 3, 4 and 6; 1 has none). In one operation you pick any element and divide it by its largest proper divisor. For 1 and for primes the operation changes nothing. Return the smallest number of operations after which the array is non-decreasing, or -1 if that cannot be done.
Example 1
values=[12, 5, 9] → 1

The largest proper divisor of 12 is 6, and 12 / 6 = 2. One operation gives [2, 5, 9].

Example 2
values=[6, 4, 3] → 2

4 becomes 2, then 6 becomes 2: [2, 2, 3] after two operations.

Example 3
values=[5, 3] → -1

5 is prime, its largest proper divisor is 1 and dividing changes nothing, so the order cannot be fixed.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsChunks With a Common Divisor MediumShave Primes Into Order MediumEqual Window Sums on a Ring MediumShrink a List With Remainders MediumPrimes Below a Bound Medium
loading Python…
Input
values=[12, 5, 9]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.