All problems
0859MediumArrayHash TableGreedy

Fewest Crates to Sort the Bearings

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2910Minimum Number of Groups to Create a Valid Assignment

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tray of bearings is given as balls, where balls[i] is the grade of bearing i.

Every bearing must go into a crate, and a crate may only hold bearings of a single grade. The packing is tidy when any two crates differ in count by at most one.

Return the fewest crates a tidy packing can use.

Examples

Example 1

Input
balls = [5, 5, 5, 5, 5, 6]
Output
4

Grade 6 appears once, so every crate must hold one or two bearings. The five grade 5 bearings need three crates at that size, and the grade 6 bearing needs one of its own.

Example 2

Input
balls = [1, 1, 1, 2]
Output
3

Grade 2 appears once, so every crate must hold one or two bearings. Three crates of one grade-1 bearing each, plus one for the grade 2, gives four.

Example 3

Input
balls = [7, 7, 7]
Output
1

All three bearings share a grade, so a single crate holds them and no other crate exists to differ from.

Constraints

  • 1 <= balls.length <= 10^5
  • 1 <= balls[i] <= 10^9

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_crates(balls: list[int]) -> int:
Java
public int fewestCrates(int[] balls)
September 7
Apply