Java solution using HashMap


  • 0
    public class Solution {
        public int leastBricks(List<List<Integer>> wall) {
            Map<Integer, Integer> bricksEndingAtMap = new HashMap<>();
            for(List<Integer> row : wall) {
                int runningWidthSum = 0;
                for(int i = 0; i < row.size() - 1; i++) { //exclude last brick
                    runningWidthSum += row.get(i);
                    Integer bricksEndingAt = bricksEndingAtMap.get(runningWidthSum);
                    if(bricksEndingAt == null) {
                        bricksEndingAtMap.put(runningWidthSum, 1);
                    }
                    else {
                        bricksEndingAtMap.put(runningWidthSum, bricksEndingAt + 1);
                    }
                }
            }
            int maxBrickEndsLinedUp = 0;
            for(int brickEndsLinedUp : bricksEndingAtMap.values()) {
                maxBrickEndsLinedUp = Math.max(maxBrickEndsLinedUp, brickEndsLinedUp);
            }
            int wallHeight = wall.size();
            int minCrossings = wallHeight - maxBrickEndsLinedUp;
            
            return minCrossings;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.