FreeExam

Scheduling and Resource Utilities

Original Python coding interviews on resource constraints, dependency timing, fair queues, reservation boundaries, exact subset choices, and capacity headroom.

These problems are original practice. They are not questions from a named employer or a live hiring loop.

  1. 1.Admit whole resource vectors without partial consumption

    Write admit_vectors(capacity, requests). capacity maps resource names to nonnegative integer units; requests is [unique_id,demand_dict] rows of nonnegative integers. Scan in order; accept and subtract a whole demand only if every resource fits. Reject without consumption and continue. Unknown resources have zero capacity. Return {"accepted":ids,"rejected":ids,"remaining":capacity_keys_only}.

  2. 2.Apply first-fit decreasing with explicit stable ties

    Write decreasing_bins(items, capacity). items is [unique_string_id,nonnegative_integer_size] rows; capacity is positive integer. Reject oversized ids in input order. Sort the rest by decreasing size then id. Place each in the first bin with room, or open a bin, including for a first zero-size item. Return {"bins": id lists,"remaining": free units per bin,"rejected": ids}. Do not mutate inputs.

  3. 3.Find the earliest maximum simultaneous reservation load

    Write resource_peak(reservations), [id,integer_start,integer_end,positive_integer_units] rows with start<end. Intervals are half-open and may overlap. Return {"peak": maximum simultaneous units,"at": earliest time attaining it}; empty input returns peak 0, at None. Combine all starts and ends at the same time before evaluating the following load. Do not count touching reservations as overlapping.

  4. 4.Find the first free nonpreemptive time slot

    Write earliest_slot(busy, now, duration). busy is unsorted integer [start,end) intervals with start<end, possibly overlapping; now is integer and duration positive integer. Return the smallest t>=now for which [t,t+duration) overlaps no busy interval. There is no upper horizon. Touching endpoints are allowed. Do not change busy.

  5. 5.Intersect availability calendars before applying duration

    Write common_windows(calendars, duration). Each calendar lists integer [start,end) availability intervals with start<end; input may be unsorted or touching. Return maximal intervals available in every calendar, sorted, keeping only those of length>=positive integer duration. Merge touching availability first. No calendars or any empty calendar returns []. Do not mutate inputs.

  6. 6.Allocate bounded integer quotas in alphabetical rounds

    Write quota_rounds(demand, budget). demand maps string tenants to nonnegative integer requested units; budget is a nonnegative integer. Start each allocation at zero. In alphabetical rounds, grant one unit to each still-unsatisfied tenant until budget is exhausted or all demands are met. Return every tenant's allocated units, including zeros. Do not redistribute by demand proportion.

  7. 7.Serve tenant queues in weighted consecutive bursts

    Write weighted_queues(queues, weights, limit). queues maps string tenants to job-id lists; weights has the same keys with positive integer burst sizes; limit>=0 is integer. Each round visits tenants alphabetically and pops up to that tenant's weight from its queue stopping after limit jobs or exhaustion. Return {"order":job ids,"remaining": copied queues}. Never wrap or repeat jobs.

  8. 8.Order tenants by their largest normalized resource share

    Write dominant_order(allocations, capacities). capacities is a list of positive integer resource capacities; allocations maps string tenants to equally wide nonnegative integer vectors. A tenant's dominant share is max(allocation_i/capacity_i), or 0 for zero-width vectors. Return [tenant,share] sorted by increasing exact share, then name. Report shares as numbers; do not allocate more resources.

  9. 9.Track refill and rejection without consuming absent tokens

    Write token_decisions(requests, capacity, refill, initial). requests is [id,time,cost] rows with nondecreasing integer times>=0 and integer costs>=0. capacity/refill/initial are nonnegative integers, initial<=capacity. Starting at time 0, refill by elapsed*refill capped at capacity per request. Accept iff cost fits and subtract only on acceptance. Return [id,accepted_bool,tokens_after] rows.

  10. 10.Enforce a fixed-grid request count limit

    Write fixed_window_limit(requests, width, cap). requests is [id,time] rows with nondecreasing integer times>=0; width is positive integer and cap nonnegative integer. Window index is time//width. Accept the first cap requests in each window; reject the rest without carrying counts across windows. Return {"accepted":ids,"rejected":ids}, each in input order. This is a fixed-grid limit.

  11. 11.Expire accepted requests at the rolling-window boundary

    Write sliding_window_limit(requests, width, cap). requests is [id,time] rows with nondecreasing integer times>=0; width>0 and cap>=0 are integers. Accept iff fewer than cap previously accepted requests have time>current_time-width. Then record the current acceptance. Rejected requests never consume capacity. Return {"accepted":ids,"rejected":ids} in input order. Same-time acceptances count.

  12. 12.Compute earliest task times without worker limits

    Write dependency_times(tasks). tasks maps string ids to [nonnegative_integer_duration, predecessor_ids]; every predecessor is a key. Tasks start after all predecessors finish; otherwise they start at time 0. Return {"times": id->[earliest_start,finish],"makespan": maximum finish or 0}. There is no worker limit. Ignore repeated predecessors. Return None for any dependency cycle.

  13. 13.Propagate latest starts from a supplied project deadline

    Write latest_slack(nodes, deadline). nodes maps string ids to [earliest_start,nonnegative_duration,successor_ids], with integer times and all successors declared. deadline>=earliest project finish. Latest finish is min(successor latest starts), or deadline for a sink; latest start subtracts duration. Return id->latest_start-earliest_start. Return None on any cycle; empty nodes returns {}.

  14. 14.Return complete ready waves without mixing generations

    Write dag_waves(predecessors), a dict mapping string task ids to lists of known predecessor ids. Repeatedly emit alphabetical tasks whose predecessors all finished before this wave. Finish the whole wave together, then discover the next. Return the wave lists, or None if any cycle prevents completion. Duplicate predecessor entries do not create extra dependencies. Empty input returns [].

  15. 15.Dispatch released jobs using earliest worker availability

    Write dispatch_jobs(jobs, workers). jobs is [unique_id,integer_release>=0,positive_integer_duration] rows; workers is positive integer, indexed from 0. Sort by release then input position. For each, choose the worker with earliest free time, ties by index; start=max(release,free_time), then update its finish. Initially all workers are free at 0. Return [id,worker,start,end] in processing order.

  16. 16.Protect a future head reservation while backfilling now

    Write safe_backfill(free, now, reserved_at, reserved_units, jobs). All are integers, reserved_at>=now and 0<=reserved_units<=free. jobs is [id,positive_duration,positive_units]. Scan in order; accepted jobs start now. Each must fit now; if ending after reserved_at, it must also leave reserved_units free then. End equality is safe. Return accepted/rejected ids, "free_now" and "free_at_reservation".

  17. 17.Select a maximum-cardinality nonoverlapping interval set

    Write interval_selection(jobs), [unique_string_id,integer_start,integer_end] rows with start<end. Sort by end, then start, then id; accept a job if its start is at least the last accepted end. Return selected ids in that order. Touching half-open intervals are compatible. This earliest-finish rule maximizes job count; do not choose by duration or original order. Empty input returns [].

  18. 18.Optimize interval value with deterministic subset ties

    Write weighted_intervals(jobs), [unique_string_id,integer_start,integer_end,nonnegative_integer_value] rows with start<end. Choose nonoverlapping half-open intervals maximizing total value. Ties prefer fewer jobs, then the lexicographically smallest sorted id list. Return {"value":total,"ids":sorted selected ids}. Empty selection is allowed; do not optimize cardinality before value.

  19. 19.Choose an exact two-resource value-maximizing subset

    Write resource_subset(jobs, cpu, memory). jobs has at most 16 [unique_string_id,cpu_need,memory_need,value] rows of nonnegative integers; capacities cpu/memory are nonnegative integers. Choose a subset fitting both totals and maximizing value. Ties prefer fewer jobs, then lexicographically smallest sorted ids. Return {"value":total,"ids":sorted ids}. Empty selection is allowed. Do not split a job.

  20. 20.Minimize explicit preemption penalties before job count

    Write preemption_plan(running, needed). running has at most 16 [unique_string_id,positive_integer_units,nonnegative_integer_penalty] rows; integer needed>=0. Choose a subset freeing at least needed units. Minimize (sum penalties, number of jobs, freed units, sorted id list) lexicographically. Return {"ids":sorted ids,"freed":units}, or None if impossible. needed=0 permits the empty subset.

  21. 21.Build a capped exponential retry timetable

    Write retry_times(start, base, cap, attempts). start is integer; base, cap and attempts are nonnegative integers. Attempt 0 occurs at start. Before attempt i>=1 wait min(cap,base*2^(i-1)) after the previous attempt time. Return exactly attempts timestamps, or [] for zero attempts. Cap applies even to the first wait. This deterministic schedule has no jitter.

  22. 22.Check a write against its exact lease token and interval

    Write lease_checks(leases, writes). leases maps resource strings to [integer_start,integer_end,integer_token], start<end. writes is [resource,token,integer_time] rows. Return one Boolean per write: True only for a known resource with the exact current token and start<=time<end. A matching token alone is insufficient. Preserve write order and do not mutate inputs.

  23. 23.Reclaim borrowed units while protecting tenant guarantees

    Write reclaim_borrowed(allocated, guarantees, needed). Dicts share string keys and nonnegative integer values; integer needed>=0. Reclaim unitwise from the tenant with largest current max(allocated-guarantee,0), ties by name. Stop after needed units or when no borrowing remains. Return {"reclaimed": all tenant counts,"remaining": new allocations,"unmet": units still needed}. Do not mutate inputs.

  24. 24.Choose the tightest fitting node with the required label

    Write typed_placement(nodes, jobs). nodes maps string names to [string_label,nonnegative_integer_free]; jobs is [unique_id,required_label,positive_integer_units] rows. Scan in order. Among matching-label nodes that fit, choose least free units after placement, ties by name. Place wholly there; otherwise reject. Return {"placed":[id,node] rows,"rejected":ids,"remaining": free units per node}.

  25. 25.Place replicas without repeating a group on a node

    Write anti_affinity_place(nodes, jobs). nodes maps string names to nonnegative integer free slots; jobs is [unique_id,string_group] rows. Each job needs one slot and cannot share a node with any earlier placed job of its group. Choose the eligible node with most free slots, ties by name. Reject if none fits. Return {"placed":[id,node] rows,"rejected":ids,"remaining": slot counts}, in job order.

  26. 26.Batch node drains while retaining one healthy replica

    Write drain_batches(nodes, replicas, limit). nodes lists unique string names; replicas lists nonempty subsets of nodes; limit>0 is integer. For each batch, scan remaining nodes alphabetically, adding a node if batch size<limit and every replica set retains a node outside the batch. Batches recover before the next. Stop if none fits. Return {"batches": lists,"blocked": remaining sorted nodes}.

  27. 27.Merge overloaded spans across time-varying capacity

    Write capacity_overloads(horizon, initial, changes, reservations). Times/units are integers; horizon/initial>=0. changes is unique [time,new_capacity] rows, capacity>=0, 0<=time<=horizon. Reservations are [start,end,positive_units] within [0,horizon], start<end. Return maximal [start,end,peak_excess] spans with load>capacity. Apply all changes at a time before its following half-open span.

  28. 28.Assign workers by the next positive marginal gain

    Write gain_allocation(gains, budget). gains maps service strings to nonincreasing lists of nonnegative integer marginal gains; budget>=0 is integer. Each worker takes that service's next gain. Repeatedly choose the largest available positive next gain, ties by service name, until budget or positive gains run out. Return {"allocations": worker counts for all services,"gain": summed selected gains}.

  29. 29.Find the first time shared by two periodic schedules

    Write aligned_time(p, a, q, b, earliest). Periods p/q are integers in 1..1000; offsets satisfy 0<=a<p and 0<=b<q; earliest>=0 is integer. Return the least integer t>=earliest satisfying t%p=a and t%q=b, or None if no shared time exists. Offsets describe repeating absolute-time grids, not delays measured from earliest.

  30. 30.Measure capacity after the worst permitted node losses

    Write failure_headroom(nodes, demand, tolerate). nodes maps string names to nonnegative integer capacities; demand/tolerate are nonnegative integers. Remove up to tolerate nodes with greatest capacity, ties by name, to model the least remaining capacity. Return {"available": remaining sum,"pass": available>=demand,"lost": removed names sorted}. If tolerate exceeds node count, remove all nodes.