0
from collections import deque

dq1 = deque([...])  # with n length
dq2 = deque([...])  # with m length

we want to left-extend dq2 to dq1 (with left to right order) and then, keep the dq1.

question1: if the best solution depends on the n and m?

I tried the following solutions:

scenario1: (n > m)

for _ in range(len(dq2)):
    dq1.appendleft(dq2.pop())

scenario2: (n < m)

dq2.extend(dq1)
dq1 = dq2  # question2

question2: what's the time complexity of specified line? O(1) or O(n+m)?

question3: Are there any better solutions than these I have mentioned for 2 scenarios?

ahmdnz
  • 11
  • 3
  • Does this answer your question? [Fastest way to merge two deques](https://stackoverflow.com/questions/53139531/fastest-way-to-merge-two-deques) – Yevhen Kuzmovych Jan 05 '23 at 14:49
  • Thanks for your time, It's useful method and I can use it in scenario 2, but what about scenario 1? – ahmdnz Jan 05 '23 at 15:55
  • But in a large scale, they seem to matter. for example: n=200, m=200000 is different compared to n=200000, m=200. It seems that I shouldn't use same method for these two scenarios. – ahmdnz Jan 05 '23 at 17:21
  • @YevhenKuzmovych: It's not constant time. I'm not sure why you would think it is. (The implementation can't just hook up the second deque's internal unrolled linked list to the tail of the first deque's unrolled linked list, if that's what you're thinking.) – user2357112 Jan 06 '23 at 11:03
  • @ahmdnz: What do you actually mean by "left-extend dq2 to dq1 (with left to right order) and then, keep the dq1"? If we have `dq1 = deque([1, 2])` and `dq2 = deque([3, 4, 5])`, what should the deques contain after your desired operations? – user2357112 Jan 06 '23 at 11:04
  • thanks for your attention @user2357112, my desired result is: `dq1=deque([3, 4, 5, 1, 2])` – ahmdnz Jan 06 '23 at 17:56
  • @ahmdnz: What about `dq2`? What should that be? – user2357112 Jan 06 '23 at 18:14
  • `dq2` doesn't matter. – ahmdnz Jan 06 '23 at 18:16
  • if I change my solution of scenario 1 to `dq1.extendleft(dq2.reverse())`, It seems that both solutions of two scenarios are good enough. but when I should use each one? the conditions (`m>n` and `m – ahmdnz Jan 06 '23 at 18:24

1 Answers1

0

change scenario 1: (n>m)

dq1.extendleft(dq2)

question 2:

O(min(m,n))
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • It would be useful for future readers if you could elaborate on why these are the answers, in your opinion. – snakecharmerb Jan 05 '23 at 19:41
  • Thanks for your answer, But `dq1.extendleft(dq2)` adds the **reverse** of dq2 to the left of dq1, I mean: if `dq1 = [0, 1, 2]`, `dq2 = [-3, -2, -1]`, your code gives this result: `dq1 = [-1, -2, -3, 0, 1, 2]` – ahmdnz Jan 05 '23 at 20:15
  • dq1.extendleft(dq2.reverse()) – zarrinkafsh Jan 06 '23 at 10:20
  • @zarrinkafsh your solution seems to be better than my `for` loop, It's should be faster. Thank you! – ahmdnz Jan 06 '23 at 18:02