The Indian Engineer

Problem 2501 Longest Square Streak in an Array

Posted on Last edited 4 mins

Set Array Math

Problem Statement

Link - Problem 2501

Question

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

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 eleme

Example 1

Input: nums = [4,3,6,16,8,2]
Output: 3
Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].
- 4 = 2 * 2.
- 16 = 4 * 4.
Therefore, [4,16,2] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.

Example 2

Input: nums = [2,3,5,6,7]
Output: -1
Explanation: There is no square streak in nums so return -1.

Constraints

Solution

class Solution {
public:
    int longestSquareStreak(vector<int>& nums) {
        vector<bool> check_vector(100001, false);
        for(int num : nums) {
                check_vector[num] = true;
        }

        int max_len = -1;

        for(int num : nums) {
            int len = 1;
            long val = num;
            if (val > 317) { // sqrt(100000) is around 317, so beyond this limit, squares exceed 100000
                continue;
            }

            while (val * val <= 100000 && check_vector[val * val]) {
                len++;
                max_len = max(max_len, len);
                val = val * val;
            }
        }
        return max_len;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Creating a set for lookup O(N) O(N)
Iteration and checking O(N) O(1)
Total O(N) O(N)

Explanation

If a subsequence can be sorted after picking the elements, then its equivalent to sorting the parent array and then picking the elements.

1. Intuition

2. Implementation

This is a relatively simple problem that can be solved using a set for lookup and iteration over the elements of the array. The time complexity of the solution is O(N), where N is the number of elements in the array, and the space complexity is O(N) for the set used for lookup.