- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 45 lines of Python from the credited upstream file 324.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def wiggleSort(self, nums: list[int]) -> None:3 n = len(nums)4 median = self._findKthLargest(nums, (n + 1) 2)5 6 def A(i: int):7 return (1 + 2 * i) % (n | 1)8 9 i = 010 j = 011 k = n - 112 13 while i <= k:14 if nums[A(i)] > median:15 nums[A(i)], nums[A(j)] = nums[A(j)], nums[A(i)]16 i, j = i + 1, j + 117 elif nums[A(i)] < median:18 nums[A(i)], nums[A(k)] = nums[A(k)], nums[A(i)]19 k -= 120 else:21 i += 122 23 24 def _findKthLargest(self, nums: list[int], k: int) -> int:25 def quickSelect(l: int, r: int, k: int) -> int:26 randIndex = random.randint(0, r - l) + l27 nums[randIndex], nums[r] = nums[r], nums[randIndex]28 pivot = nums[r]29 30 nextSwapped = l31 for i in range(l, r):32 if nums[i] >= pivot:33 nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped]34 nextSwapped += 135 nums[nextSwapped], nums[r] = nums[r], nums[nextSwapped]36 37 count = nextSwapped - l + 1 38 if count == k:39 return nums[nextSwapped]40 if count > k:41 return quickSelect(l, nextSwapped - 1, k)42 return quickSelect(nextSwapped + 1, r, k - count)43 44 return quickSelect(0, len(nums) - 1, k)45