AlgoTales · Roadmap

Finding minimum feasible value

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

This pattern looks for the smallest value that passes a test, where everything below it fails and everything at or above it passes. Because the results flip only once, you can halve the range each time and find the switch point quickly.

Practical use cases

  • Web app: First bad release. Your app was fine in release 1 and broken in release 200. Every release after the first bad one is also broken. Testing the middle release and halving finds the first broken one in about 8 deployments instead of 200.
  • Web app: Minimum days to finish all orders. A warehouse tool asks the smallest number of days in which a team can pack all pending orders. Guess 10 days, simulate, check if it fits, and adjust. The answer appears after a few simulations without trying every day count.
  • System: Finding the smallest threshold. A monitoring system needs the lowest alert threshold that stops false alarms. It tests thresholds by halves on past data and finds the cutoff quickly. Each simulation takes a minute, so a handful of guesses is a huge saving over trying every threshold one by one.

The story: The First Day That Works

Raju's cousin was a florist, and a big wedding needed 2 garlands. Each garland needed 3 flowers that sit side by side on the vine. Every flower bloomed on its own day: 7, 7, 7, 7, 12, 7, 7. "What is the earliest day I can make both garlands?" he asked.

Mira did not try to reason about every flower. She just asked a yes/no question: "If I wait until day D, can I make 2 garlands?" On day 6: no. Day 7? Count the groups of three neighbouring bloomed flowers: just one group (flowers 1-3). No. Day 12: yes! And look: once the answer is yes, it stays yes forever. More waiting never hurts.

So the days form a line that looks like no, no, no, YES, YES, YES. We want the first YES: the minimum feasible value. Whenever the feasibility has that "switch from no to yes" shape, binary search finds the switch point in a few guesses. Test the middle day: yes means the switch is here or earlier; no means it is later. This one pattern solves a huge family of "smallest X that works" puzzles.

How to spot this problem, and where you need it

You are looking for the first point where something starts working or stops failing, and once it flips it stays that way, but testing every point is too slow.

Signs you need it

  • The problem says "minimum", "earliest", "first version that", "smallest threshold" or "at least how many days".
  • Results look like no, no, no, yes, yes, yes, with one clean switch from failing to passing.
  • Each test is expensive, such as a build, a simulation or a database run, so you want as few tests as possible.

Where to use it in a project

  • Finding the first bad commit or release, using git bisect or a manual deployment search.
  • Choosing the smallest setting, like a timeout, cache size or worker count, that makes a test pass.

The solution

Set a low value that fails and a high value that passes. Test the middle. If it passes, the answer is this value or something smaller, so move the high edge down. If it fails, the answer is larger, so move the low edge up. Keep going until the two edges touch; the high edge is the smallest value that works.

Payoff: Before: 200 test runs one by one. After: about 8 runs to pin down the first working or failing point.

Explain it like I am 8

Imagine a door that is locked until some secret moment and stays open after that. You want to know the very first moment it is open. Check the middle of the time: open? Then the secret moment is before or now. Locked? Then it is later. Keep halving.

How it works, step by step

  1. Name your answer (here: a day) and choose its range: the smallest and largest it could ever be.
  2. Write a feasible(x) check that answers "does x work?". Make sure it flips from no to yes just once.
  3. Test the middle. Feasible? It might be the first yes: high = mid. Not feasible? low = mid + 1.
  4. Stop when low equals high. That is the first (minimum) feasible value.
  5. Check impossible cases first (for example, not enough flowers at all) and return -1.

The code in four languages

PHP

<?php
// Can we make $m garlands, each from $k ADJACENT bloomed flowers, by day $day?
function canMake(array $bloom, int $m, int $k, int $day): bool {
    $run = 0;          // current streak of bloomed neighbours
    $made = 0;
    foreach ($bloom as $b) {
        if ($b <= $day) {
            $run++;
            if ($run === $k) { $made++; $run = 0; }   // one garland done, start again
        } else {
            $run = 0;                                  // an unbloomed flower breaks the streak
        }
    }
    return $made >= $m;
}

// Earliest day that works, or -1 when there are not enough flowers at all.
function minDays(array $bloom, int $m, int $k): int {
    if ($m * $k > count($bloom)) return -1;
    $low = min($bloom);
    $high = max($bloom);
    while ($low < $high) {
        $mid = intdiv($low + $high, 2);
        if (canMake($bloom, $m, $k, $mid)) {
            $high = $mid;           // works: maybe an earlier day works too
        } else {
            $low = $mid + 1;
        }
    }
    return $low;
}

