Longest Square Streak in an Array

medium hash set chaining array

Problem

A subsequence of nums is a square streak if it has length at least 2 and, after sorting, every element except the first equals the square of the element before it. Return the length of the longest square streak, or -1 if none exists.

Inputnums = [4,3,6,16,8,2]
Output3
Pick [2, 4, 16]: 4 = 2², 16 = 4². Length 3 is the longest.
Inputnums = [2,3,5,6,7]
Output-1
No value's square is present, so no streak of length 2 exists.

def longest_square_streak(nums):
    s = set(nums)
    best = -1
    for n in nums:
        length = 0
        cur = n
        while cur in s:
            length += 1
            cur = cur * cur
        if length >= 2:
            best = max(best, length)
    return best
function longestSquareStreak(nums) {
  const s = new Set(nums);
  let best = -1;
  for (const n of nums) {
    let length = 0;
    let cur = n;
    while (s.has(cur)) {
      length++;
      cur = cur * cur;
    }
    if (length >= 2) best = Math.max(best, length);
  }
  return best;
}
int longestSquareStreak(int[] nums) {
    Set<Long> s = new HashSet<>();
    for (int n : nums) s.add((long) n);
    int best = -1;
    for (int n : nums) {
        int length = 0;
        long cur = n;
        while (s.contains(cur)) {
            length++;
            cur = cur * cur;
        }
        if (length >= 2) best = Math.max(best, length);
    }
    return best;
}
int longestSquareStreak(vector<int>& nums) {
    unordered_set<long long> s(nums.begin(), nums.end());
    int best = -1;
    for (int n : nums) {
        int length = 0;
        long long cur = n;
        while (s.count(cur)) {
            length++;
            cur = cur * cur;
        }
        if (length >= 2) best = max(best, length);
    }
    return best;
}
Time: O(n · log log max) Space: O(n)