Two pointers Flashcards
(5 cards)
What is the Two Pointers pattern and when is it used?
Uses two pointers to traverse array/list for efficient solutions.
Use Case: Sorted arrays, linked lists, pair-wise comparisons.
Example: [Merge Two Sorted Lists]. Action: Verbalize use case aloud.
What are the key steps in the Two Pointers technique?
- Initialize pointers (e.g., left=0, right=n-1).
- Move based on condition (e.g., sum < target).
- Update result (e.g., store pair).
Action: Explain steps for [Merge Two Sorted Lists] aloud.
How does the Two Pointers technique apply to [Merge Two Sorted Lists]?
Merge two sorted linked lists by comparing nodes, attaching the smaller to the result, and advancing the pointer.
Action: Verbalize solution logic aloud.
What are the complexity and gotchas of the Two Pointers technique?
Time complexity: O(n+m), Space complexity: O(1).
Gotchas: Empty lists, one list longer.
Action: List edge cases for [Merge Two Sorted Lists] aloud.
Code example for the Two Pointers technique.
```python
from typing import Optional
class ListNode:
def __init__(self, val: int = 0, next: ‘ListNode’ = None):
self.val = val
self.next = next
def merge_two_lists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
current = dummy
while list1 and list2:
if list1.val <= list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
current.next = list1 or list2
return dummy.next
~~~