Deleting element and getting it's neighbours - algorithm

I have got a sequence 1 2 3 4 5 6 ... n. Now, I am given a sequence of n deletions - each deletion is a number which I want to delete. I need to respond to each deletion with two numbers - of a left and right neighbour of deleted number (-1 if any doesn't exists).
E.g. I delete 2 - I respond 1 3, then I delete 3 I respond 1 4 , I delete 6 I respond 5 -1 etc.
I want to do it fast - linear of linear-logarithmic time complexity.
What data structure should I use? I guess the key to the solution is the fact that the sequence is sorted.

A doubly-linked list will do fine.
We will store the links in two arrays, prev and next, to allow O(1) access for deletions.
First, for every element and two sentinels at the ends, link it to the previous and next integers:
init ():
for cur := 0, 1, 2, ..., n, n+1:
prev[cur] := cur-1
next[cur] := cur+1
When you delete an element cur, update the links in O(1) like this:
remove (cur):
print (num (prev[cur]), " ", num (next[cur]), newline)
prev[next[cur]] := prev[cur]
next[prev[cur]] := next[cur]
Here, the num wrapper is inserted to print -1 for the sentinels:
num (cur):
if (cur == 0) or (cur == n+1):
return -1
else:
return cur
Here's how it works:
prev next
n = 6 prev/ print 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
/next ------------------- -------------------
init () -1 0 1 2 3 4 5 6 1 2 3 4 5 6 7 8
remove (2) 1 3 1 3 -1 0 1 3 4 5 6 1 3 4 5 6 7 8
remove (3) 1 4 1 4 -1 0 1 4 5 6 1 4 5 6 7 8
remove (6) 5 7 5 -1 -1 0 1 4 5 1 4 5 7 8
remove (1) 0 4 -1 4 -1 0 4 5 4 5 7 8
remove (5) 4 7 4 -1 -1 0 4 4 7 8
remove (4) 0 7 -1 -1 -1 0 7 8
Above, the portions not used anymore are blanked out for clarity.
The respective elements of the arrays still store the values printed above them, but we no longer access them.
As Jim Mischel rightly noted (thanks!), storing the list in two arrays instead of dynamically allocating the storage is crucial to make this O(1) per deletion.

You can use a binary search tree. Deleting from it is logarithmic. If you want to remove n elements and the number of total elements is m, then the complexity of removing n elements from it will be
nlogm

Related

Maximum k such that A[0]<A[k], A[1]<A[k+1], ..., A[k-1]<A[2*k-1], after sorting each k-sized window

I need the efficient algorithm for this problem (time comlexity less than O(n^2)), please help me:
a[i..j] is called a[i..j] < b[i..j] if a[i]<b[i], a[i+1]<b[i+1], ..., a[j]<b[j] after sorting these 2 arrays.
Given array A[1..n], (n<= 10^5, a[i]<= 1000). Find the maximum of k that A[1..k] < A[k+1..2k]
For example, n=10: 2 2 1 4 3 2 5 4 2 3
the answer is 4
Easily to see that k <= n/2. So we can use brute-forces (k from n/2 to 1), but not binary search.
And I don't know what to do with a[i] <= 1000. Maybe using map???
Use a Fenwick tree with range updates. Each index in the tree represents the count of how many numbers in window A are smaller than it. For the windows to be valid, each element in B (the window on the right) must have a partner in A (the window on the left). When we shift a number x into A, we add 1 to the range, [x+1, 1000] in the tree. For the element shifted from B to A, add 1 in its tree index. For each new element in B, add -1 to its index in the tree. If an index drops below zero, the window is invalid.
For the example, we have:
2 2 1 4 3 2 5 4 2 3
2 2
|
Tree:
add 1 to [3, 1000]
add -1 to 2
idx 1 2 3 4 5
val 0 -1 1 1 1 (invalid)
2 2 1 4 3 2 5 4 2 3
2 2 1 4
|
Tree:
add 1 to [3, 1000]
add 1 to 2 (remove 2 from B)
add -1 to 1
add -1 to 4
idx 1 2 3 4 5
val -1 0 2 1 2 (invalid)
2 2 1 4 3 2 5 4 2 3
2 2 1 4 3 2
|
Tree:
add 1 to [2, 1000]
add 1 to 1 (remove 1 from B)
add -1 to 3
add -1 to 2
idx 1 2 3 4 5
val 0 0 2 2 3 (valid)
2 2 1 4 3 2 5 4 2 3
2 2 1 4 3 2 5 4
|
Tree:
add 1 to [5, 1000]
add 1 to 4 (remove 4 from B)
add -1 to 5
add -1 to 4
idx 1 2 3 4 5
val 0 0 2 2 3 (valid)
2 2 1 4 3 2 5 4 2 3
2 2 1 4 3 2 5 4 2 3
|
Tree:
add 1 to [4, 1000]
add 1 to 3 (remove 3 from B)
add -1 to 2
add -1 to 3
idx 1 2 3 4 5
val 0 -1 2 3 4 (invalid)

Picking out exacly one value from each row and column of a matrix

This is not exactly a question about code, but I need some help with the logic of the algorithm.
Given an NxN matrix which has at least one zero value on each row and column, how would you chose N zeros so that there is exactly one value on each row and each column? For example:
0 4 6 0 2
0 8 9 5 0
4 0 9 8 5
0 8 0 1 3
8 6 0 1 3
Clearly, you first have to choose the zeros that are singular on each row or column. I am not sure about the case when there is an equal number of zeros on several rows and columns. How would I pick the optimal values so that no line or column is left out?
This is the problem of finding a maximum cardinality matching in a bipartite graph: the rows represent one set of vertices u_1, u_2, ..., u_N, the columns the other set v_1, v_2, ..., v_N, and there is an edge u_i -- v_j whenever there is a 0 at matrix position (i, j).
It can be solved using maximum flow algorithms such as Ford-Fulkerson in O(N^3) time, or with the more specialised Hopcroft-Karp algorithm in O(N^2.5) time. In fact these algorithms solve a slightly more general problem: It will find a largest-possible set of unique (row, column) pairs such that each pair has a 0 in the matrix. (In your case, you happen to know that there is a solution with N such pairs: this is obviously best-possible.)
Select the row with least number of zeros.
For every zero in that row, pick the one whose column has the least number of zeros.
Mark that row and column in some way (maybe remove all zeors from them after storing the index of the selected zero? This one is up to you).
The marked rows and columns are skipped in the next iteration.
Repeat until all unmarked rows and columns are traversed, or until a further solution can't be built.
So for the sample problem, this is how the solution can be visualized ( < and ^ represent marked rows and columns ):
0 4 6 0 2
0 8 9 5 0
4 0 9 8 5
0 8 0 1 3
8 6 0 1 3 // Row with least zeros, and last one to be accessed
Iteration 1:
0 4 6 0 2
0 8 9 5 0
4 0 9 8 5
0 8 0 1 3
8 6 0 1 3 <
_ _ ^ _ _
Iteration 2:
0 4 6 0 2
0 8 9 5 0
4 0 9 8 5 <
0 8 0 1 3
8 6 0 1 3 <
_ ^ ^ _ _
Iteration 3:
0 4 6 0 2
0 8 9 5 0 <
4 0 9 8 5 <
0 8 0 1 3
8 6 0 1 3 <
_ ^ ^ _ ^
Iteration 4:
0 4 6 0 2 <
0 8 9 5 0 <
4 0 9 8 5 <
0 8 0 1 3
8 6 0 1 3 <
_ ^ ^ ^ ^
Iteration 5:
0 4 6 0 2 <
0 8 9 5 0 <
4 0 9 8 5 <
0 8 0 1 3 <
8 6 0 1 3 <
^ ^ ^ ^ ^

Check if a road is available in something similar to a binary tree

I have a coordinates system which looks like that http://i.imgur.com/oKCU2uv.png Where the points -> (depthToNode, Node). But I don't have this structure, just raw points. You can go from (x,y) only to (x+1,y+1) or (x+1,y-1).
The data I get is a n < 500000, n - number of 'pillars' with blocked points. Then for each n I get x, a, b which are: x - the x coord of the pillar, a - everyone y coord <= a is blocked, b - everyone y coord >= b is blocked. The next x is always greater than the previous one. For Example: (x,a,b) -> (4,0,5). Then I know that the not blocked points on x = 4 are (4,2),(4,4). Note that if x is even then y must be also even, otherwise we can't go through such a point, for example (4,1), (4,3).
I noticed that if our coordinates are like (s,m) and I want to go to (c,d) then if c+d-s-m >= 0 then I can get from point (s,m) to (c,d). But the problem is that if I get 500000 'pillars' with blocked points, and the points are blocked from y < -10^8 and y > 10^8 then there is a large amount of points to check.
So the question is: How can I check if I can go from point (0,0) to the one of the points (x,y) avoiding the points which are blocking the path. (x,y) are all the points not blocked in the last 'pillar'
EXAMPLE 1:
INPUT:
4
1 0 2
4 -5 3
5 1 3
8 2 5
OUTPUT: NO
EXAMPLE 2:
INPUT:
4
1 0 2
4 3 5
5 -1000 3000
8 1 98
OUTPUT: YES
There is no need to check all possible nodes.
For each step of tree culling we only need to keep 2 values: min and max nodes that survived this step at its base level N. Let`s call them LN and UN, respectively.
Given the range [LN; UN] we can easily find [LN+K; UN+K] for any natural K.
Now we choose K so that N + K = N`, i.e. the level where the next step of culling is to be performed. We already know [LN`; UN`], see above. And now we compute [L`N`; U`N`] — the range of values that actually survived this next step at level N`.
Intersect these two ranges and repeat.
Proceed until either [LN`; UN`] ∩ [L`N`; U`N`] = ∅ (in which case the answer`s NO) or there is no more data left (the answer`s YES).
Illustration:
0
-1 1
-2 0 2
-3 -1 1 3
-4 -2 0 2 4
-5 -3 -1 1 3 5
-6 -4 -2 0 2 4 6
-7 -5 -3 -1 1 3 5 7
-8 -6 -4 -2 0 2 4 6 8
0
1 ← #1 (1: 0, 2)
0 2
-1 1 3
-2_____0_____2_____4_
-3 -1 1 3 5
-4 -2 0 2 4 6
-5 -3 -1 1 3 5 7
-6 -4 -2 0 2 4 6 8
0
1 ← #1 (1: 0, 2)
0 2
-1 1 3
4 ← #2 (4: 3, 5)
_3_____5_
2 4 6
1 3 5 7
0 2 4 6 8
0
1 ← #1 (1: 0, 2)
0 2
-1 1 3
4 ← #2 (4: 3, 5)
3 5 ← #3 (5: –1000, 3000)
2 4 6
1 3 5 7
_0_____2_____4_____6_____8_
0
1 ← #1 (1: 0, 2)
0 2
-1 1 3
4 ← #2 (4: 3, 5)
3 5 ← #3 (5: –1000, 3000)
2 4 6
1 3 5 7
2 4 6 8 ← #4 (8: 1, 98)

Efficiently construct a square matrix with unique numbers in each row

A matrix of size nxn needs to be constructed with the desired properties.
n is even. (given as input to the algorithm)
Matrix should contain integers from 0 to n-1
Main diagonal should contain only zeroes and matrix should be symmetric.
All numbers in each row should be different.
For various n , any one of the possible output is required.
input
2
output
0 1
1 0
input
4
output
0 1 3 2
1 0 2 3
3 2 0 1
2 3 1 0
Now the only idea that comes to my mind is to brute-force build combinations recursively and prune.
How can this be done in a iterative way perhaps efficiently?
IMO, You can handle your answer by an algorithm to handle this:
If 8x8 result is:
0 1 2 3 4 5 6 7
1 0 3 2 5 4 7 6
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
4 5 6 7 0 1 2 3
5 4 7 6 1 0 3 2
6 7 4 5 2 3 0 1
7 6 5 4 3 2 1 0
You have actually a matrix of two 4x4 matrices in below pattern:
m0 => 0 1 2 3 m1 => 4 5 6 7 pattern => m0 m1
1 0 3 2 5 4 7 6 m1 m0
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
And also each 4x4 is a matrix of two 2x2 matrices with a relation to a power of 2:
m0 => 0 1 m1 => 2 3 pattern => m0 m1
1 0 3 2 m1 m0
In other explanation I should say you have a 2x2 matrix of 0 and 1 then you expand it to a 4x4 matrix by replacing each cell with a new 2x2 matrix:
0 => 0+2*0 1+2*0 1=> 0+2*1 1+2*1
1+2*0 0+2*0 1+2*1 0+2*1
result => 0 1 2 3
1 0 3 2
2 3 0 1
3 2 1 0
Now expand it again:
0,1=> as above 2=> 0+2*2 1+2*2 3=> 0+2*3 1+2*3
1+2*2 0+2*2 1+2*3 0+2*3
I can calculate value of each cell by this C# sample code:
// i: row, j: column, n: matrix dimension
var v = 0;
var m = 2;
do
{
var p = m/2;
v = v*2 + (i%(n/p) < n/m == j%(n/p) < n/m ? 0 : 1);
m *= 2;
} while (m <= n);
We know each row must contain each number. Likewise, each row contains each number.
Let us take CS convention of indices starting from 0.
First, consider how to place the 1's in the matrix. Choose a random number k0, from 1 to n-1. Place the 1 in row 0 at position (0,k0). In row 1, if k0 = 1 in which case there is already a one placed. Otherwise, there are n-2 free positions and place the 1 at position (1,k1). Continue in this way until all the 1 are placed. In the final row there is exactly one free position.
Next, repeat with the 2 which have to fit in the remaining places.
Now the problem is that we might not be able to actually complete the square. We may find there are some constraints which make it impossible to fill in the last digits. The problem is that checking a partially filled latin square is NP-complete.(wikipedia) This basically means pretty compute intensive and there no know short-cut algorithm. So I think the best you can do is generate squares and test if they work or not.
If you only want one particular square for each n then there might be simpler ways of generating them.
The link Ted Hopp gave in his comment Latin Squares. Simple Construction does provide a method for generating a square starting with the addition of integers mod n.
I might be wrong, but if you just look for printing a symmetric table - a special case of latin squares isomorphic to the symmetric difference operation table over a powerset({0,1,..,n}) mapped to a ring {0,1,2,..,2^n-1}.
One can also produce such a table, using XOR(i,j) where i and j are n*n table indexes.
For example:
def latin_powerset(n):
for i in range(n):
for j in range(n):
yield (i, j, i^j)
Printing tuples coming from previously defined special-case generator of symmetric latin squares declared above:
def print_latin_square(sq, n=None):
cells = [c for c in sq]
if n is None:
# find the length of the square side
n = 1; n2 = len(cells)
while n2 != n*n:
n += 1
rows = list()
for i in range(n):
rows.append(" ".join("{0}".format(cells[i*n + j][2]) for j in range(n)))
print("\n".join(rows))
square = latin_powerset(8)
print(print_latin_square(square))
outputs:
0 1 2 3 4 5 6 7
1 0 3 2 5 4 7 6
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
4 5 6 7 0 1 2 3
5 4 7 6 1 0 3 2
6 7 4 5 2 3 0 1
7 6 5 4 3 2 1 0
See also
This covers more generic cases of latin squares, rather than that super symmetrical case with the trivial code above:
https://www.cut-the-knot.org/arithmetic/latin2.shtml (also pointed in the comments above for symmetric latin square construction)
https://doc.sagemath.org/html/en/reference/combinat/sage/combinat/matrices/latin.html

Selection sort count number of swaps

http://www.cs.pitt.edu/~kirk/cs1501/animations/Sort1.html is this applet counting right? Selection sort for 5 4 3 2 1, I see 2 swaps, but the applet is counting 4 exchanges....
I guess it's a matter of definition. He is doing a swap in the end of every loop, even if he is swapping one element against itself. In his case, the swaps will be:
Original: 5 4 3 2 1
Swap pos 1 and 5: 1 4 3 2 5
Swap pos 2 and 4: 1 2 3 4 5
Swap pos 3 and 3: 1 2 3 4 5
Swap pos 4 and 4: 1 2 3 4 5
(No swap is done for the last element since that will always be in the correct place)
A simple if statement could be used to eliminate the two last swaps.

Resources