[LeetCode] Longest Square Streak in an Array

2501. Longest Square Streak in an Array

You are given an integer array nums. A subsequence of nums is called a square streak if:

  • The length of the subsequence is at least 2, and
  • after sorting the subsequence, each element (except the first element) is the square of the previous number.

Return the length of the longest square streak in nums, or return -1 if there is no square streak.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int longestSquareStreak(vector<int>& A) {
sort(begin(A), end(A));
unordered_set<int> us(begin(A), end(A));
int res = 0;
for(int i = 0; i < A.size(); i++) {
if(!us.count(A[i])) continue;
long long now = A[i], cnt = 0;
while(us.count(now)) {
cnt += 1;
us.erase(now);
now = now * now;
}
res = max(res, (int)cnt);
}
return res == 1 ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/11/PS/LeetCode/longest-square-streak-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.