DEV Community

Cover image for ๐Ÿš€Algorithm Techniques for Efficient Problem Solving
Atul Tripathi
Atul Tripathi

Posted on

๐Ÿš€Algorithm Techniques for Efficient Problem Solving

๐Ÿš€ Must-Know Algorithm Techniques for Efficient Problem Solving

Mastering algorithmic techniques can significantly improve your coding efficiency. Below are some key strategies along with examples and LeetCode problems to help you practice. ๐Ÿ’ก


๐Ÿ”น 1. Two Pointer Technique ๐Ÿƒโ€โ™‚๏ธ๐Ÿƒโ€โ™€๏ธ

Concept: Use two pointers to efficiently search through a sorted list.

Common Use Cases:

  • Searching in sorted arrays
  • Finding pairs that meet a condition

Example: Find two numbers in a sorted array that sum to a target value.

function twoSumSorted(arr, target) {
  let left = 0, right = arr.length - 1;
  while (left < right) {
    let sum = arr[left] + arr[right];
    if (sum === target) return [arr[left], arr[right]];
    sum < target ? left++ : right--;
  }
  return [];
}
Enter fullscreen mode Exit fullscreen mode

Practice: Two Sum II


๐Ÿ”น 2. Prefix Sum โž•

Concept: Compute cumulative sums to quickly answer range sum queries.

Common Use Cases:

  • Fast range sum calculations
  • Detecting patterns in sequences

Example: Compute prefix sums for an array.

function prefixSum(arr) {
  let prefix = [0];
  for (let i = 0; i < arr.length; i++) {
    prefix[i + 1] = prefix[i] + arr[i];
  }
  return prefix;
}
Enter fullscreen mode Exit fullscreen mode

Practice: Range Sum Query


๐Ÿ”น 3. Top K Elements ๐Ÿ”

Concept: Use sorting or heaps to find the most important elements in a list.

Example: Find the largest k elements.

function topKElements(arr, k) {
  return arr.sort((a, b) => b - a).slice(0, k);
}
Enter fullscreen mode Exit fullscreen mode

Practice: Top K Frequent Elements


๐Ÿ”น 4. Sliding Window ๐Ÿ 

Concept: Use a moving window to optimize range-based computations.

Example: Find the maximum sum of any k consecutive elements.

function maxSumSubarray(arr, k) {
  let sum = 0, maxSum = -Infinity;
  for (let i = 0; i < k; i++) sum += arr[i];
  for (let i = k; i < arr.length; i++) {
    sum += arr[i] - arr[i - k];
    maxSum = Math.max(maxSum, sum);
  }
  return maxSum;
}
Enter fullscreen mode Exit fullscreen mode

Practice: Maximum Subarray


๐Ÿ”น 5. Breadth-First Search ๐ŸŒณ

Concept: Explore a graph layer by layer.

Example: Traverse a graph using BFS.

function bfs(graph, start) {
  let queue = [start], visited = new Set(queue);
  while (queue.length) {
    let node = queue.shift();
    console.log(node);
    for (let neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Practice: Binary Tree Level Order Traversal


๐Ÿ”น 6. Depth-First Search ๐Ÿ•ต๏ธ

Concept: Explore one path deeply before backtracking.

Example: Perform DFS on a graph.

function dfs(graph, node, visited = new Set()) {
  if (visited.has(node)) return;
  visited.add(node);
  console.log(node);
  for (let neighbor of graph[node]) {
    dfs(graph, neighbor, visited);
  }
}
Enter fullscreen mode Exit fullscreen mode

Practice: Number of Islands


๐Ÿ”น 7. Topological Sort ๐Ÿ“‹

Concept: Order tasks when dependencies exist.

Example: Perform topological sorting.

function topologicalSort(graph) {
  let inDegree = {}, queue = [], result = [];
  Object.keys(graph).forEach(node => inDegree[node] = 0);
  Object.values(graph).flat().forEach(node => inDegree[node]++);
  Object.keys(graph).forEach(node => inDegree[node] === 0 && queue.push(node));
  while (queue.length) {
    let node = queue.shift();
    result.push(node);
    graph[node].forEach(neighbor => {
      if (--inDegree[neighbor] === 0) queue.push(neighbor);
    });
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Practice: Course Schedule II


๐Ÿ”น 8. Divide and Conquer โœ‚๏ธ

Concept: Break a problem into smaller parts and solve them independently.

Example: Implement merge sort.

function mergeSort(arr) {
  if (arr.length < 2) return arr;
  let mid = Math.floor(arr.length / 2);
  let left = mergeSort(arr.slice(0, mid));
  let right = mergeSort(arr.slice(mid));
  return merge(left, right);
}
function merge(left, right) {
  let result = [];
  while (left.length && right.length) {
    result.push(left[0] < right[0] ? left.shift() : right.shift());
  }
  return [...result, ...left, ...right];
}
Enter fullscreen mode Exit fullscreen mode

Practice: Sort an Array


๐Ÿš€ Keep Practicing!

These techniques will significantly improve your problem-solving skills. Keep practicing and refining your approach! ๐Ÿ’ช๐ŸŽ‰

๐Ÿ’ฌ Have questions? Drop them in the comments! ๐Ÿ‘‡


Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.