summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2026-05-24 13:54:37 +0300
committerPaul Buetow <paul@buetow.org>2026-05-24 13:54:37 +0300
commit9ab695d7397ff60386dece45d62d6fb5249d66a3 (patch)
treeda3fa16e6500c2174014f88fb8a94aca8bbd39dc
parentdddcf4a1ef3ca2a9960e608e55a57d65655b981e (diff)
fix(rpn): optimize Swap from O(n) to O(1) (task dj)
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.
-rw-r--r--internal/rpn/operations_stack.go16
1 files 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)