Data structures and algorithms · Lesson 27 of 60 · Code lesson, JavaScript or Python · Optional
Problem-solving techniques
Problem-solving techniques are reusable ideas: decomposition splits a big problem into small steps, two pointers walk in from both ends, a sliding window moves over a range, and divide and conquer splits the data in half.
Most of them turn slow repeated work into a single careful pass.
Naming the technique helps you spot the same shape in a new problem.
Worked example
In JavaScript, two index variables, left and right, start at the ends and move toward each other.
const numbers = [1, 2, 3, 4];
let left = 0;
let right = numbers.length - 1;
while (left < right) {
console.log(numbers[left] + numbers[right]);
left += 1;
right -= 1;
}Output:
5 5
In Python, two index variables, left and right, start at the ends and move toward each other.
numbers = [1, 2, 3, 4]
left = 0
right = len(numbers) - 1
while left < right:
print(numbers[left] + numbers[right])
left += 1
right -= 1Output:
5 5
Your turn
Use two pointers to check whether any two different numbers in a sorted list add up to the target. Finish the two branches: move the left pointer up when the sum is too small, and the right pointer down when it is too big.
Your program is checked with these 3 inputs:
Input:
1 2 4 7 11 9
Expected output:
yes
Input:
1 2 3 10
Expected output:
no
Input:
2 5 7
Expected output:
yes
Loading your practice…
Preparing your workspace…