Leetcode 2161: Partition Array According to Given Pivot

grid47
grid47
Exploring patterns and algorithms
Apr 4, 2024 6 min read

You are given an integer array ’nums’ and a value ‘pivot’. Your task is to rearrange the elements in ’nums’ such that all elements less than ‘pivot’ appear before any element greater than ‘pivot’, and all elements equal to ‘pivot’ appear between the elements less than and greater than ‘pivot’. The relative order of the elements less than and greater than ‘pivot’ should be preserved.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array 'nums' and an integer 'pivot'.
Example: nums = [15, 20, 10, 25, 10, 5], pivot = 10
Constraints:
• 1 <= nums.length <= 10^5
• -10^6 <= nums[i] <= 10^6
• pivot is an element in nums.
Output: The output should be the array 'nums' after rearranging it according to the conditions described in the problem statement.
Example: [5, 10, 10, 15, 20, 25]
Constraints:
• The output must preserve the relative order of elements less than and greater than pivot.
Goal: Rearrange the elements in nums such that all elements less than pivot come first, followed by elements equal to pivot, and then elements greater than pivot.
Steps:
• Count the number of elements less than pivot, equal to pivot, and greater than pivot.
• Allocate space for the rearranged array.
• Place elements less than pivot first, then the pivot elements, and finally the elements greater than pivot, maintaining the relative order.
Goal: The input array nums must have between 1 and 100,000 elements, and the values in nums and pivot are bounded between -1,000,000 and 1,000,000.
Steps:
• nums.length between 1 and 100,000
• -10^6 <= nums[i] <= 10^6
• pivot must be an element in nums
Assumptions:
• The input will always contain a valid pivot, and there will always be at least one element equal to pivot in nums.
Input: Example 1: nums = [15, 20, 10, 25, 10, 5], pivot = 10
Explanation: The elements 5 are less than the pivot and appear before the 10's. The pivot 10's are in the middle, and the elements greater than 10 (15, 20, 25) appear last.

Input: Example 2: nums = [2, 3, 1, 4, 1], pivot = 3
Explanation: The element 2 and 1 are less than the pivot and appear first, followed by 3, and finally 4, maintaining the original order.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus