Combining two very large lists

Given a list of elements of size 2n -1, and the list is as follows:

x1, x2, x3, ....., xn, y1, y2, y3, ....y(n- 1)

Convert it to:

x1, y1, x2, y2, x3, y3, ........., y(n-1), xn

I can use two iterators for each of the lists and get a solution in O (n) time complexity and O (n) complexity. But if my n was very large, is there a way to do this with less complexity of space?

+4
source share
2 answers

, O (1) O (n) , . , , , x2, , , , (.. X3), x2. , x3 ..

, , ( ).

:

x1 x2 x3 y1 y2      x2 is out of place so take it into temp storage
x1 -- x3 y1 y2      temp: x2       needs to go where x3 currently is
x1 -- x2 y1 y2      temp: x3       needs to go where y2 currently is
x1 -- x2 y1 x3      temp: y2       needs to go where y1 currently is
x1 -- x2 y2 x3      temp: y1       needs to go into the empty slot
x1 y1 x2 y2 x3      all elements in place -> finished

0, k

2k            if k < n
2(k-n) + 1    if k >= n

, , . , n = 4, 3 :

0 -> 0
1 -> 2 -> 4 -> 1
3 -> 6 -> 5 -> 3

.

, , , O (n) .

+1

Python:

lst = 'x1 x2 x3 x4 x5 y1 y2 y3 y4 y5'.split()

lst
Out[9]: ['x1', 'x2', 'x3', 'x4', 'x5', 'y1', 'y2', 'y3', 'y4', 'y5']

out = sum((list(xy) for xy in zip(lst[:len(lst)//2], lst[len(lst)//2:])), [])

out
Out[11]: ['x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4', 'x5', 'y5']
-1

All Articles