← Questions

Fill a weekly work schedule to an exact hour total

0
SnowflakeCoding

A coding interview question asked at Snowflake. It tests backtracking, strings and combinatorics.

A week's work plan is written as a 7-character string pattern, one character per day. A digit (0-9) is a day whose hours are already set. A ? is a day that is still open.

Implement:

def find_schedules(work_hours: int, day_hours: int, pattern: str) -> list[str]

Replace every ? with a digit from 0 to day_hours so that the seven digits sum to exactly work_hours. Return every valid schedule as a 7-character string, in ascending lexicographic order. Return an empty list if none exists. Digits already in the pattern never change.

Constraints

  • len(pattern) == 7
  • 0 <= day_hours <= 8
  • 0 <= work_hours <= 56

Example 1

work_hours = 24, day_hours = 4, pattern = "08??840"
-> ["0804840", "0813840", "0822840", "0831840", "0840840"]

The fixed days sum to 20, so the two open days must share 4 hours, each at most 4.

Example 2

work_hours = 10, day_hours = 3, pattern = "1111111"
-> []

There are no open days and the fixed days sum to 7, not 10.

Clarifying questions

  • Can a fixed digit be larger than day_hours? (Example 1 has an 8 with day_hours = 4, so fixed days are kept as given.)
  • Is "ascending lexicographic order" plain string order? (With equal-length digit strings, yes.)
  • With no ?, should the function return [pattern] when its sum already matches?

What a strong answer covers

  • Sums the fixed days first and works out the hours still needed. Returns [] at once when that number is negative or more than day_hours times the number of open days.
  • Backtracks over the open days left to right, trying digits from 0 up to day_hours, so results come out already sorted.
  • Prunes a branch when the remaining hours cannot fit the remaining open days (too many, or negative).
  • Notes that the output itself can be large (up to 9^7 strings when every day is open), so the cost is driven by the output.
  • Tests both examples, day_hours = 0, and a pattern of seven ?.

Follow-ups

  • Return only the number of schedules, with a DP over days and hours, without listing them.
  • Each day has its own maximum, or a minimum as well.
  • Return the k-th schedule in order without generating the ones before it.

Where it's asked

What it tests

backtracking · strings · combinatorics

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding