06. Letters Collection
The problem can be found at the following link: Question Link
My Approach
To solve this problem, I just found the left, right, up, and down boundaries for the given cell and then added the elements present in those boundaries.
To do so I follow these steps
Initialize an empty vector called
out
to store the results.For each query, iterate through the cells in the matrix within a 'hop' distance from the given coordinates
(x, y
).For each cell
(i, j)
within thehop
distance, check if it is within the boundaries of the matrix(i.e., i >= 0, i < n, j >= 0, and j < m)
.If the conditions are met, add the values of the matrix cells at
(i, y - hop)
and(i, y + hop)
to thesum
ifj
is within bounds. Similarly, add the values of the matrix cells at(x - hop, j)
and(x + hop, j)
to thesum
if i is within bounds.Append the
sum
to theout
vector for the current query. Return theout
vector containing the results for all queries.
Time and Auxiliary Space Complexity
Time Complexity:
O(q * (hop^2))
whereq
is the number of queries and 'hop' is the hop distance.Auxiliary Space Complexity: The auxiliary space is used to store the results in the out vector, which takes
O(q)
space.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated