|
| 1 | +## Explanation |
| 2 | + |
| 3 | +### Strategy |
| 4 | + |
| 5 | +**Constraints & Edge Cases** |
| 6 | + |
| 7 | + * **Input Size:** Array length can be up to 10⁵, and values can range from -10⁶ to 10⁶. |
| 8 | + * **Time Complexity:** O(n) - We make a single pass through the array to partition elements. |
| 9 | + * **Space Complexity:** O(n) - We create three lists to store elements (less, equal, greater). |
| 10 | + * **Edge Case:** All elements equal to pivot results in returning the original array. |
| 11 | + |
| 12 | +**High-level approach** |
| 13 | +We partition the array into three groups: elements less than pivot, elements equal to pivot, and elements greater than pivot. We maintain the relative order within each group, then combine them. |
| 14 | + |
| 15 | +**Brute force vs. optimized strategy** |
| 16 | + |
| 17 | + * **Brute Force:** Sort the array - but this doesn't maintain relative order of elements within groups. |
| 18 | + * **Optimized Strategy:** Use three separate lists to collect elements in a single pass, preserving relative order. |
| 19 | + |
| 20 | +**Decomposition** |
| 21 | + |
| 22 | +1. **Create Three Lists:** Initialize lists for elements less than, equal to, and greater than pivot. |
| 23 | +2. **Partition Elements:** Iterate through the array and place each element into the appropriate list. |
| 24 | +3. **Combine Lists:** Concatenate the three lists in order: less, equal, greater. |
| 25 | + |
| 26 | +### Steps |
| 27 | + |
| 28 | +1. **Initialization & Example Setup:** |
| 29 | + Let's say `nums = [9, 12, 5, 10, 14, 3, 10]` and `pivot = 10`. |
| 30 | + We create three empty lists: `less = []`, `equal = []`, `greater = []`. |
| 31 | + |
| 32 | +2. **Start Processing:** |
| 33 | + We iterate through each element in `nums`. |
| 34 | + |
| 35 | +3. **Trace Walkthrough:** |
| 36 | + |
| 37 | + | Element | Comparison | Action | less | equal | greater | |
| 38 | + |---------|-------------|--------|------|-------|---------| |
| 39 | + | 9 | 9 < 10 | Add to less | [9] | [] | [] | |
| 40 | + | 12 | 12 > 10 | Add to greater | [9] | [] | [12] | |
| 41 | + | 5 | 5 < 10 | Add to less | [9, 5] | [] | [12] | |
| 42 | + | 10 | 10 == 10 | Add to equal | [9, 5] | [10] | [12] | |
| 43 | + | 14 | 14 > 10 | Add to greater | [9, 5] | [10] | [12, 14] | |
| 44 | + | 3 | 3 < 10 | Add to less | [9, 5, 3] | [10] | [12, 14] | |
| 45 | + | 10 | 10 == 10 | Add to equal | [9, 5, 3] | [10, 10] | [12, 14] | |
| 46 | + |
| 47 | +4. **Combine:** |
| 48 | + `res = less + equal + greater = [9, 5, 3] + [10, 10] + [12, 14] = [9, 5, 3, 10, 10, 12, 14]` |
| 49 | + |
| 50 | +5. **Return Result:** |
| 51 | + Return the combined array `[9, 5, 3, 10, 10, 12, 14]`. |
| 52 | + |
0 commit comments