What would be an efficent way to solve the following problem?
Given an NxN matrix of natural numbers, return ALL positions (matrix indexes, i and j) whose number is bigger than all their adjacent positions (horizontal and vertical only, if position is out of the matrix it counts as -1).
In other words, matrix[i][j] has to be bigger than all of the following:
matrix[i+1][j], matrix[i-1][j], matrix[i][j+1], matrix[i][j-1]
If matrix[i][j] fulfilled the condition then (i,j) is a valid position.
Is there any way to solve this without checking every single cell and making all 4 comparisons?
Related
You are given a grid of 0's and 1's and it's dimension 1 ≤ N,M ≤ 2500 and a number 0 ≤ K ≤ 6. The task is to count the number of rectangles in the grid that have exactly K ones inside it.
It has to be quicker that O(N^2*M), something like O(NMlog(N+M)) will work. My best aproach was a dp with complexity O(N^2*M), but this is to slow, I've been told that the answer is divide and conquer but I can't get it. Any idea?
One way to get the log factor is to divide horizontally, add the number of rectangles with K 1s above the dividing line, the number of rectangles with K 1s below the dividing line (computed recursively), and for each horizontal width, (there are O(|columns|^2) of them) the number of rectangles that extend some part above and some part below the divided line with the same fixed width. We compute the last one by splitting into two-part partitions of K (maxed at 7 since K ≤ 6 and we may want one part zero). We can binary search on a fixed width and bottom or top line, up or down, on matrix prefix sums, which we can precalculate in O(M * N) and retrieve in O(1).
f(vertical_range) =
f(top_part) +
f(bottom_part) +
NumTopRecs(w, i) * NumBottomRecs(w, k - i)
where i <- [0...k],
w <- all O(M^2) widths
The trick is that in each recursive call, we rotate the half that's passed to f such that the horizontal divider line becomes vertical, which means we've cut the M for our call (from which we draw O(M^2) widths) in 2.
Suppose I have a nxn coulmn stochastic matrix. If I multiply it by a vector of length n that has elements that sum to one I get a resultant vector of length n that again sums to one Why does this happen? What if I give the vector of lenght n sum =0.8 or some 1.2?
Edit:
What happens if one of the columns of the matrix dosent add up to 1?
Consider matrix B=4x4 and vector A=4x1. Now when we are calculating the output vector sum it can be broken as
a1*(b11+b21+b31+b41)+a2*(b12+b22+b32+b42)+a3*(b13+b23+b33+b43)+a4*(b14+b24+b34+b44)
Now since all columns sum to 1 since it's column stochastic the
sum=a1*1+a2*1+a3*1+a4*1=1
since the vector was 1. Now if one of the cols is not 1 we will have that column's contribution reduced for the jth entry of vector A. For eg. if
b13+b23+b33+b43=0.8
then
sum=a1*1+a2*1+a3*(0.8)+a4*1=a1*1+a2*1+a3*1+a4*1 -0.2*a3
So there is a leak of -0.2a*3 from the original sum of 1
Input:
Table T of length N (N <= 10000) containing 32-bit integers. Each integer denotes length and direction of consecutive edge of polygon on a square grid (every vertex has integer coordinates). If integer is positive, it means edge goes up or right. If integer is negative, edge goes down or left. Edges are perpendicular to its neighbors. Edges do not intersect nor overlap with each other. Vertices do not overlap with each other.
Examplary input T:
2, -3, -1, 1, -1, 2
Represents two polygons (it doesn't matter which one we will choose):
Arrows denote
first edge corresponding to the first 2 in T.
Output:
Integer denoting surface area of given polygon. For exemplary input, the output should be 5.
Desired time complexity: O(N)
Desired memory complexity (not counting input): O(1)
Can you present such algorithm and rationale behind it?
Algorithm:
int area(int[] T) {
int area = 0;
int x = 0;
for (int i = 0; i < T.length; i += 2) {
x += t[i];
area += x * t[i + 1];
}
return Math.abs(area);
}
Description:
Our polygon is closed in a big rectangle. Based on this we are counting areas of small rectangles which are building our shape - rectangles which are inside polygon as well as rectangles which are outside (with opposite sign).
It doesn't matter from which vertex in polygon we are starting.
In the beginning we need one based line from which we will count vertical (it can be horizontal as well, it doesn't matter) translation of vertices.
We are getting the first number - it will tell us, how much from the based line our first vertex is moved. The second number is translation according to second coordinate. By multiplying this pair we are getting the first rectangle in our sum.
Second rectangle is described by third and fourth point:
the third number added to the first number is a vertical translation of the vertex
the fourth number is a horizontal translation of the vertex.
Multiplying this points is giving us the second rectangle.
We are continuing to do this for the rest of numbers in table. We are adding areas of rectangles. The result is an absolute value of the sum.
Given a 15*15 symmetric matrix, each row containing all the numbers from 1 to 15 and each column containing all the numbers from 1 to 15, how do you go on to prove that all the diagonal elements will be different?
I tried to prove that no two diagonal elements will be same, but couldn't come up with anything solid. Even tried it for 5*5 matrix, but nothing I could come up with to prove it.
Any help would be appreciated!
This is a problem of symmetric latin squares. The first observation (which requires a short proof) is that each of the numbers 1 to 15 occur an even number of times in the off-diagonal positions. Since 15 is odd, this means that each number must occur at least once in the diagonal positions. But there are only 15 diagonal positions and so each number must occur exactly once in the diagonal positions.
If by 'prove' you mean demonstrate for a particular matrix, see below. If by 'prove' you mean mathematically prove, well, all diagonal matrices are symmetric matrices, and a diagonal matrix isn't required to have unique elements, so not all symmetric matrices have unique elements on the diagonal.
One way to test a particular matrix is to make a new array containing all the diagonal elements, then eliminate duplicates in that array, and test the length. Another is to take each diagonal element and compare it against those elements on the diagonal with a higher index. Here's the latter with some pseudocode using 0 based arrays
unique = TRUE
for i = 0 to 14 {
value = matrix[i][i]
for j = i+1 to 14 // doesn't loop if i+1 > 14
if (value == matrix[j][j])
unique = FALSE
}
ADDED: The OP points out I missed the restriction on the contents of each row and column! All symmetric NxN matrices consisting of N unique values with no duplicated values in each row and column must have an antidiagonal consisting of only one value, by the definition of symmetry. If N is odd, the resulting matrix has a single element that is in both the diagonal and antidiagonal (and of course, if N is even, no element is in common). Given this, you can see the diagonal values must differ in each position from the antidiagonal, except in the common element. Combine that with the requirement that each row and each column has N values, and you'll see that the diagonal element must be different for each row. This isn't formal, but I hope it helps.
We can assume the given matrix is m * m, and we should fill the matrix with m distinct numbers: N1, N2 ... Nm.
Because each element should show up in each column/row once, for each number, it will show up n) times in the matrix.
Because it is symmetric, each number will show up x (even) times in the upper section above the diagonal or x (even) times in the lower section below the diagonal. In this way, in addition to the diagonal, each number will show up 2 * x (x is even) times in the matrix.
Therefore, if the given m is odd, each number should show up one more time in the diagonal; if the given is even, we don't require each number show up on the diagonal cause 2 * x is already even.
We are given an N dimensional matrix of order [m][m][m]....n times where value position contains the value sum of its index..
For example in 6x6 matrix A, value at position A[3][4] will be 7.
We have to find out the total number of counts of elements greater than x. For 2 dimensional matrix we have following approach:
If we know the one index say [i][j] {i+j = x} then we create a diagonal by just doing [i++][j--] of [i--][j++] with constraint that i and j are always in range of 0 to m.
For example in two dimensional matrix A[6][6] for value A[3][4] (x = 7), diagonal can be created via:
A[1][6] -> A[2][5] -> A[3][4] -> A[4][3] -> A[5][2] -> A[6][2]
Here we have converted our problem into another problem which is count the element below the diagonal including the diagonal.
We can easily count in O(m) complexity instead spending O(m^2) where 2 is order of matrix.
But if we consider N dimensional matrix, how we will do it, because in N dimensional matrix if we know the index of that location,
where sum of index is x say A[i1][i2][i3][i4]....[in] times.
Then there may be multiple diagonal which satisfy that condition, say by doing i1-- we can increment any of {i2, i3, i4....in}
So, above used approach for 2 dimensional matrix become useless here... because there is only two variable quantity i1 and i2 is present.
Please help me to find solution
For 2D: count of the elements below diagonal is triangular number.
For 3D: count of the elements below diagonal plane is tetrahedral number
Note that Kth tetrahedral number is the sum of the first K triangular numbers.
For nD: n-simplexial (I don't know exact english term) number (is sum of first (n-1)-simplexial numbers).
The value of Kth n-simplexial is
S(k, n) = k * (k+1) * (k+2).. (k + n - 1) / n! = BinomialCoefficient(k+n-1, n)
Edit: this method works "as is" for limited values of X below main anti-diagonal (hyper)plane.
Generating function approach:
Let's we have polynom
A(s)=1+s+s^2+s^3+..+s^m
then it's nth power
B(s) = An(s) has important property: coefficient of kth power of s is the number of ways to compose k from n summands. So the sum of nth to kth coefficients gives us the count of the elements below kth diagonal
For a 2-dimensional matrix, you converted the problem into another problem, which is count the elements below the diagonal including the diagonal.
Try and visualize it for a 3-d matrix. In case of a 3-dimensional matrix, the problem will be reduced to another problem, which is to count the elements below the diagonal plane including the diagonal