
Code
Two Pointers
Need two items in a sorted list that add up to a target? The naive way checks every pair with nested loops: O(n²). The two pointers pattern does it in one pass, O(n).
Put left at the start and right at the end:
- sum too small? move
leftright (to a bigger number) - sum too big? move
rightleft (to a smaller number) - equal? found it!
nums = [1, 3, 4, 6, 9] # sorted!
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
...
Each step throws away one candidate that can't possibly work, so the pointers meet after at most n steps.
The same idea checks palindromes, pointers start at both ends and walk inward comparing characters, with no reversed copy needed.
Assignment
pair_with_sum(nums, target):numsis sorted. Return a tuple(a, b)of two values (at different positions,a <= b) that add totarget, orNoneif there isn't one.is_mirror(text): returnTrueif the text reads the same both ways, ignoring case and anything that isn't a letter or digit (usestr.isalnum()). Use two pointers.
pair_with_sum(nums, target):numsis sorted. Return a tuple(a, b)of two values (at different positions,a <= b) that add totarget, orNoneif there isn't one.is_mirror(text): returnTrueif the text reads the same both ways, ignoring case and anything that isn't a letter or digit (usestr.isalnum()). Use two pointers.
main.py Python sleeping
Press Run to try your code, then Check to test it.