Two Pointers
16 / 170Two PointersLesson 1 of 6About 48 min
The simplest version of the pattern, and the habit of naming what is already settled.
A common variation is that only some positions count. Rather than building a cleaned copy of the input, advance each pointer past the characters that do not matter and work with what is left.
This keeps the extra space at O(1), which is usually the reason the problem is being asked in the first place. Below, only letters move; everything else stays exactly where it started.
def reverse_letters_only(text): chars = list(text) left, right = 0, len(chars) - 1 while left < right: while left < right and not chars[left].isalpha(): left += 1 while left < right and not chars[right].isalpha(): right -= 1 chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1 return "".join(chars) print(reverse_letters_only("a-bC-dEf-ghIj"))print(reverse_letters_only("....."))The inner skip loop has no bound of its own. Type what this prints, including the exception name if it raises one.
def broken(text): chars = list(text) left, right = 0, len(chars) - 1 while left < right: while not chars[left].isalpha(): left += 1 while not chars[right].isalpha(): right -= 1 chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1 return "".join(chars) try: print(broken(".,.,"))except IndexError: print("IndexError")Three functions on the same skeleton. pair_sums_from_ends pairs the outermost values, then the next pair inward, and so on. count_matching_ends counts how many pairs of characters match while walking inward, stopping at the first mismatch. has_pair_summing_to takes a sorted list and reports whether any two values add to the target.
Tests
print(pair_sums_from_ends([1, 2, 3, 4]), pair_sums_from_ends([1, 2, 3]), pair_sums_from_ends([5]))print(count_matching_ends("abcba"), count_matching_ends("abcda"), count_matching_ends("xy"))print(has_pair_summing_to([1, 3, 5, 8], 11), has_pair_summing_to([1, 3, 5, 8], 12))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.