Subarrays Distinct Element Sum of Squares I — LeetCode 2913 Python Solution
- Problem
- #2913
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums. The distinct count of a subarray of nums is defined as: Let nums[i..j] be a subarray of nums consisting of all the indices from i to j such that 0 <= i <= j < nums.length.
Example
- Input
- nums = [1,2,1]
- Output
- 15
- Explanation
- Six possible subarrays are:
Python solution
class Solution:
def sumCounts(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(n):
s = set()
for j in range(i, n):
s.add(nums[j])
ans += len(s) * len(s)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2913. Subarrays Distinct Element Sum of Squares I is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2913. Subarrays Distinct Element Sum of Squares I?
- LeetCode 2913. Subarrays Distinct Element Sum of Squares I is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2913. Subarrays Distinct Element Sum of Squares I?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2913. Subarrays Distinct Element Sum of Squares I?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2913. Subarrays Distinct Element Sum of Squares I cover?
- LeetCode 2913. Subarrays Distinct Element Sum of Squares I is tagged Array and Hash Table on LeetCode.