echo minDays([7, 7, 7, 7, 12, 7, 7], 2, 3), "\n";   // 12
echo minDays([1, 10, 3, 10, 2], 3, 1), "\n";         // 3
echo minDays([1, 10], 2, 2), "\n";                   // -1

JavaScript

// Can we make m garlands, each from k ADJACENT bloomed flowers, by the given day?
function canMake(bloom, m, k, day) {
  let run = 0;          // current streak of bloomed neighbours
  let made = 0;
  for (const b of bloom) {
    if (b <= day) {
      run++;
      if (run === k) { made++; run = 0; }   // one garland done, start again
    } else {
      run = 0;                              // an unbloomed flower breaks the streak
    }
  }
  return made >= m;
}

// Earliest day that works, or -1 when there are not enough flowers at all.
function minDays(bloom, m, k) {
  if (m * k > bloom.length) return -1;
  let low = Math.min(...bloom);
  let high = Math.max(...bloom);
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (canMake(bloom, m, k, mid)) {
      high = mid;       // works: maybe an earlier day works too
    } else {
      low = mid + 1;
    }
  }
  return low;
}

console.log(minDays([7, 7, 7, 7, 12, 7, 7], 2, 3));   // 12
console.log(minDays([1, 10, 3, 10, 2], 3, 1));         // 3
console.log(minDays([1, 10], 2, 2));                   // -1

Java

public class Main {
    // Can we make m garlands, each from k ADJACENT bloomed flowers, by the given day?
    static boolean canMake(int[] bloom, int m, int k, int day) {
        int run = 0;          // current streak of bloomed neighbours
        int made = 0;
        for (int b : bloom) {
            if (b <= day) {
                run++;
                if (run == k) { made++; run = 0; }   // one garland done, start again
            } else {
                run = 0;                             // an unbloomed flower breaks the streak
            }
        }
        return made >= m;
    }

    // Earliest day that works, or -1 when there are not enough flowers at all.
    static int minDays(int[] bloom, int m, int k) {
        if (m * k > bloom.length) return -1;
        int low = Integer.MAX_VALUE, high = Integer.MIN_VALUE;
        for (int b : bloom) {
            low = Math.min(low, b);
            high = Math.max(high, b);
        }
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (canMake(bloom, m, k, mid)) {
                high = mid;       // works: maybe an earlier day works too
            } else {
                low = mid + 1;
            }
        }
        return low;
    }

    public static void main(String[] args) {
        System.out.println(minDays(new int[]{7, 7, 7, 7, 12, 7, 7}, 2, 3));   // 12
        System.out.println(minDays(new int[]{1, 10, 3, 10, 2}, 3, 1));         // 3
        System.out.println(minDays(new int[]{1, 10}, 2, 2));                   // -1
    }
}

Go

package main

import (
	"fmt"
	"slices"
)

// canMake: can we make m garlands, each from k ADJACENT bloomed flowers, by the given day?
func canMake(bloom []int, m, k, day int) bool {
	run := 0 // current streak of bloomed neighbours
	made := 0
	for _, b := range bloom {
		if b <= day {
			run++
			if run == k {
				made++
				run = 0 // one garland done, start again
			}
		} else {
			run = 0 // an unbloomed flower breaks the streak
		}
	}
	return made >= m
}

// minDays returns the earliest day that works, or -1 when there are not enough flowers at all.
func minDays(bloom []int, m, k int) int {
	if m*k > len(bloom) {
		return -1
	}
	low := slices.Min(bloom)
	high := slices.Max(bloom)
	for low < high {
		mid := low + (high-low)/2
		if canMake(bloom, m, k, mid) {
			high = mid // works: maybe an earlier day works too
		} else {
			low = mid + 1
		}
	}
	return low
}

func main() {
	fmt.Println(minDays([]int{7, 7, 7, 7, 12, 7, 7}, 2, 3)) // 12
	fmt.Println(minDays([]int{1, 10, 3, 10, 2}, 3, 1))      // 3
	fmt.Println(minDays([]int{1, 10}, 2, 2))                // -1
}

Time: O(n log R) · Extra space: O(1). About log R guesses over the day range R, and each check walks the n flowers once.

Watch out for

  • Forgetting that flowers must be adjacent; counting bloomed flowers in total gives wrong answers.
  • Not resetting the streak after finishing a garland or hitting an unbloomed flower.
  • Skipping the "impossible" check, so the search returns a day that never works.

Quick check

  1. What shape must the yes/no answers have?
    • no...no, then yes...yes (one switch)
    • Alternating yes and no
    • All yes
  2. The middle guess is feasible. What do we do?
    • low = mid + 1
    • Stop immediately
    • high = mid
  3. What does the search return?
    • The largest feasible value
    • The middle of the range
    • The smallest feasible value