Sponsored
Sponsored
This approach leverages a HashSet for quick access to elements and checks subsequent squares in the sequence. We iterate over each number in the array, and for each number, keep finding its squares while incrementing the length of the streak. The longest streak is tracked and returned at the end.
Time Complexity: O(n^1.5) in worst-case due to nested loops and nested search.
Space Complexity: O(1) extra space for auxiliary storage as in-place checks are performed.
1def longest_square_streak(nums):
2 num_set = set(nums)
3 max_length = -1
4
5 for num in nums:
6 length = 1
7 current = num
8 while current * current in num_set:
9 length += 1
10 current *= current
11 if length > 1:
12 max_length = max(max_length, length)
13
14 return max_length
15
16nums = [4, 3, 6, 16, 8, 2]
17print(longest_square_streak(nums))
In the Python implementation, the standard set
collection provides a time-efficient way to check for elements. It processes each number and checks for its square's existence, calculating and comparing the streak length throughout.
This approach uses dynamic programming to store intermediate results regarding the longest square streak ending at each number. Sorting the array helps in ensuring that every subsequent square evaluated is in a larger-than relationship compared to previous elements, thus contributing to the streak length.
Time Complexity: O(n^2) due to nested loops used in the calculation of dp array.
Space Complexity: O(n) for managing the dp array.
1
In JavaScript, after sorting, the code utilizes a dp array with default values, advancing through likewise nested evaluations to track potential sequence streaks that conform to required conditions.