- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 103 lines of Python from the credited upstream file rotate-non-negative-elements.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def rotateElements(self, nums, k):7 """8 :type nums: List[int]9 :type k: int10 :rtype: List[int]11 """12 def gcd(a, b):13 while b:14 a, b = b, a%b15 return a16 17 def rotate(nums, k):18 k %= len(nums)19 c = gcd(len(nums), k)20 for i in xrange(c):21 for j in xrange(1, len(nums)c):22 nums[i], nums[(i-j*k)%len(nums)] = nums[(i-j*k)%len(nums)], nums[i]23 24 result = [x for x in nums if x >= 0]25 if not result:26 return nums27 rotate(result, k)28 j = 029 for i in xrange(len(nums)):30 if nums[i] < 0:31 continue32 nums[i] = result[j]33 j += 134 return nums35 36 37383940class Solution2(object):41 def rotateElements(self, nums, k):42 """43 :type nums: List[int]44 :type k: int45 :rtype: List[int]46 """47 def reverse(nums, left, right):48 while left < right:49 nums[left], nums[right] = nums[right], nums[left]50 left += 151 right -= 152 53 def rotate(nums, k):54 k %= len(nums)55 reverse(nums, 0, len(nums)-1)56 reverse(nums, 0, len(nums)-k-1)57 reverse(nums, len(nums)-k, len(nums)-1)58 59 result = [x for x in nums if x >= 0]60 if not result:61 return nums62 rotate(result, k)63 j = 064 for i in xrange(len(nums)):65 if nums[i] < 0:66 continue67 nums[i] = result[j]68 j += 169 return nums70 71 72737475class Solution3(object):76 def rotateElements(self, nums, k):77 """78 :type nums: List[int]79 :type k: int80 :rtype: List[int]81 """82 def reverse(nums, left, right):83 while left < right:84 nums[left], nums[right] = nums[right], nums[left]85 left += 186 right -= 187 88 def rotate(nums, k):89 k %= len(nums)90 nums[:] = nums[k:]+nums[:k]91 92 result = [x for x in nums if x >= 0]93 if not result:94 return nums95 rotate(result, k)96 j = 097 for i in xrange(len(nums)):98 if nums[i] < 0:99 continue100 nums[i] = result[j]101 j += 1102 return nums103