- 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
- 39 lines of Java from the credited upstream file 3548.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 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 boolean canPartitionGrid(int[][] grid) {3 final long sum = Arrays.stream(grid).flatMapToInt(Arrays::stream).asLongStream().sum();4 return canPartition(grid, sum) || canPartition(reversed(grid), sum) ||5 canPartition(reversed(transposed(grid)), sum) || canPartition(transposed(grid), sum);6 }7 8 private boolean canPartition(int[][] grid, long sum) {9 long topSum = 0;10 Set<Integer> seen = new HashSet<>();11 for (int i = 0; i < grid.length; ++i) {12 topSum += Arrays.stream(grid[i]).asLongStream().sum();13 final long botSum = sum - topSum;14 Arrays.stream(grid[i]).forEach(seen::add);15 if (topSum - botSum == 0 || topSum - botSum == grid[0][0] ||16 topSum - botSum == grid[0][grid[0].length - 1] || topSum - botSum == grid[i][0])17 return true;18 if (grid[0].length > 1 && i > 0 && seen.contains((int) (topSum - botSum)))19 return true;20 }21 return false;22 }23 24 private int[][] transposed(int[][] grid) {25 int[][] res = new int[grid[0].length][grid.length];26 for (int i = 0; i < grid.length; ++i)27 for (int j = 0; j < grid[0].length; ++j)28 res[j][i] = grid[i][j];29 return res;30 }31 32 private int[][] reversed(int[][] grid) {33 return Arrays.stream(grid).collect(Collectors.collectingAndThen(Collectors.toList(), list -> {34 Collections.reverse(list);35 return list.toArray(new int[0][]);36 }));37 }38}39