| | 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.ShortestDistanceToTargetStringInCircularArray; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ShortestDistanceToTargetStringInCircularArrayIterative : IShortestDistanceToTargetStringInCircularArray |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="words"></param> |
| | 22 | | /// <param name="target"></param> |
| | 23 | | /// <param name="startIndex"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int ClosetTarget(string[] words, string target, int startIndex) |
| 3 | 26 | | { |
| 3 | 27 | | var closestDistance = int.MaxValue; |
| 3 | 28 | | var targetFound = false; |
| | 29 | |
|
| 28 | 30 | | for (var i = 0; i < words.Length; i++) |
| 11 | 31 | | { |
| 11 | 32 | | if (words[i] != target) |
| 8 | 33 | | { |
| 8 | 34 | | continue; |
| | 35 | | } |
| | 36 | |
|
| 3 | 37 | | targetFound = true; |
| | 38 | |
|
| 3 | 39 | | var directDistance = Math.Abs(i - startIndex); |
| 3 | 40 | | var circularDistance = words.Length - directDistance; |
| 3 | 41 | | var distance = Math.Min(directDistance, circularDistance); |
| | 42 | |
|
| 3 | 43 | | closestDistance = Math.Min(closestDistance, distance); |
| 3 | 44 | | } |
| | 45 | |
|
| 3 | 46 | | return targetFound ? closestDistance : -1; |
| 3 | 47 | | } |
| | 48 | | } |