LeetCode 2913: Subarrays Distinct Element Sum of Squares I Solution

Master LeetCode problem 2913 (Subarrays Distinct Element Sum of Squares I), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2913. Subarrays Distinct Element Sum of Squares I

Problem Explanation

Explanation:

To solve this problem, we can iterate through all possible subarrays of the given array nums. For each subarray, we calculate the distinct count of elements in that subarray and then square that count. Finally, we sum up the squares of distinct counts for all subarrays to get the result.

Algorithm:

  1. Initialize a variable result to store the final result.
  2. Iterate over all possible subarrays using two nested loops.
  3. For each subarray, calculate the distinct count of elements.
  4. Square the distinct count and add it to the result.
  5. Return the result as the final answer.

Time Complexity: O(n^3), where n is the length of the input array nums. Space Complexity: O(1) since we are not using any extra space.

:

Solution Code

class Solution {
    public int sumOfSquares(int[] nums) {
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i; j < nums.length; j++) {
                int distinctCount = countDistinct(nums, i, j);
                result += distinctCount * distinctCount;
            }
        }
        return result;
    }
    
    private int countDistinct(int[] nums, int start, int end) {
        Set<Integer> set = new HashSet<>();
        for (int i = start; i <= end; i++) {
            set.add(nums[i]);
        }
        return set.size();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2913 (Subarrays Distinct Element Sum of Squares I)?

This page provides optimized solutions for LeetCode problem 2913 (Subarrays Distinct Element Sum of Squares I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2913 (Subarrays Distinct Element Sum of Squares I)?

The time complexity for LeetCode 2913 (Subarrays Distinct Element Sum of Squares I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2913 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2913 in Java, C++, or Python.

Back to LeetCode Solutions