Sort Integers by The Power Value Problem
Description
LeetCode Problem 1387.
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:
- if
xis even thenx = x / 2 - if
xis odd thenx = 3 * x + 1
For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).
Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.
Return the k^th integer in the range [lo, hi] sorted by the power value.
Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.
Example 1:
Input: lo = 12, hi = 15, k = 2
Output: 13
Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
The power of 13 is 9
The power of 14 is 17
The power of 15 is 17
The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.
Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.
Example 2:
Input: lo = 7, hi = 11, k = 4
Output: 7
Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].
The interval sorted by power is [8, 10, 11, 7, 9].
The fourth number in the sorted array is 7.
Constraints:
1 <= lo <= hi <= 10001 <= k <= hi - lo + 1
Solution
Approach: Compute Every Power, Then Sort
The range holds at most 1000 integers, and for x <= 1000 the sequence reaches 1 in fewer than 200 steps, so we can simply simulate it for every number.
- Write
power(x): applyx / 2or3x + 1untilx == 1, counting the steps. - Sort the numbers
lo..hiby the key(power(x), x): by power first, and by the value itself when powers are equal. - Return the element at index
k - 1.
The tie-break matters: in Example 1, 12 and 13 both have power 9, and 12 comes first because it is smaller. Compute each power once before sorting instead of inside the comparator, so it is not recomputed on every comparison. If the range were larger, caching the power of every value met on the way (memoization) would avoid walking the same chains again.
Complexity: O(N * S + N log N) time, where N = hi - lo + 1 and S is the largest number of steps, and O(N) extra space.
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
def power(x: int) -> int:
steps = 0
while x != 1:
x = x // 2 if x % 2 == 0 else 3 * x + 1
steps += 1
return steps
# Sort by power, ties by the value itself.
return sorted(range(lo, hi + 1), key=lambda x: (power(x), x))[k - 1]