KatInterview

Count Tile-Filling Combinations for a Target Length

Dynamic ProgrammingAuto-graded · 26 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingcombinatoricsunbounded-knapsack

Last updated

Tests unbounded-knapsack DP by counting unordered multisets of tile widths, drawn from a given list, that sum exactly to a target corridor length.

Problem Statement

You are tiling a narrow corridor of integer length corridor_len. A list tile_sizes gives the available tile widths. Every tile width in the list may be used an unlimited number of times.

Two fillings are considered the same combination if and only if they use exactly the same multiset of tile widths; the physical order the tiles are laid down does not matter. For example, placing widths [2, 1] and [1, 2] is one combination, not two.

Write a function that returns the total number of distinct combinations of tile widths from tile_sizes that sum exactly to corridor_len. Return 0 if no such combination exists.

Parameters

NameTypeDescription
corridor_lenintTotal length to fill.
tile_sizesList[int]Available tile widths, one entry per tile type.

How duplicate entries in tile_sizes are handled

If the same width appears more than once in tile_sizes, treat each occurrence as a separate pass over the DP table — do not deduplicate the list before processing. This matches the expected outputs in the test cases below.

Constraints

  • 1 <= len(tile_sizes) <= 300
  • 1 <= tile_sizes[i] <= 5000
  • 0 <= corridor_len <= 5000
  • Each width in tile_sizes may be reused an unlimited number of times within a single combination.
  • Order within a combination is irrelevant; only the multiset of widths matters.

Edge Cases

  • If corridor_len is 0, return 1. There is exactly one valid combination: the empty selection (no tiles placed).
  • If corridor_len is greater than 0 and no combination of the given widths sums to it, return 0.
  • Any tile width that exceeds corridor_len cannot contribute to any valid combination and is effectively skipped.

Examples

Example 1

Input: count_tile_combinations(5, [1, 2, 5])

Output: 4

Example 2

Input: count_tile_combinations(3, [2])

Output: 0

Example 3

Input: count_tile_combinations(0, [1, 2, 5])

Output: 1

Example 4

Input: count_tile_combinations(10, [2, 5, 3, 6])

Output: 5

Hints

Hint 1

Define dp[i] as the number of distinct tile multisets summing to length i, built from the widths seen so far. Pin down dp[0] before worrying about the rest.

Hint 2

To ensure a multiset is counted exactly once, tile widths must be the outer loop. Think about what goes wrong if you put the target lengths on the outside instead.

Hint 3

Inside each tile's pass, sweep i upward from that tile's width to corridor_len. When you read dp[i - tile] during this sweep, it has already been updated by the current tile — what does that imply about how many times the current width can appear in a combination?