Cube Summation

  • + 1 comment

    Python 3 Just maintains a sparse representation through a dict, and iterates over entries checking they are within the bounds for each QUERY. Seems like this is only one conceptual step above the naive solution. Why is this in week 13? Is it harder in some languages?

    def cubeSum(n, operations):
        matrix = {}
        results = []
        for op in operations:
            oplist = op.strip().split()
            optype, data = oplist[0], tuple(int(x) for x in oplist[1:])
            
            if (optype == 'UPDATE') and (not data[-1] == 0):
                matrix[data[:-1]] = data[-1]
            else:
                result = 0
                x1, y1, z1, x2, y2, z2 = data
                for coord, value in matrix.items():
                    x, y, z = coord
                    if (x >= x1) and (x <= x2) and (y >= y1) and (y <= y2) and (z >= z1) and (z <= z2):
                        result += value
                results.append(result)
        return results