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 |
Binary Tree: There can be a maximum of two children for each parent in a binary tree, which is a non-linear data structure of the tree type. Every node in a binary tree has a left and right reference in addition to the data element. The node at...
7 min read
Introduction: Binary trees are fundamental data structures in computer science that organize data in a hierarchical manner. They consist of nodes, each having at most two children - a left child and a right child. Understanding and manipulating binary trees is crucial in various applications, and one...
8 min read
We are given an array of n elements, and we have to find that element in the array, which divides the array into two parts in such a way, that the sum of both subarrays is equal. Basically, the sum of the left side and the...
6 min read
Introduction: Dynamic data structures play a vital role in computer science by enabling efficient manipulation and querying of changing datasets. Dynamic Segment Trees and Poly Hash Tables offer a powerful combination for handling dynamic range queries on large datasets. Dynamic Segment Trees: Dynamic Segment Trees provide a flexible structure...
8 min read
Introduction Within the larger class of subarray sum problems, the problem is a difficult algorithmic task. The objective is to determine the K-th largest sum among an array's potential contiguous subarrays. This issue has a wide range of applications in fields where it's critical to find...
9 min read
Introduction Data can be sorted and organized using Binary Search Trees, a basic data structure in computer science. Checking for similarities between two trees is a frequently done procedure on BSTs. It is a type of hierarchical data structure made up of nodes, with the left...
4 min read
Two arrays, arr1[0..m-1] and arr2[0..n-1], are provided. Determine whether or whether arr2[] is a subset of arr1[]. The two arrays are not ordered in any way. It is possible to assume that each element in both arrays is unique. EXAMPLES Example-1 arr1[] = {11, 1, 13, 21, 3, 7},...
10 min read
Search Question Auto Complete, otherwise called auto-propose or look-through ideas, is an element usually found in web search tools and sites that help clients form their pursuit questions. At the point when a client starts composing in the hunt bar, the framework predicts and shows a...
7 min read
Introduction Several issues concerning graphs involve paths manipulation to meet given specifications. For example, reordering the routes within a directed graph such as city zero which commands all paths. Traffic management and network routing amongst others practical applications have been illustrated in this book. This article will...
9 min read
Introduction This article will examine an effective Python algorithm to identify the "k" numbers that appear the most frequently in an array. Finding the elements with the highest frequency is a common data analysis challenge with a variety of uses, including identifying popular e-commerce items, studying user...
7 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