From 9ab695d7397ff60386dece45d62d6fb5249d66a3 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sun, 24 May 2026 13:54:37 +0300 Subject: fix(rpn): optimize Swap from O(n) to O(1) (task dj) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace stack.Values() with direct Pop() calls in Swap(). Previously created a full stack copy just to read the top two values. Behavior is unchanged — ensureStackLength guard guarantees pops succeed. --- internal/rpn/operations_stack.go | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/internal/rpn/operations_stack.go b/internal/rpn/operations_stack.go index c028ab7..99eaa8b 100644 --- a/internal/rpn/operations_stack.go +++ b/internal/rpn/operations_stack.go @@ -4,7 +4,6 @@ package rpn import ( - "fmt" "strings" ) @@ -26,20 +25,9 @@ func (o *Operations) Swap(stack *Stack) error { return err } - // Get the values without popping - vals := stack.Values() - top := vals[len(vals)-1] - second := vals[len(vals)-2] - - // Pop both values - if _, err := stack.Pop(); err != nil { - return buildError("swap", fmt.Errorf("failed to pop top value: %w", err)) - } - if _, err := stack.Pop(); err != nil { - return buildError("swap", fmt.Errorf("failed to pop second value: %w", err)) - } + top, _ := stack.Pop() + second, _ := stack.Pop() - // Push in swapped order stack.Push(top) stack.Push(second) -- cgit v1.2.3