Rearrange an array
Problem Description
Given an unsorted array of integers arr and a threshold index thres, implement a function that transforms and returns the array such that:
All elements before index thres (indices 0 to thres - 1) are sorted in ascending order.
The element at index thres remains in its original position and value (acts as an untouched pivot).
All elements after index thres (indices thres + 1 to N - 1) are sorted in descending order.
Constraints & Requirements
0 <= thres < arr.size()
The element at arr[thres] must remain at index thres with its value unchanged.
Elements cannot be discarded or synthesized—the output array must contain all original elements partitioned into their respective sub-regions.
Examples
Example 1
Input: arr = [1, 5, 2, 9, 6, 7, 8], thres = 3
Output: [1, 2, 5, 9, 8, 7, 6]
Valid: true (Sub-array [1, 5, 2] sorted ascending to [1, 2, 5], index 3 (9) untouched, sub-array [6, 7, 8] sorted descending to [8, 7, 6])
Example 2 (Threshold at Start)
Input: arr = [10, 40, 20, 50, 30], thres = 0
Output: [10, 50, 40, 30, 20]
Valid: true (No elements before thres, index 0 (10) untouched, elements after thres sorted descending)
SystemVerilog
Code Editor Access
Log in to write, run and submit your solution to this interview question. It's free.
