101 Logo
onenoughtone

Search Space Reduction

What is Search Space Reduction?

Search Space Reduction is a pattern that uses binary search to efficiently find an optimal value in a range, even when we don't have a sorted array to search in.

Instead of searching for a specific value, we search for the optimal value that satisfies certain conditions.

Key Concepts

  • Search Space: Define a range of possible answers (the search space)
  • Feasibility Function: Create a function that checks if a value is a feasible solution
  • Binary Search: Use binary search to narrow down the search space
  • Monotonicity: The feasibility function must be monotonic (if x is feasible, all values greater than x are also feasible, or vice versa)

Example: Square Root

Here's how to find the integer square root of a number using binary search:

function mySqrt(x) { if (x === 0) return 0; let left = 1; let right = Math.floor(x / 2) + 1; // Square root can't be larger than x/2 for x > 1 while (left <= right) { const mid = Math.floor((left + right) / 2); const square = mid * mid; if (square === x) { return mid; } if (square < x) { left = mid + 1; } else { right = mid - 1; } } // When we exit the loop, right is the integer square root of x return right; }

Example: Minimize Maximum Distance

Here's a more complex example: minimizing the maximum distance between adjacent positions after placing m new positions.

function minimizeMaxDistance(positions, m) { // Sort the positions positions.sort((a, b) => a - b); // Define the search space let left = 0; let right = positions[positions.length - 1] - positions[0]; // Binary search for the minimum maximum distance while (left < right) { const mid = Math.floor((left + right) / 2); // Check if it's possible to place m new positions // such that the maximum distance is at most mid if (canPlace(positions, m, mid)) { right = mid; } else { left = mid + 1; } } return left; } function canPlace(positions, m, maxDistance) { let count = 0; let prev = positions[0]; for (let i = 1; i < positions.length; i++) { const current = positions[i]; const distance = current - prev; // Calculate how many new positions we need to place // to ensure the distance is at most maxDistance count += Math.floor(distance / maxDistance); prev = current; } // Return true if we can place at most m new positions return count <= m; }

When to Use This Pattern

Use the Search Space Reduction pattern when:

  • You need to find an optimal value (minimum or maximum) that satisfies certain conditions
  • The search space is too large for a linear search
  • You can define a monotonic feasibility function
  • The problem involves optimization with a clear objective function
IntroVisualizePatternsPractice
101 Logo
onenoughtone