Fill a weekly work schedule to an exact hour total
I was asked this
No reports yet. Sign in to say where you were asked it.
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) == 70 <= day_hours <= 80 <= 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 withday_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 thanday_hourstimes 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
