KatInterview

Seat Assignment with Forward-Only Probing on a Fixed Row

Data Structure DesignAuto-graded · 21 test cases
MediumAuto-gradedData Structure Designunion-findsimulationarrays

Last updated

Decide whether every request in a sequence can be seated in a fixed row when taken spots push it to the next free higher slot; tests efficient next-free-slot lookup, e.g. with union-find.

A storage hall has n_slots slots in a single row, numbered 0 to n_slots - 1. Items are delivered one at a time, in the order given by the list wishes. The value wishes[i] is the slot number that the i-th item would like to occupy.

Your task is to decide whether all items can be stored.

Placement rules

  • All slots are empty at the start. An item that has been stored stays in its slot permanently.
  • An item is placed in its wished slot if that slot is empty.
  • Otherwise, it is placed in the empty slot with the smallest number that is greater than its wished slot.
  • Items never move to a slot with a number lower than the one they wished for. If every slot from the wished one to the last is occupied, that item cannot be stored.

Output

Return True if every item gets stored. Return False if at least one item cannot be stored. If wishes is empty, return True.

A solution that walks forward one slot at a time for each item can be too slow when many items crowd the same region, so aim for something better.

Constraints

  • 1 <= n_slots <= 10^5
  • 0 <= len(wishes) <= 10^5
  • 0 <= wishes[i] <= n_slots - 1

Examples

Example 1

Input: all_items_stored(5, [2, 2, 0, 4])

Output: True

Example 2

Input: all_items_stored(4, [2, 2, 3])

Output: False

Example 3

Input: all_items_stored(6, [3, 0])

Output: True

Hints

Hint 1

Slots only ever go from empty to occupied, never back. Think about what question you need to answer quickly for each item: 'which is the smallest empty slot at or after position x?'

Hint 2

A disjoint-set (union-find) structure fits this well: let each occupied slot point to the next slot, so that find(x) returns the smallest empty slot at or after x.

Hint 3

Add a sentinel index equal to n_slots meaning 'no slot available'. After filling slot s, link it to find(s + 1). If find(wish) ever returns the sentinel, return False. Use path compression to keep lookups near constant time.