Ctrl K

Squared Variety of Segments

Easy
You are given an integer array values. For every non-empty contiguous segment of the array, take its variety, the number of distinct values it contains, and square it. Return the sum of these squares over all segments. Segments at different positions count separately even when their contents match.
Example 1
values=[5, 7] → 6

The segments [5] and [7] give 1² = 1 each, the segment [5, 7] gives 2² = 4. Total 1 + 1 + 4 = 6.

Example 2
values=[4, 4, 4] → 6

Six segments, each with a single distinct value: 6 · 1 = 6.

Example 3
values=[2, 3, 2] → 15

The three single segments give 3, [2, 3] and [3, 2] give 4 each, and [2, 3, 2] gives 4 too (only two distinct values). Total 15.

Constraints
  • 1 ≤ values.length ≤ 100
  • 1 ≤ values[i] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasyThe Candidate With Most Votes EasyDoes Any Value Repeat EasyRepeat Within Reach EasyThe Lost Ticket Easy
loading Python…
Input
values=[5, 7]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 107 tests on the server, hidden ones included.