Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change solution to avoid O(N^2) in any operation #65

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

whoan
Copy link

@whoan whoan commented Oct 3, 2019

Complexity:

  • Push: O(N)
  • Peek: O(1)
  • Pop: O(1)

This is what happens when we push a value (let's say 3) to a pair of sorted stacks:

      [1]                  [2]                [3]                 [4]

  +---+  +---+        +---+  +---+        +---+  +---+        +---+  +---+
  |   |  |   |        |   |  | 1 |        |   |  | 1 |        |   |  |   |
  +---+  +---+        +---+  +---+        +---+  +---+        +---+  +---+
  |   |  | 4 |        |   |  | 4 |        |   |  | 4 |        | 1 |  | 4 |
  +---+  +---+  --->  +---+  +---+  --->  +---+  +---+  --->  +---+  +---+
  | 1 |  | 7 |        |   |  | 7 |        | 3 |  | 7 |        | 3 |  | 7 |
  +---+  +---+        +---+  +---+        +---+  +---+        +---+  +---+
  | 5 |  | 8 |        | 5 |  | 8 |        | 5 |  | 8 |        | 5 |  | 8 |
  +---+  +---+        +---+  +---+        +---+  +---+        +---+  +---+

  [1] We check that our value (5) is greater that both values at the top of the stacks,
      so we need to reorder elements. We find the stack with less elements (optional).
  [2] Push elements from the stack with less elements to the other stack until the value
      at the top of the former is greater or equal our value: 3
  [3] Push our value in the stack with less elements
  [4] Push (back) the elements from the other stack to the one which had less elements

Now we have two sorted stacks, so pop and peek are fast: O(1).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant