DMITRII’s Substack

Share this post

Leetcode daily: # 12.04.2023

dmitriisamoilenko.substack.com

Leetcode daily: # 12.04.2023

71. Simplify Path

DMITRII SAMOILENKO
Apr 12, 2023
Share

# 12.04.2023

[71. Simplify Path](https://leetcode.com/problems/simplify-path/description/) medium

fun simplifyPath(path: String): String =
"/" + Stack<String>().apply {
    path.split("/").forEach {
        when (it) {
            ".." -> if (isNotEmpty()) pop()
            "." -> Unit
            "" -> Unit
            else -> push(it)
        }
    }
}.joinToString("/")

[blog post](https://leetcode.com/problems/simplify-path/solutions/3407165/kotlin-stack/)

#### Join me on Telegram

https://t.me/leetcode_daily_unstoppable/178

#### Intuition

We can simulate what each of the `.` and `..` commands do by using a `Stack`.

#### Approach

* split the string by `/`

* add elements to the Stack if they are not commands and not empty

#### Complexity

- Time complexity:

\(O(n)\)

- Space complexity:

\(O(n)\)


Thanks for reading DMITRII’s Substack! Subscribe for free to receive new posts and support my work.

Share
Previous
Next
Comments
Top
New

No posts

Ready for more?

© 2023 DMITRII SAMOILENKO
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing