- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 50 lines of Java from the credited upstream file 1240.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int tilingRectangle(int n, int m) {3 return tilingRectangle(n, m, 0, new int[m]);4 }5 6 private static final int BASE = 13;7 private Map<Long, Integer> dp = new HashMap<>();8 9 private int tilingRectangle(int n, int m, long hashedHeights, int[] heights) {10 if (dp.containsKey(hashedHeights))11 return dp.get(hashedHeights);12 13 final int minHeight = Arrays.stream(heights).min().getAsInt();14 if (minHeight == n) 15 return 0;16 17 int ans = m * n;18 int start = -1;19 20 for (int i = 0; i < m; ++i)21 if (heights[i] == minHeight) {22 start = i;23 break;24 }25 26 27 for (int sz = 1; sz <= Math.min(m - start, n - minHeight); ++sz) {28 29 if (heights[start + sz - 1] != minHeight)30 break;31 32 for (int i = start; i < start + sz; ++i)33 heights[i] += sz;34 ans = Math.min(ans, tilingRectangle(n, m, hash(heights), heights));35 for (int i = start; i < start + sz; ++i)36 heights[i] -= sz;37 }38 39 dp.put(hashedHeights, 1 + ans);40 return 1 + ans;41 }42 43 private long hash(int[] heights) {44 long hashed = 0;45 for (int i = heights.length - 1; i >= 0; --i)46 hashed = hashed * BASE + heights[i];47 return hashed;48 }49}50