From 970f7c10605e454ab1bfa846d39740863f59fae2 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 15 Nov 2024 23:25:03 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB1574.=20Shortest=20Subarray?= =?UTF-8?q?=20to=20be=20Removed=20to=20Make=20Array=20Sorted=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/ Signed-off-by: Matej Focko --- ...rray-to-be-removed-to-make-array-sorted.kt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 kt/shortest-subarray-to-be-removed-to-make-array-sorted.kt diff --git a/kt/shortest-subarray-to-be-removed-to-make-array-sorted.kt b/kt/shortest-subarray-to-be-removed-to-make-array-sorted.kt new file mode 100644 index 0000000..f9c556f --- /dev/null +++ b/kt/shortest-subarray-to-be-removed-to-make-array-sorted.kt @@ -0,0 +1,22 @@ +class Solution { + fun findLengthOfShortestSubarray(arr: IntArray): Int { + var (left, right) = 0 to arr.size - 1 + + // shift ‹right› while ensorted + while (right > 0 && arr[right] >= arr[right - 1]) { + right -= 1 + } + + var shortest = right + while (left < right && (left < 1 || arr[left - 1] <= arr[left])) { + while (right < arr.size && arr[left] > arr[right]) { + right += 1 + } + + shortest = listOf(shortest, right - left - 1).min() + left += 1 + } + + return shortest + } +}