Merge Sorted Runs by Absolute Value and Extract k-th Element
Heaps, Sorting & SearchModel answerLast updated
Reorder a sorted array by absolute value in linear time, then find the k-th element in that order using logarithmic-time search without materializing the full result.
You're given an array nums containing integers in nondecreasing order.
Part 1: Rearrange the elements so they appear in increasing order of their absolute values. When multiple elements have the same absolute value, any relative ordering among them is acceptable. Your solution must run in O(N) time—strictly faster than a general O(N log N) sort.
Example: [-3, -2, 0, 1, 2, 5] becomes [0, 1, -2, 2, -3, 5] (or any valid reordering by absolute value).
Part 2: Given the same sorted array nums and a 1-indexed integer k, determine which element would appear at position k if the array were reordered by absolute value—but do it in O(log N) time and O(1) extra space. You cannot build the full reordered array; you must compute the answer directly.
Describe your algorithm clearly, analyze its time and space complexity, and explain any tie-breaking rules you assume.
Hints
Hint 1
The input is already sorted, so negative and non-negative values form two subsequences with predictable absolute-value orderings
Hint 2
Merging two sorted sequences takes linear time with two pointers; one sequence just needs to be traversed in reverse
Hint 3
Finding the k-th element across two sorted arrays can be solved with binary search by determining how many elements to take from each array
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Core Insight
Since nums is sorted in nondecreasing order, it naturally partitions into two segments:
- Negative values (if any): their absolute values decrease as you move right
- Non-negative values (if any): their absolute values increase as you move right
Let p be the index of the first non-negative element (found via binary search in O(log N)). The key observation: ordering by absolute value is equivalent to merging these two runs, where the negative run is traversed backward.
Part 1: Linear-Time Reordering
Use a two-pointer merge:
- Initialize
left = p - 1(pointing at the last negative) andright = p(pointing at the first non-negative) - Compare
|nums[left]|withnums[right] - Append whichever element has smaller absolute value to the result
- Advance the corresponding pointer
- When one pointer exhausts its range, append all remaining elements from the other
This is the standard merge procedure, just with one pointer moving leftward. Since we visit each element exactly once, the time complexity is O(N).
Tie-breaking convention: When -nums[left] == nums[right], I choose the negative element first to ensure consistency with Part 2. This matches the example output where -2 appears before 2.
Part 2: Logarithmic-Time k-th Element Query
We need to find the k-th element without building the merged array. Think of this as having two virtual sorted arrays:
- Array A: absolute values of negatives, in increasing order (accessed as
|nums[p-1-i]|for indexi) - Array B: non-negative values, already in increasing order (accessed as
nums[p+j]for indexj)
The problem reduces to: "find the k-th smallest element across two sorted arrays."
Binary search approach: We search for how many elements to take from array A (call this count_A). Then count_B = k - count_A elements come from B.
The search range is [max(0, k - len_B), min(k, len_A)].
A split is valid when:
- Upper boundary: Either A is exhausted (
count_A == len_A) or B has remaining elements with|A[count_A-1]| <= B[count_B] - Lower boundary: Either B is exhausted (
count_B == len_B) or A has remaining elements withB[count_B-1] < |A[count_A]|
(Note the strict inequality in condition 2 to handle ties consistently.)
If condition 1 fails, we took too many from A (search lower). If condition 2 fails, we took too few from A (search higher). When both conditions hold, the k-th element is the maximum of A[count_A-1] and B[count_B-1] (whichever was "picked last" in the merge order).
Time complexity: O(log N) for finding the partition point + O(log N) for the binary search = O(log N) total.
Space complexity: O(1), we only use a few index variables.
Implementation
def reorder_by_absolute_value(nums):
"""Part 1: Reorder by absolute value in O(N) time."""
n = len(nums)
# Find the split point
p = 0
while p < n and nums[p] < 0:
p += 1
result = []
left, right = p - 1, p
# Merge the two runs
while left >= 0 and right < n:
if -nums[left] <= nums[right]: # negative comes first on ties
result.append(nums[left])
left -= 1
else:
result.append(nums[right])
right += 1
# Append remaining elements
while left >= 0:
result.append(nums[left])
left -= 1
while right < n:
result.append(nums[right])
right += 1
return result
def kth_by_absolute_value(nums, k):
"""Part 2: Find k-th element (1-indexed) by absolute value in O(log N) time."""
n = len(nums)
if k < 1 or k > n:
raise ValueError("k out of bounds")
# Find partition point
p = 0
while p < n and nums[p] < 0:
p += 1
len_A, len_B = p, n - p
# Binary search for the split
lo = max(0, k - len_B)
hi = min(k, len_A)
while lo <= hi:
count_A = (lo + hi) // 2
count_B = k - count_A
# Get the boundary values (with bounds checking)
a_last = -nums[p - count_A] if count_A > 0 else -1
b_last = nums[p + count_B - 1] if count_B > 0 else -1
a_next = -nums[p - count_A - 1] if count_A < len_A else float('inf')
b_next = nums[p + count_B] if count_B < len_B else float('inf')
# Check validity of this split
if a_last > b_next:
# Took too many from A
hi = count_A - 1
elif b_last >= a_next: # strict inequality for tie-breaking
# Took too few from A
lo = count_A + 1
else:
# Valid split found
if count_A == 0:
return b_last
if count_B == 0:
return nums[p - count_A]
# Return the larger of the two "last taken" elements
return b_last if a_last <= b_last else nums[p - count_A]
raise AssertionError("Should not reach here")
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
| Part 1: Full reordering | O(N) | O(N) for output |
| Part 2: k-th element query | O(log N) | O(1) |
Common Mistakes
- Sorting the entire array: Using a general sort costs O(N log N), missing the linear-time opportunity
- Squaring values: Causes integer overflow; comparing absolute values is safer
- Inconsistent tie-breaking: Part 1 and Part 2 must handle equal absolute values identically
- Off-by-one errors: Mixing 0-indexed and 1-indexed positions, or incorrect boundary checks in the binary search
- Building intermediate arrays in Part 2: Defeats the O(1) space requirement; use index arithmetic instead
Edge Cases
- All negative or all non-negative: One run is empty; the merge degenerates to copying or reversing
- Zero present: Appears first (smallest absolute value)
- Duplicates: Handle via the tie-breaking rule
- k = 1 or k = n: Boundary cases for the search range