KatInterview

Merge Sorted Runs by Absolute Value and Extract k-th Element

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbinary-searchtwo-pointersorder-statistics

Last 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