DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Range sum query 2D - Immutable

Problem

TC: O(n*m) for creating the prefix[][] sum matrix, O(row1+row2) for calculating the sum of the given rectangle
SC: O(n*m) for using the prefix[][] sum matrix

class NumMatrix {
    int prefix[][];
    public NumMatrix(int[][] matrix) {
        prefix = new int[matrix.length][matrix[0].length];
        for(int i=0;i<matrix.length;i++){
            int current = 0;
            for(int j = 0;j<matrix[0].length;j++){
                current+=matrix[i][j];
                prefix[i][j] = current;
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum =0;
        for(int i =row1;i<=row2;i++){
            int right = prefix[i][col2];
            int left = (col1>0) ? prefix[i][col1-1] : 0;
            sum+=right-left;
        }
        return sum;
    }
}

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * int param_1 = obj.sumRegion(row1,col1,row2,col2);
 */
Enter fullscreen mode Exit fullscreen mode
đź‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay