Skip to content

Commit b18b63e

Browse files
authored
Added #195
1 parent fa51b6a commit b18b63e

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
#195
3+
Google
4+
5+
Let A be an N by M matrix in which every row and every column is sorted.
6+
7+
Given i1, j1, i2, and j2, compute the number of elements of M smaller than M[i1, j1] and larger than M[i2, j2].
8+
9+
For example, given the following matrix:
10+
11+
[[1, 3, 7, 10, 15, 20],
12+
[2, 6, 9, 14, 22, 25],
13+
[3, 8, 10, 15, 25, 30],
14+
[10, 11, 12, 23, 30, 35],
15+
[20, 25, 30, 35, 40, 45]]
16+
17+
And i1 = 1, j1 = 1, i2 = 3, j2 = 3, return 15 as there are 15 numbers in the matrix smaller than 6 or greater than 23.
18+
19+
"""
20+
21+
# Uncomment all print statements to see the valid upper and lower bound elements and their respective count
22+
def countElements(matrix, upperBound, lowerBound):
23+
N = len(matrix)
24+
M = len(matrix[0])
25+
26+
upperBoundCount = 0
27+
lowerBoundCount = 0
28+
29+
# print("Upper bound elements: ", end = " ")
30+
for i in range(N):
31+
if matrix[i][0] >= upperBound:
32+
break
33+
else:
34+
# print(matrix[i][0], end = " ")
35+
upperBoundCount += 1
36+
37+
for j in range(1, M):
38+
if matrix[i][j] >= upperBound:
39+
break
40+
# print(matrix[i][j], end = " ")
41+
upperBoundCount += 1
42+
43+
# print("\nLower Bound Elements: ", end = " ")
44+
for i in range(N-1, -1, -1):
45+
if matrix[i][M-1] <= lowerBound:
46+
break
47+
else:
48+
# print(matrix[i][M-1], end = " ")
49+
lowerBoundCount += 1
50+
51+
for j in range(M-2, -1, -1):
52+
if matrix[i][j] <= lowerBound:
53+
break
54+
# print(matrix[i][j], end = " ")
55+
lowerBoundCount += 1
56+
57+
# print("\nUpper Bound Count:", upperBoundCount, "\nLower Bound Count:", lowerBoundCount)
58+
return upperBoundCount + lowerBoundCount
59+
60+
61+
def main():
62+
matrix = [
63+
[1, 3, 7, 10, 15, 20],
64+
[2, 6, 9, 14, 22, 25],
65+
[3, 8, 10, 15, 25, 30],
66+
[10, 11, 12, 23, 30, 35],
67+
[20, 25, 30, 35, 40, 45]
68+
]
69+
70+
i1 = 1
71+
j1 = 1
72+
73+
i2 = 3
74+
j2 = 3
75+
76+
upperBound = matrix[i1][j1]
77+
lowerBound = matrix[i2][j2]
78+
79+
print(countElements(matrix, upperBound, lowerBound))
80+
81+
if __name__ == "__main__":
82+
main()

0 commit comments

Comments
 (0)