LeetCode 2161: Partition Array by Pivot

LeetCode 2161: Partition array according to given pivot ➗ Topic: Simulation Imagine you want to rearrange an array so all numbers smaller than a given pivot come first, followed by all equals to the pivot, then all larger numbers—while preserving the original order within each group. How does the code work? - Initialization: ---- Create three empty lists: before for numbers < pivot, middle for numbers == pivot, and after for numbers > pivot. - Partitioning Loop: ---- Iterate through each number in the input nums array exactly once. ---- If num < pivot, append it to before. ---- If num == pivot, append it to middle. ---- Otherwise (num > pivot), append it to after. - Result Construction: ---- Concatenate the three lists in order: before + middle + after using - Python's list addition. ---- Return the new partitioned list (same length as input). Complexity: - Time Complexity: O(n) — single pass through n elements, each append is O(1) amortized, concatenation is O(n). - Space Complexity: O(n) — three lists store all n elements plus temporary result list. Check out the problem here: https://lnkd.in/gu5yPWb9 Keep going, keep revising, and keep building confidence! 💪🔥 #DSA #Coding #ProblemSolving #Learning

  • text

Nice solution. Stability matters here and this approach keeps it simple and correct.

To view or add a comment, sign in

Explore content categories