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.
1function longestSquareStreak(nums) {
2 const numSet = new Set(nums);
3 let maxLength = -1;
4
5 for (let num of nums) {
6 let length = 1;
7 let current = num;
8 while (numSet.has(current * current)) {
9 length++;
10 current *= current;
11 }
12 if (length > 1) {
13 maxLength = Math.max(maxLength, length);
14 }
15 }
16 return maxLength;
17}
18
19const nums = [4, 3, 6, 16, 8, 2];
20console.log(longestSquareStreak(nums));
In JavaScript, a Set
speeds up checking for existing elements. We iterate over the array and maintain the streak length calculated by consecutive squares, updating the longest found streak as required.
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.
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.