Two Pointers
18 / 170Two PointersLesson 3 of 6About 52 min
Turning a three-element search into a two-element one, and handling duplicates without a set.
This is meant to return each distinct pair once. On the input [1, 1, 2, 2, 3, 3] with target 4 it returns [[1, 3], [1, 3], [2, 2]]. Click the line that causes the repeat.
Give the time and space complexity of count_triples_summing_to on an already sorted list of length n, not counting the output.
for i in range(len(sorted_values) - 2): left, right = i + 1, len(sorted_values) - 1 need = target - sorted_values[i] while left < right: pair = sorted_values[left] + sorted_values[right] if pair == need: total += 1 left += 1 right -= 1 elif pair < need: left += 1 else: right -= 1Read 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.