Katkat

Implement Byte Formatting and Cafeteria Billing

UpstartSoftware Engineer · Online Assessment

Last updated

This problem tests your ability to implement custom string formatting logic for file sizes and a stateful simulation of a billing system with capacity limits.

Part 1: Byte Formatter

Write a function format_bytes(n) that converts an integer representing bytes into a human-readable string. Use the following suffixes: '', 'KB', 'MB', 'GB'. Each unit is a factor of 1024. Return the value rounded to 2 decimal places, removing trailing zeros and the decimal point if it's a whole number.

Example:

  • format_bytes(500) -> "500"
  • format_bytes(2048) -> "2 KB"
  • format_bytes(10485760) -> "10 MB"

Part 2: Cafeteria Billing

You are simulating a cafeteria line. The cafeteria has a fixed capacity of seats. You are given a list of events where each event is a tuple: (timestamp, person_id, action).

  • 'enter': The person tries to sit down. If current_seats < capacity, they enter and pay a one-time fee of $5. If full, they leave (ignore).
  • 'exit': The person leaves, freeing up a seat.

Write a function calculate_billing(events, capacity) that returns a dictionary mapping person_id to their total fees paid. Only charge a fee if the user successfully occupies a seat.

Constraints:

  • events are sorted by timestamp.
  • capacity > 0.
  • A person cannot 'enter' if they are already inside, and cannot 'exit' if they are not inside.

Hints

Hint 1

For byte formatting, use a loop or logarithmic calculation to determine the magnitude and apply division by powers of 1024.

Hint 2

For string formatting, use string manipulation or formatting patterns to strip unnecessary decimal zeros while keeping exactly two places when needed.

Hint 3

For the billing simulation, maintain a 'set' of currently seated users to validate actions and a dictionary to track accumulated costs.

Follow-up questions

  • How would you modify the byte formatter to support 'TB' and 'PB' suffixes?
  • What changes are needed if the cafeteria has a 'membership' status that waives the $5 fee for certain users?
  • How would you handle concurrent events if multiple people arrive at the exact same timestamp?