| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.ShortestSubarrayToBeRemovedToMakeArraySorted; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ShortestSubarrayToBeRemovedToMakeArraySortedTwoPointers : IShortestSubarrayToBeRemovedToMakeArraySorted |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="arr"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int FindLengthOfShortestSubarray(int[] arr) |
| 3 | 24 | | { |
| 3 | 25 | | var left = 0; |
| | 26 | |
|
| 8 | 27 | | while (left < arr.Length - 1 && arr[left] <= arr[left + 1]) |
| 5 | 28 | | { |
| 5 | 29 | | left++; |
| 5 | 30 | | } |
| | 31 | |
|
| 3 | 32 | | if (left == arr.Length - 1) |
| 1 | 33 | | { |
| 1 | 34 | | return 0; |
| | 35 | | } |
| | 36 | |
|
| 2 | 37 | | var right = arr.Length - 1; |
| | 38 | |
|
| 4 | 39 | | while (right > 0 && arr[right - 1] <= arr[right]) |
| 2 | 40 | | { |
| 2 | 41 | | right--; |
| 2 | 42 | | } |
| | 43 | |
|
| 2 | 44 | | var result = Math.Min(arr.Length - left - 1, right); |
| | 45 | |
|
| 2 | 46 | | var i = 0; |
| 2 | 47 | | var j = right; |
| | 48 | |
|
| 9 | 49 | | while (i <= left && j < arr.Length) |
| 7 | 50 | | { |
| 7 | 51 | | if (arr[i] <= arr[j]) |
| 3 | 52 | | { |
| 3 | 53 | | result = Math.Min(result, j - i - 1); |
| | 54 | |
|
| 3 | 55 | | i++; |
| 3 | 56 | | } |
| | 57 | | else |
| 4 | 58 | | { |
| 4 | 59 | | j++; |
| 4 | 60 | | } |
| 7 | 61 | | } |
| | 62 | |
|
| 2 | 63 | | return result; |
| 3 | 64 | | } |
| | 65 | | } |