Sort Integers by The Power Value — LeetCode 1387 Python Solution

MediumMemoizationDynamic ProgrammingSorting
Problem
#1387
Pattern
Sorting
Reading time
3 min

The problem

The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps: if x is even then x = x / 2 if x is odd then x = 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.

Example

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)

Python solution

Python
@cache
def f(x: int) -> int:
    ans = 0
    while x != 1:
        if x % 2 == 0:
            x //= 2
        else:
            x = 3 * x + 1
        ans += 1
    return ans


class Solution:
    def getKth(self, lo: int, hi: int, k: int) -> int:
        return sorted(range(lo, hi + 1), key=f)[k - 1]

Complexity

MeasureComplexity
TimeO(n \times \log n \times M)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1387. Sort Integers by The Power Value is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1387. Sort Integers by The Power Value?
LeetCode 1387. Sort Integers by The Power Value is rated Medium on LeetCode.
What is the time complexity of LeetCode 1387. Sort Integers by The Power Value?
The Python solution on this page runs in O(n \times \log n \times M).
What is the space complexity of LeetCode 1387. Sort Integers by The Power Value?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1387. Sort Integers by The Power Value cover?
LeetCode 1387. Sort Integers by The Power Value is tagged Memoization, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview