DMITRII’s Substack

Share this post

Leetcode daily # 9.05.2023

dmitriisamoilenko.substack.com

Discover more from DMITRII’s Substack

I post a problem that I solve every single day
Continue reading
Sign in

Leetcode daily # 9.05.2023

[54. Spiral Matrix]

DMITRII SAMOILENKO
May 9, 2023
Share this post

Leetcode daily # 9.05.2023

dmitriisamoilenko.substack.com
Share

9.05.2023

54. Spiral Matrix medium

fun spiralOrder(matrix: Array<IntArray>): List<Int> = mutableListOf<Int>().apply {
    var x = 0
    var y = 0
    val dxy = arrayOf(0, 1, 0, -1)
    val borders = arrayOf(matrix[0].lastIndex, matrix.lastIndex, 0, 0)
    var dir = 0
    val moveBorder = { border: Int -> borders[border] += if (border < 2) -1 else 1 }
    repeat (matrix.size * matrix[0].size) {
        if ((if (dir % 2 == 0) x else y) == borders[dir]) {
            moveBorder((dir + 3) % 4)
            dir = (dir + 1) % 4
        }
        add(matrix[y][x])
        x += dxy[(dir + 1) % 4]
        y += dxy[dir]
    }
}

blog post

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/207

Intuition

Just implement what is asked.
We can use a loop with four directions, or try to program a robot that will rotate after it hit a wall.

Approach

  • do track the borders left, top, right, bottom

  • use single direction variable dir

  • move the wall after a robot walked parallel to it

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 this post

Leetcode daily # 9.05.2023

dmitriisamoilenko.substack.com
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