LeetCode Entry

2913. Subarrays Distinct Element Sum of Squares I

15.10.2026 easy 2026 kotlin rust

Sum of squares of uniq numbers counts in all subarrays

2913. Subarrays Distinct Element Sum of Squares I easy substack youtube

https://dmitrysamoylenko.com/leetcode/

15.10.2026.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1512

Problem TLDR

Sum of squares of uniq numbers counts in all subarrays

Intuition

Brute force by taking each start, each end and hashset size between them.

Approach

  • or try all sliding windows
  • or reuse hashset/bitmask for O(n^2)

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code

    fun sumCounts(n: List<Int>)=
    (1..n.size).sumOf{n.windowed(it){val s=it.toSet().size;s*s}.sum()}
    pub fn sum_counts(n: Vec<i32>) -> i32 {
        let mut a=0;for i in 0..n.len(){let mut m=0u128;for x in&n[i..]{m|=1<<x;a+=m.count_ones().pow(2)}}a as _
    }

Comments