awelgorithms

Compare two stack tops

Updated

Comparing tops is peek(a) vs peek(b). After a compare you usually pop the smaller or larger and leave the other. That is merge of two decreasing stacks, not queue merge.

What to focus on

You do not compare bottoms unless the problem says so. Equal tops need a tie rule.

Worked examples

both nonempty

a = [4, 1, 9], b = [8, 2]
  1. top 9 vs 2
  2. 9>2

Result: 9 vs 2

one empty

a = [4, 1, 9], b = []
  1. b has no top

Result: cannot compare / take a

equal tops

a = [4, 9], b = [1, 9]
  1. 9==9
  2. tie rule needed

Result: equal

Try it

Write compareTops(a, b). a and b are stacks written bottom to top. Return peek(a) versus peek(b). State a tie rule when tops are equal. Pop the smaller only if the step asks. a = [4, 1, 9], b = [8, 2] → 9 vs 2. a = [4, 1, 9], b = [] → cannot compare / take a. a = [4, 9], b = [1, 9] → equal.

Either stack may be empty. Values are integers.