| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.CheckIfArrayIsSortedAndRotated; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class CheckIfArrayIsSortedAndRotatedIterative : ICheckIfArrayIsSortedAndRotated |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public bool Check(int[] nums) |
| | 3 | 24 | | { |
| | 3 | 25 | | var isRotated = false; |
| | | 26 | | |
| | 24 | 27 | | for (var i = 0; i < nums.Length - 1; i++) |
| | 9 | 28 | | { |
| | 9 | 29 | | if (nums[i] <= nums[i + 1]) |
| | 7 | 30 | | { |
| | 7 | 31 | | continue; |
| | | 32 | | } |
| | | 33 | | |
| | 2 | 34 | | if (isRotated) |
| | 0 | 35 | | { |
| | 0 | 36 | | return false; |
| | | 37 | | } |
| | | 38 | | |
| | 2 | 39 | | isRotated = true; |
| | 2 | 40 | | } |
| | | 41 | | |
| | 3 | 42 | | if (nums[^1] <= nums[0]) |
| | 1 | 43 | | { |
| | 1 | 44 | | return true; |
| | | 45 | | } |
| | | 46 | | |
| | 2 | 47 | | return !isRotated; |
| | 3 | 48 | | } |
| | | 49 | | } |