Add lesson 2: Arrays and two pointers

Mira Kovac 9 months ago
parent 646966f49a commit eca5fb3145deaac841638d4b06492f646314a049
3 changed files with 38 additions and 0 deletions
+19-0lessons/02-arrays-and-two-pointers/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 2: Arrays and two pointers
2+
3+Arrays and two pointers comes up in almost every real Python project. We start with the why, then write code together.
4+
5+Full lesson: [https://glibcode.net/courses/algorithms/lessons/2](https://glibcode.net/courses/algorithms/lessons/2)
6+
7+## Files
8+
9+- `two_pointers.py`: pair sum in a sorted list with two pointers
10+
11+## Run it
12+
13+```sh
14+python3 two_pointers.py
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/02-arrays-and-two-pointers/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 2
2+
3+1. Make the example ask for its input instead of using a fixed value.
4+2. Add a check that prints a warning when a result looks wrong (negative, empty, too big).
5+3. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to?
+14-0lessons/02-arrays-and-two-pointers/two_pointers.py ADDED
@@ -0,0 +1,14 @@
1+def pair_with_sum(sorted_nums, target):
2+ left, right = 0, len(sorted_nums) - 1
3+ while left < right:
4+ total = sorted_nums[left] + sorted_nums[right]
5+ if total == target:
6+ return sorted_nums[left], sorted_nums[right]
7+ if total < target:
8+ left += 1
9+ else:
10+ right -= 1
11+ return None
12+
13+
14+print(pair_with_sum([1, 3, 4, 6, 8, 11], 10)) # (4, 6)