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.
1#include <iostream>
2#include <vector>
3#include <unordered_set>
4#include <algorithm>
5using namespace std;
6
7int longestSquareStreak(vector<int>& nums) {
8 unordered_set<int> hashSet(nums.begin(), nums.end());
9 int maxLength = -1;
10
11 for (int num : nums) {
12 int length = 1;
13 int current = num;
14 while (hashSet.count(current * current)) {
15 ++length;
16 current *= current;
17 }
18 if (length > 1) {
19 maxLength = max(maxLength, length);
20 }
21 }
22 return maxLength;
23}
24
25int main() {
26 vector<int> nums = {4, 3, 6, 16, 8, 2};
27 cout << longestSquareStreak(nums) << endl;
28 return 0;
29}
This solution uses a C++ unordered_set
for O(1) average-time presence checks of squared values, improving overall efficiency. For each number in the array, it counts the length of the square streak and updates the maximum streak found.
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
The C solution uses a dynamic programming array dp
where each entry keeps track of the longest sequence ending with that element. It sorts the input array to facilitate streak calculations, checking possible backward links with previous elements.