Build a data structure that supports O(1) min, max, insert, and delete operations.
- User
Build a data structure that supports O(1) min, max, insert, and delete operations.
- Assistantpython
class MinMaxStack: def __init__(self): self.stack = [] # List of (val, cur_min, cur_max) def insert(self, val: int) -> None: if not self.stack: cur_min = cur_max = val else: cur_min = min(val, self.stack[-1][1]) cur_max = max(val, self.stack[-1][2]) self.stack.append((val, cur_min, cur_max)) def delete(self) -> None: if self.stack: self.stack.pop() def min(self) -> int: return self.stack[-1][1] if self.stack else float('inf') # or raise error def max(self) -> int: return self.stack[-1][2] if self.stack else float('-inf') # or raise error # Example usage: # s = MinMaxStack() # s.insert(3) # s.insert(1) # print(s.min()) # 1 # print(s.max()) # 3 # s.insert(4) # print(s.min()) # 1 # print(s.max()) # 4 # s.delete() # removes 4 # print(s.min()) # 1 # print(s.max()) # 3
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.