| | | 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.LongestSquareStreakInAnArray; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class LongestSquareStreakInAnArrayHashSet : ILongestSquareStreakInAnArray |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n log n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int LongestSquareStreak(int[] nums) |
| | 3 | 24 | | { |
| | 3 | 25 | | var longestSquareStreak = -1; |
| | | 26 | | |
| | 3 | 27 | | var numsHashSet = new HashSet<int>(nums); |
| | | 28 | | |
| | 35 | 29 | | foreach (var num in nums) |
| | 13 | 30 | | { |
| | 13 | 31 | | var currentLongestSquareStreak = 1; |
| | | 32 | | |
| | 13 | 33 | | long square = num; |
| | | 34 | | |
| | 17 | 35 | | while (square * square <= int.MaxValue && numsHashSet.Contains((int)(square * square))) |
| | 4 | 36 | | { |
| | 4 | 37 | | currentLongestSquareStreak++; |
| | | 38 | | |
| | 4 | 39 | | square = square * square; |
| | 4 | 40 | | } |
| | | 41 | | |
| | 13 | 42 | | if (currentLongestSquareStreak > 1) |
| | 3 | 43 | | { |
| | 3 | 44 | | longestSquareStreak = Math.Max(longestSquareStreak, currentLongestSquareStreak); |
| | 3 | 45 | | } |
| | 13 | 46 | | } |
| | | 47 | | |
| | 3 | 48 | | return longestSquareStreak; |
| | 3 | 49 | | } |
| | | 50 | | } |