Algorithmic Techniques
🎯 What will I be able to do after this article, and how will it help in practice? Describe this in one short paragraph.
These techniques help frontend beginners understand and solve complex problems such as page data processing, animation state management, and performance optimization. Simple examples and accessible explanations introduce recursion, divide and conquer, greedy algorithms, dynamic programming, and two pointers so you can write code with greater confidence and efficiency.
🌀 Recursion and Iteration
Recursion and iteration are two fundamental approaches to solving problems. Recursion means a function calls itself, like moving deeper into a maze one step at a time. Iteration uses loops to repeat an operation.
For example, consider calculating the sum from 1 to n.
The recursive approach breaks this down into n + (the sum from 1 to n-1):
function sumRecursive(n) {
if (n === 1) return 1;
return n + sumRecursive(n - 1);
}
console.log(sumRecursive(5)); // 15
The iterative approach accumulates the sum in a loop:
function sumIterative(n) {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i;
}
return total;
}
console.log(sumIterative(5)); // 15
🪓 Divide and Conquer
Divide and conquer splits a problem into smaller problems, solves them separately, and combines their results. It is useful for complex tasks such as sorting.
Quick sort is a classic example.
The steps are:
- Choose a pivot.
- Partition the array into values smaller than the pivot and values greater than or equal to it.
- Recursively sort both portions.
- Combine the results.
Example code:
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) left.push(arr[i]);
else right.push(arr[i]);
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
console.log(quickSort([3, 6, 2, 8, 4])); // [2,3,4,6,8]
💰 Greedy Algorithms
A greedy algorithm chooses the locally optimal option at each step in the hope of reaching a globally optimal solution.
For a simple change-making problem, suppose the available denominations are 10, 5, and 1 yuan, and you need to give 18 yuan in change.
A greedy algorithm chooses the largest denomination first:
- Take one 10-yuan coin, leaving 8 yuan.
- Take one 5-yuan coin, leaving 3 yuan.
- Take three 1-yuan coins, leaving 0 yuan.
Code example:
function getChange(amount) {
const coins = [10, 5, 1];
const result = [];
for (let coin of coins) {
while (amount >= coin) {
amount -= coin;
result.push(coin);
}
}
return result;
}
console.log(getChange(18)); // [10, 5, 1, 1, 1]
🧩 Introduction to Dynamic Programming
Dynamic programming (DP) can optimize recursive solutions and suits problems with overlapping subproblems and optimal substructure.
For example, consider the classic Fibonacci sequence:
function fib(n) {
const dp = [0, 1];
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
console.log(fib(10)); // 55
Dynamic programming stores previously calculated results to avoid repeated computation.
🧮 Two Pointers and Sliding Windows
The two-pointer technique uses two indices (pointers) that move through an array or string to solve a problem.
A sliding window is a variation of this technique, often used for substring or subarray problems.
For example, find the length of the longest substring without repeating characters.
Use two pointers to maintain a window. Move the right pointer forward and adjust the left pointer to keep all characters in the window unique.
Example code:
function lengthOfLongestSubstring(s) {
let left = 0;
let maxLen = 0;
const map = new Map();
for (let right = 0; right < s.length; right++) {
const char = s[right];
if (map.has(char) && map.get(char) >= left) {
left = map.get(char) + 1;
}
map.set(char, right);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
console.log(lengthOfLongestSubstring('abcabcbb')); // 3
❓ Questions and Answers
Q1: What are the advantages and disadvantages of recursion and iteration? Recursion is concise and naturally expresses tree structures and divide-and-conquer solutions, but it can overflow the stack. Iteration uses less memory and is efficient, although its code can sometimes be more complex.
Q2: How do divide and conquer and dynamic programming differ? Divide and conquer splits a problem into independent subproblems. Dynamic programming suits overlapping subproblems whose results need to be reused.
🎉 You have learned recursion and iteration, divide and conquer, greedy algorithms, introductory dynamic programming, and two-pointer sliding windows! Keep practicing to strengthen your frontend algorithm skills!
Algorithms
Learn common sorting and searching algorithms in JavaScript through explanations and examples for frontend beginners.
Depth-First and Breadth-First Search
Learn depth-first and breadth-first search through tree structures and approachable explanations of these two classic traversal algorithms.
