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.

Example 1
Inputnums = [4,3,6,16,8,2]
Output3
Choose the subsequence [4, 16, 2], which becomes [2, 4, 16] after sorting, and each element is the square of the previous one.
Example 2
Inputnums = [2,3,5,6,7]
Output-1
There is no square streak in nums, so return -1.

Constraints

  • 2 <= nums.length <= 10^5
  • 2 <= nums[i] <= 10^5

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate