Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 4, 2025 00:01
Show Gist options
  • Save tatsuyax25/856766aec5a39dcd075207f1ba290240 to your computer and use it in GitHub Desktop.
Save tatsuyax25/856766aec5a39dcd075207f1ba290240 to your computer and use it in GitHub Desktop.
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears i
/**
* @param {number[]} nums
* @param {number} pivot
* @return {number[]}
*/
var pivotArray = function(nums, pivot) {
// Arrays to hold elements less than, equal to, and greater than pivot
let lessThanPivot = [];
let equalToPivot = [];
let greaterThanPivot = [];
// Iterate through the array to clssify elements
for (let num of nums) {
if (num < pivot) {
lessThanPivot.push(num); // Add to lessThanPivot if element is less than pivot
} else if (num === pivot) {
equalToPivot.push(num); // Add to equalToPivot if element is equal to pivot
} else {
greaterThanPivot.push(num); // Add to greaterThanPivot if element is greater than pivot
}
}
// Combine the three arrays in order: lessThanPivot, equalToPivot, greaterThanPivot
return [...lessThanPivot, ...equalToPivot, ...greaterThanPivot];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment