I iterate through nums and categorize elements into three lists: less_than, equal_to, and greater_than. This shows that all elements less than pivot appear first, followed by elements equal to pivot, then elements greater than pivot.
The relative order of elements in each category is preserved as required.
class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
less_than = []
equal_to = []
greater_than = []
for num in nums:
if num < pivot:
less_than.append(num)
elif num == pivot:
equal_to.append(num)
else:
greater_than.append(num)
return less_than + equal_to + greater_than
- Time: O(n)
- Space: O(n)
