Skip to content

Latest commit

 

History

History
37 lines (34 loc) · 1.31 KB

896.monotonic-array.md

File metadata and controls

37 lines (34 loc) · 1.31 KB
fun isMonotonic(nums: IntArray): Boolean {
    if (nums.size == 1) return true
    // We decide if that is increasing or decreasing or unknown (the two numbers are equal)
    var increasing: Boolean? = if (nums[0] == nums[1]) null else if (nums[0] < nums[1]) true else false
    for (i in 2 until nums.size) {
        // If we can't decide, we try to decide
        if (increasing == null) {
            if (nums[i - 1] < nums[i]) increasing = true
            else if (nums[i - 1] > nums[i]) increasing = false
        } else {
            // We can decide, but the next number is not following the rule
            if (increasing && nums[i - 1] > nums[i]) return false
            if (!increasing && nums[i - 1] < nums[i]) return false
        }
    }
    return true
}
  • Time Complexity: O(n).
  • Space Complexity: O(1).

Two Pointers

fun isMonotonic(nums: IntArray): Boolean {
    var increasing = false
    var decreasing = false
    for (i in 1 until nums.size) {
        if (nums[i - 1] < nums[i]) increasing = true
        if (nums[i - 1] > nums[i]) decreasing = true
    }
    // If increasing and decreasing contradict each other, then it is not monotonic.
    return if (increasing && decreasing) false else true
}