Given a n x n square matrix, find the sum of all sub-squares of size k x k17 Mar 2025 | 5 min read Problem Statement Given a square matrix of size n x n and an integer k, we need to find the sum of all sub-squares of size k x k within the matrix. For example, let's consider the following 4x4 matrix: If k is 2, we need to find the sum of all 2x2 sub-squares: Sub-square 1: Sum = 1 + 2 + 5 + 6 = 14 Sub-square 2: Sum = 2 + 3 + 6 + 7 = 18 ... and so on for all possible 2x2 sub-squares. Brute Force Approach One straightforward approach is to iterate through all possible sub-squares of size k x k and calculate their sums individually. This involves nested loops to traverse the matrix and compute the sum for each sub-square. While this approach is intuitive, it has a time complexity of O(n^4), making it inefficient for large matrices. Output: ![]() Time Complexity: The time complexity of the brute force approach is determined by the nested loops used to iterate over all possible sub-squares of size k x k within the n x n matrix. The nested loops structure leads to a time complexity of O((n - k + 1)^2 * k^2). The outer two loops iterate over (n - k + 1) rows and (n - k + 1) columns. The inner two loops iterate over the k x k sub-square. In the worst case scenario, when k is much smaller than n, the time complexity can be approximated to O(n^4). This is because the terms (n - k + 1)^2 and k^2 would contribute significantly compared to n^2. Approach 2 : Preprocessing for Efficient Computation We can significantly improve the efficiency of our algorithm by using a preprocessing technique that computes the cumulative sum matrix. The idea is to create a new matrix where each cell (i, j) holds the sum of all elements in the sub-matrix that starts at (0, 0) and ends at (i, j) in the original matrix. For example, given the matrix: The cumulative sum matrix would be Once we have the cumulative sum matrix, we can efficiently calculate the sum of any sub-square by utilizing the sums of its corner elements. Efficient Approach Compute Cumulative Sum Matrix: Iterate through the original matrix and build the cumulative sum matrix. Calculate Sub-Square Sum: For each sub-square (i, j) of size k x k, calculate its sum using the cumulative sum matrix: Here, cumSum[i+k][j+k] is the sum of the sub-matrix from (0, 0) to (i+k, j+k), and the other terms exclude the portions that are not part of the sub-square. Output: ![]() The key operations contributing to this time complexity are: Building Cumulative Sum Matrix: The nested loops used to iterate through the entire matrix and calculate the cumulative sum at each cell take O(n^2) time. Calculating Sub-Square Sums: The nested loops used to iterate through all possible sub-squares of size k x k take O((n - k + 1)^2) time. Since 'k' is typically smaller than 'n', the term (n - k + 1)^2 is dominated by the n^2 term, making the overall complexity O(n^2). In summary, the time complexity of the code is O(n^2), which is a significant improvement over the brute force approach with a higher time complexity of O(n^4) for larger matrices and sub-square dimensions. Next TopicInplace MxN size matrix transpose |
Check if any anagram of a string is palindrome or not
Problem statement: Here, we have given an input string, and we have to find if there is any anagram of the given string available which is a palindrome or not? If it is, then it returns true; otherwise, it will return false. What is an Anagram string? If we...
5 min read
Binary Indexed Tree Range Updates and Point Queries
Introduction: In this article, we are going about the Range Updates and Point Queries of Binary Indexed Tree. But before that, we have to know what a binary index tree is. We can say that a binary index tree is a type of data structure that helps us...
8 min read
Implementation of Deque by Circular Array
Before going to the implementation of Deque using the circular array, first, let's understand what a queue is? A queue is an orderly collection of items in which new items are added at one end, referred to as the "back", and current items are removed at the...
16 min read
Largest Number After Digit Swaps By Parity
Problem Statement: We are given a positive integer num. We may swap any two digits of num that have the same parity (i.e., both odd digits or both even digits). Return the largest possible value of num after any number of swaps. Java Approach Using Brute Force import java....
5 min read
Arrange Consonants and Vowels in a linked list
Introduction: Linked lists are fundamental data structures in computer science that allow for efficient organization and manipulation of data. While they are commonly used to represent sequences of elements, such as numbers or strings, the arrangement of consonants and vowels in a linked list introduces an interesting...
8 min read
Recaman's Sequence
, named after the Colombian mathematician Bernardo Recaman Santos, is a fascinating integer sequence that has captured the imagination of mathematicians and computer scientists alike. It's defined by a simple yet intriguing rule, making it an excellent Java exploration topic. Understanding Recamán's Sequence starts with the first...
6 min read
Print all words matching a pattern in CamelCase Notation Dictionary
Introduction: A person's ability to comprehend text accurately and efficiently has become crucial in a world where technology and data are driving change. Finding terms in a CamelCase Notation Dictionary that fit a given pattern is an interesting challenge in this field. Writing compound words or phrases...
4 min read
Checking for the Mirror Images in the Binary Trees
Checking mirror images in the binary tree tends to be an interesting problem that emerges in various applications such as computer graphics, data analysis, and algorithm design. This involves that we have to compare the structure and values of the two binary trees to verify or...
5 min read
Remove extra edge from a BST
Introduction: Binary Search Trees (BSTs) are robust data structures that are frequently utilized for effective retrieval and searching tasks. On the other hand, more edges can occasionally cause a BST to become imbalanced. Maintaining a BST's equilibrium is essential to maximizing functions like insertion and searching. This...
4 min read
Inorder Tree Traversal without Recursion
A binary tree's nodes can be visited in a precise order using a technique called norder tree traversal. Nodes are accessed in the following order during this traversal: left child, root, then right child. Because you visit the left child "in" between visiting the root and...
4 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India

