awelgorithms

Compare two stacks

Updated

Equal stacks have the same size and the same values in the same LIFO order (same top, same buried sequence). Identity (same object) is stronger. Empty equals empty.

What to focus on

Compare bottom-to-top or pop both in lockstep onto helpers and compare pop sequences. Size mismatch is an early false. Do not compare only the tops.

Worked examples

equal

a = [4, 1, 9], b = [4, 1, 9]
  1. size 3
  2. each corresponding value

Result: true

same top only

a = [4, 1, 9], b = [8, 9]
  1. tops 9=9
  2. size and buried differ

Result: false

empty

a = [], b = []
  1. both empty

Result: true

Try it

Write equal(a, b). a and b are stacks written bottom to top. Return true if they have the same size and the same LIFO order. Do not compare only the tops. Empty equals empty. a = [4, 1, 9], b = [4, 1, 9] → true. a = [4, 1, 9], b = [8, 9] → false. a = [], b = [] → true.

Values are integers. Either stack may be empty. Compare the whole LIFO order, not only the tops.