Python For-Loop Control & Indexing
- The Loop Control Mistake: Do not use
for i in nums when you need to change elements based on position. It only gives the direct values of the array, not the positions.
- The Indexing Error: When doing an in-place lookup like
nums[i-1], always start your loop range from index 1 (range(1, len(nums))). Starting from 0 will trigger a negative index (nums[-1]), which incorrectly pulls the last item of the array.
- Array Handling: Remember that indexing allows direct modification of data in memory, whereas looping through direct values doesn't allow you to alter the array structure safely.
Append()
- Infinite Loop Trap: When concatenating, don’t change the list length (e.g., with
append) while iterating over the same list unless you have a clear stopping condition. This can lead to unexpected index behavior.
- Appending vs. Adding:
append() adds a single element, while + concatenates two lists. Don’t confuse ans.append(nums) (which adds the entire list as one nested element) with ans.extend(nums) or nums + nums.
Use of Build-in functions
- I used a built-in method, and the count is O(1), not O(n).
Python While-Loop Control & Pointer Logic
- Loop control: Don’t use a fixed
for loop (or let pointers move past the middle). If you keep swapping after the midpoint, you’ll swap back and undo the reverse.
- Correct stopping condition: For an in-place swap like
s[left], s[right] = s[right], s[left], the condition must be while left < right.
- Avoid
left <= right (causes redundant swaps at the center).
- Ensure pointer updates are correct:
left += 1, right -= 1.
- In-place constraint: Two-pointer swapping modifies the existing array/string buffer and uses O(1) extra space; creating a new reversed structure violates the in-place requirement.