LeetCode 2501: Longest Square Streak in an Array

LeetCode 2501 Solution Explanation

Explanation:

To solve this problem, we can iterate through each element in the array and consider it as the starting point of a potential square streak. We then try to build the square streak by looking for the square of the current element in the remaining elements. If we find the square, we continue this process until we can no longer find the next square in the sequence.

Algorithmic Idea:

  1. Initialize a variable longestStreak to keep track of the maximum square streak length found so far.
  2. Iterate through each element in the array.
  3. For each element num[i], try to build a square streak starting from num[i].
  4. Check if num[i] * num[i] exists in nums, if it does, increment the streak length by 1 and update the current element to the square found.
  5. Continue this process until we can no longer find the next square in the sequence.
  6. Update longestStreak if the current streak is longer.

Time Complexity:

The time complexity of this approach is O(n^2) where n is the length of the input array nums.

Space Complexity:

The space complexity of this approach is O(1) as we are using only a constant amount of extra space.

LeetCode 2501 Solutions in Java, C++, Python

class Solution {
    public int longestSquareStreak(int[] nums) {
        int longestStreak = -1;
        for (int i = 0; i < nums.length; i++) {
            int curr = nums[i];
            int streak = 1;
            while (true) {
                int next = curr * curr;
                boolean found = false;
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] == next) {
                        streak++;
                        curr = nums[j];
                        found = true;
                        break;
                    }
                }
                if (!found) break;
            }
            longestStreak = Math.max(longestStreak, streak);
        }
        return longestStreak >= 2 ? longestStreak : -1;
    }
}

Interactive Code Editor for LeetCode 2501

Improve Your LeetCode 2501 Solution

Use the editor below to refine the provided solution for LeetCode 2501. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems