LeetCode Entry

896. Monotonic Array

29.09.2023 easy 2023 kotlin

Is array monotonic

896. Monotonic Array easy blog post substack image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/354

Problem TLDR

Is array monotonic

Intuition

Let’s compute the diffs, then array is monotonic if all the diffs have the same sign.

Approach

Let’s use Kotlin’s API:

  • asSequence - to avoid creating a collection
  • map
  • filter
  • windowed - scans array by x sized sliding window

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


    fun isMonotonic(nums: IntArray) =
      nums.asSequence().windowed(2)
      .map { it[0] - it[1] }
      .filter { it != 0 }
      .windowed(2)
      .all { it[0] > 0 == it[1] > 0 }