Rust Day 17: Leetcode — Min Stack

Arjun Sunil Kumar
Go Rust
Published in
2 min readMay 6, 2022

This is an interesting problem. Here we will be implementing a MinStack struct.

Taking a step back, I started this rust journey 17 days back. Back then, rust was a bit hard to learn, and understand. But then, day by day, I progressed to read rust code, solve LC using rust, and understand projects written in rust. Rust was never meant for rapid prototyping. It requires you to handle almost all the errors. The ownership built into this language helps you write safe parallel codes. This is really useful in projects which involve system-level programming, Databases, Image Processing, Graphics, etc( here you need to parallel threads to work on image segments for real-time fast processing).

From SO: Rust is named after a fungus that is robust, distributed, and parallel.

Ok, coming back, let's solve the LC quota for today.

Problem:

Logic:

We will be maintaining

  • a stack, which accepts a pair: { val, min_val_till_now}
  • min: holds the current min for the session

Whenever we insert, we ensure that the self.min is updated comparing the inserted val. The current min is inserted along with the val into the stack. When we pop(), we update the min, to the min_val_till_now based on the removed entry.

Code:

Syntax:

  1. Vec< (i32, i32) > : Vector which accepts a pair
  2. &mut: used to modify the content inside self.

3. unwrap_or() or unwrap(): Used to get the result directly

usage
http://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/error-handling.html#unwrapping-explained

self.stack.last() returns address. So to match that, we also return &(-1, i32::MAX) .

Reference:

Found it Interesting?

Please show your support by 👏

--

--

Arjun Sunil Kumar
Go Rust

Writes on Database Kernel, Distributed Systems, Cloud Technology, Data Engineering & SDE Paradigm. github.com/arjunsk