Sort Integers by The Power Value - 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. 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 kth 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.

Input & Output

Example 1 — Basic Case
$ Input: lo = 7, hi = 11, k = 4
Output: 7
💡 Note: Powers: 7→16, 8→3, 9→19, 10→6, 11→14. Sorted by power: [8,10,11,7,9]. 4th element is 7.
Example 2 — Small Range
$ Input: lo = 10, hi = 20, k = 5
Output: 13
💡 Note: Calculate power for each number 10-20, sort by power values, return 5th element.
Example 3 — Single Element
$ Input: lo = 1, hi = 1, k = 1
Output: 1
💡 Note: Only one number in range [1,1], so return 1 (power of 1 is 0).

Constraints

  • 1 ≤ lo ≤ hi ≤ 1000
  • 1 ≤ k ≤ hi - lo + 1

Visualization

Tap to expand
Sort Integers by Power Value: Range [7,11], k=4Input Range [7, 8, 9, 10, 11]k = 4 (find 4th element)Power Calculations (Collatz Conjecture)7→22→11→34→17→52→26→13→40→20→10→5→16→8→4→2→1 (16 steps)8→4→2→1 (3 steps), 10→5→16→8→4→2→1 (6 steps)Sorted by Power: [8(3), 10(6), 11(14), 7(16), 9(19)]4th Element: 7
Understanding the Visualization
1
Input Range
Numbers in range [lo, hi] with target position k
2
Calculate Powers
Apply Collatz conjecture rules to find power of each number
3
Sort & Select
Sort by power values, return kth element
Key Takeaway
🎯 Key Insight: Use memoization to cache power calculations since transformation sequences often overlap
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen