CtCI-6th-Edition-cpp icon indicating copy to clipboard operation
CtCI-6th-Edition-cpp copied to clipboard

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

Open whoan opened this issue 6 years ago • 0 comments

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).

whoan avatar Oct 03 '19 04:10 whoan