TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
Unit 1 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
lst
containing elements that need to be reversed.Q: What is the expected output of the function?
Q: Should the reversal be done in-place?
Q: Can the list contain any data types?
Q: What should the function return if the list is empty?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use the two-pointer approach to reverse the list in-place. One pointer starts at the beginning (left
) and the other starts at the end (right
). Swap the elements at these pointers and then move the pointers towards each other until they meet.
1) Initialize two pointers: `left` at the start of the list and `right` at the end of the list.
2) While `left` is less than `right`:
- Swap the elements at `lst[left]` and `lst[right]`.
- Move the `left` pointer one step to the right.
- Move the `right` pointer one step to the left.
3) Return the modified list after all elements have been swapped.
⚠️ Common Mistakes
def reverse_list(lst):
left = 0
right = len(lst) - 1
while left < right:
# Swap elements at left and right pointers
lst[left], lst[right] = lst[right], lst[left]
# Move pointers towards each other
left += 1
right -= 1
return lst