KatInterview

Biggest Cabin Party Respecting Everyone's Companion Limits

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalsdifference-arrayintervalscounting

Last updated

Find the largest group size k where at least k people accept exactly k-1 companions, using interval counting with a difference array in linear time.

A group of campers wants to share one cabin. There are n campers, and camper i will only stay in a cabin that holds at least min_others[i] and at most max_others[i] other campers besides themselves.

If you put k campers in the cabin together, each of them has exactly k - 1 cabin-mates. A camper i in that group is happy only if

min_others[i] <= k - 1 <= max_others[i].

Choose any subset of campers so that every chosen camper is happy. Return the largest possible size of such a subset.

Rules

  • Any subset of campers may be chosen, and the cabin is large enough for all n of them. Only the campers' own limits matter.
  • Campers who are not chosen place no requirement on the group.
  • If no non-empty group makes all its members happy, return 0.
  • Whether a size works is not necessarily monotone: a size can be impossible while both a smaller and a larger size are possible.

Input

  • min_others: list of n integers, the minimum number of cabin-mates each camper accepts.
  • max_others: list of n integers, the maximum number of cabin-mates each camper accepts. It has the same length as min_others.

Output

An integer: the largest group size that can be formed, or 0 if none exists.

Constraints

  • 1 <= n <= 10^5, where n = len(min_others) = len(max_others)
  • 0 <= min_others[i] <= max_others[i] <= 10^9
  • Aim for O(n) time.

Examples

Example 1

Input: largest_valid_party([0, 1, 1, 2, 2], [1, 2, 2, 4, 4])

Output: 3

Example 2

Input: largest_valid_party([2, 2, 2, 0], [2, 2, 3, 0])

Output: 3

Example 3

Input: largest_valid_party([1, 2], [1, 3])

Output: 0

Hints

Hint 1

Each camper's limits on other campers can be turned into a range of acceptable group sizes. Mind the off-by-one: a group of size k means k-1 cabin-mates.

Hint 2

For a fixed size k, count how many campers accept k. Any k of those campers form a valid group, so k is achievable exactly when that count is at least k.

Hint 3

Group sizes above n are never possible, so clip each range to n and apply all range additions with a difference array and one prefix-sum sweep. Do not binary search, because feasibility is not monotone.