google phone screen | passed | dec 2024 | L4 | Bangalore
Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2024-12-11Added By Anonymous
Source:Ā Link
š§ Experience: The candidate solved the problem efficiently.
ā
Outcome: passed
š° Compensation: unknown
š Location: Bangalore
š¢ Company: Google
š Education: unknown
š Benefits: unknown
š
Offer Date: Dec 2024
Problem: You are given a grid of size r Ć c and n objects located at specific coordinates. You need to find the number of axis-parallel rectangular subgrids that contain at least k of these objects. Two rectangles are considered different if their coordinates are different.
Problem: You are given a grid of size r Ć c and n objects located at specific coordinates. You need to find the number of axis-parallel rectangular subgrids that contain at least k of these objects. Two rectangles are considered different if their coordinates are different.
def count_rectangles(r: int, c: int, n: int, k: int, positions: List[Tuple[int, int]]) -> int:
eg. 1
r = 2
c = 2
n = 1
k = 1
positions = [(1, 2)]
ans: 4
r = 3
c = 2
n = 3
k = 3
positions = [(1, 1), (3, 1), (2, 2)]
ans: 1
r = 3
c = 2
n = 3
k = 2
positions = [(1, 1), (3, 1), (2, 2)]
ans: 4
was able to solve efficiently
function count_rectangles(n, m, c, k, positions):
Initialize ans to 0
// Iterate through each row as the starting point
for i from 0 to n-1:
// Initialize arrays to store left, right, count, and to values
Initialize l, r, cnt, to as arrays of size (m + 2)
// Count occurrences of objects in each column
for x from i to n-1:
for y in positions[x]:
Increment cnt[y]
// Find the left and right bounds for the current row
last = 0
for j from 1 to m:
if cnt[j] > 0:
l[j] = last
r[last] = j
last = j
r[last] = m + 1
l[m + 1] = last
// Initialize the result for the current configuration
res = 0
// Process the rectangles starting at position 0
for i = r[0], j = 0, s = 0; i <= m; i = r[i]:
while j <= m and s < k:
j = r[j]
s += cnt[j]
res += (i - l[i]) * (m + 1 - j)
to[i] = j
s -= cnt[i]
// Define the remove function for updating counts
function remove(x):
i = x
while l[i] > 0 and to[l[i]] >= x:
i = l[i]
Decrement cnt[x]
for j from l[i] to x:
while j <= m and s < k:
j = r[j]
s += cnt[j]
res -= (i - l[i]) * (j - to[i])
to[i] = j
s -= cnt[i]
if cnt[x] == 0:
l[r[x]] = l[x]
r[l[x]] = r[x]
// Iterate backwards from the last row to the starting row
for d from n-1 down to i:
ans += res
for x in positions[d]:
Call remove(x)
Return ans