Subarrays with distinct elements
Last Updated :
01 May, 2024
Given an array, the task is to calculate the sum of lengths of contiguous subarrays having all elements distinct.
Examples:
Input : arr[] = {1, 2, 3}
Output : 10
{1, 2, 3} is a subarray of length 3 with
distinct elements. Total length of length
three = 3.
{1, 2}, {2, 3} are 2 subarray of length 2
with distinct elements. Total length of
lengths two = 2 + 2 = 4
{1}, {2}, {3} are 3 subarrays of length 1
with distinct element. Total lengths of
length one = 1 + 1 + 1 = 3
Sum of lengths = 3 + 4 + 3 = 10
Input : arr[] = {1, 2, 1}
Output : 7
Input : arr[] = {1, 2, 3, 4}
Output : 20
A simple solution is to consider all subarrays and for every subarray check if it has distinct elements or not using hashing. And add lengths of all subarrays having distinct elements. If we use hashing to find distinct elements, then this approach takes O(n2) time under the assumption that hashing search and insert operations take O(1) time.
An efficient solution is based on the fact that if we know all elements in a subarray arr[i..j] are distinct, sum of all lengths of distinct element subarrays in this subarray is ((j-i+1)*(j-i+2))/2. How? the possible lengths of subarrays are 1, 2, 3,......, j - i +1. So, the sum will be ((j - i +1)*(j - i +2))/2.
We first find the largest subarray (with distinct elements) starting from first element. We count sum of lengths in this subarray using above formula. For finding next subarray of the distinct element, we increment starting point, i and ending point, j unless (i+1, j) are distinct. If not possible, then we increment i again and move forward the same way.
Below is the implementation of this approach:
C++
// C++ program to calculate sum of lengths of subarrays
// of distinct elements.
#include<bits/stdc++.h>
using namespace std;
// Returns sum of lengths of all subarrays with distinct
// elements.
int sumoflength(int arr[], int n)
{
// For maintaining distinct elements.
unordered_set<int> s;
// Initialize ending point and result
int j = 0, ans = 0;
// Fix starting point
for (int i=0; i<n; i++)
{
// Find ending point for current subarray with
// distinct elements.
while (j < n && s.find(arr[j]) == s.end())
{
s.insert(arr[j]);
j++;
}
// Calculating and adding all possible length
// subarrays in arr[i..j]
ans += ((j - i) * (j - i + 1))/2;
// Remove arr[i] as we pick new starting point
// from next
s.erase(arr[i]);
}
return ans;
}
// Driven Code
int main()
{
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout << sumoflength(arr, n) << endl;
return 0;
}
Java
// Java program to calculate sum of lengths of subarrays
// of distinct elements.
import java.util.*;
class geeks
{
// Returns sum of lengths of all subarrays
// with distinct elements.
public static int sumoflength(int[] arr, int n)
{
// For maintaining distinct elements.
Set<Integer> s = new HashSet<>();
// Initialize ending point and result
int j = 0, ans = 0;
// Fix starting point
for (int i = 0; i < n; i++)
{
while (j < n && !s.contains(arr[j]))
{
s.add(arr[j]);
j++;
}
// Calculating and adding all possible length
// subarrays in arr[i..j]
ans += ((j - i) * (j - i + 1)) / 2;
// Remove arr[i] as we pick new starting point
// from next
s.remove(arr[i]);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4 };
int n = arr.length;
System.out.println(sumoflength(arr, n));
}
}
// This code is contributed by
// sanjeev2552
Python 3
# Python 3 program to calculate sum of
# lengths of subarrays of distinct elements.
# Returns sum of lengths of all subarrays
# with distinct elements.
def sumoflength(arr, n):
# For maintaining distinct elements.
s = []
# Initialize ending point and result
j = 0
ans = 0
# Fix starting point
for i in range(n):
# Find ending point for current
# subarray with distinct elements.
while (j < n and (arr[j] not in s)):
s.append(arr[j])
j += 1
# Calculating and adding all possible
# length subarrays in arr[i..j]
ans += ((j - i) * (j - i + 1)) // 2
# Remove arr[i] as we pick new
# starting point from next
s.remove(arr[i])
return ans
# Driven Code
if __name__=="__main__":
arr = [1, 2, 3, 4]
n = len(arr)
print(sumoflength(arr, n))
# This code is contributed by ita_c
C#
// C# program to calculate sum of lengths of subarrays
// of distinct elements
using System;
using System.Collections.Generic;
public class geeks
{
// Returns sum of lengths of all subarrays
// with distinct elements.
public static int sumoflength(int[] arr, int n)
{
// For maintaining distinct elements.
HashSet<int> s = new HashSet<int>();
// Initialize ending point and result
int j = 0, ans = 0;
// Fix starting point
for (int i = 0; i < n; i++)
{
while (j < n && !s.Contains(arr[j]))
{
s.Add(arr[j]);
j++;
}
// Calculating and adding all possible length
// subarrays in arr[i..j]
ans += ((j - i) * (j - i + 1)) / 2;
// Remove arr[i] as we pick new starting point
// from next
s.Remove(arr[i]);
}
return ans;
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 1, 2, 3, 4 };
int n = arr.Length;
Console.WriteLine(sumoflength(arr, n));
}
}
/* This code is contributed by PrinciRaj1992 */
JavaScript
// Javascript program to calculate sum of lengths of subarrays
// of distinct elements.
// Returns sum of lengths of all subarrays
// with distinct elements.
function sumoflength(arr,n)
{
// For maintaining distinct elements.
let s=new Set();
// Initialize ending point and result
let j = 0, ans = 0;
// Fix starting point
for (let i = 0; i < n; i++)
{
while (j < n && !s.has(arr[j]))
{
s.add(arr[i]);
j++;
}
// Calculating and adding all possible length
// subarrays in arr[i..j]
ans += Math.floor(((j - i) * (j - i + 1)) / 2);
// Remove arr[i] as we pick new starting point
// from next
s.delete(arr[i]);
}
return ans;
}
// Driver Code
let arr=[1, 2, 3, 4];
let n = arr.length;
console.log(sumoflength(arr, n));
// This code is contributed by avanitrachhadiya2155
Time Complexity: O(n^2). Note that the inner loop runs n times in total as j goes from 0 to n across all outer loops.
Space Complexity: O(n), since n extra space has been added
Similar Reads
Count Subarrays With Exactly K Distinct Elements
Given an array arr[] and an integer k, the task is to find the count of subarrays such that each subarray has exactly k distinct elements.Examples:Input: arr[] = [1, 2, 2, 3], k = 2 Output: 4 Explanation: Subarrays with exactly 2 distinct elements are: [1, 2], [1, 2, 2] and [2, 3].Input: arr[] = [3,
10 min read
Count Subarrays With At Most K Distinct Elements
Given an array arr[] and an integer k, the task is to find the count of subarrays such that each subarray has at most k distinct elements.Examples:Input: arr[] = [1, 2, 2, 3], k = 2 Output: 9Explanation: Subarrays with at most 2 distinct elements are: [1], [2], [2], [3], [1, 2], [2, 2], [2, 3], [1,
9 min read
Minimum Subsets with Distinct Elements
You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible.Examples : Input : arr[] = {1, 2, 3, 4}Output :1Explanation : A single subset can contains all values and all values are distinct.In
9 min read
Smallest subarray with k distinct numbers
We are given an array consisting of n integers and an integer k. We need to find the smallest subarray [l, r] (both l and r are inclusive) such that there are exactly k different numbers. If no such subarray exists, print -1 and If multiple subarrays meet the criteria, return the one with the smalle
14 min read
Count of Subsequences with distinct elements
Given an array arr[] (1<=a[i]<=1e9) containing N (1<=N<=1e5) elements, the task is to find the total number of subsequences such that all elements in that subsequences are distinct. Since the answer can be very large print and modulo 1e9+7. Examples: Input: arr[] = [1, 1, 2, 2]Output: 8E
5 min read
Count subarrays with same even and odd elements
Given an array of N integers, count number of even-odd subarrays. An even - odd subarray is a subarray that contains the same number of even as well as odd integers. Examples : Input : arr[] = {2, 5, 7, 8} Output : 3 Explanation : There are total 3 even-odd subarrays. 1) {2, 5} 2) {7, 8} 3) {2, 5, 7
15+ min read
Distinct elements in subarray using Mo's Algorithm
Given an array âa[]â of size n and number of queries q. Each query can be represented by two integers l and r. Your task is to print the number of distinct integers in the subarray l to r. Given a[i] <= 10^6 Examples : Input : a[] = {1, 1, 2, 1, 2, 3} q = 3 0 4 1 3 2 5Output : 2 2 3In query 1, nu
15 min read
Construct an Array having K Subarrays with all distinct elements
Given integers N and K, the task is to construct an array arr[] of size N using numbers in the range [1, N] such that it has K sub-arrays whose all the elements are distinct. Note: If there are multiple possible answers return any of them. Examples: Input: N = 5, K = 8Output: {1, 2, 3, 3, 3}Explanat
7 min read
Count Subarrays with Consecutive elements differing by 1
Given an array arr[] of N integers. The task is to count the total number of subarrays of the given array such that the difference between the consecutive elements in the subarrays is one. That is, for any index i in the subarrays, arr[i+1] - arr[i] = 1. Note: Do not consider subarrays with a single
12 min read
Longest subarray not having more than K distinct elements
Given N elements and a number K, find the longest subarray which has not more than K distinct elements.(It can have less than K). Examples: Input : arr[] = {1, 2, 3, 4, 5} k = 6 Output : 1 2 3 4 5 Explanation: The whole array has only 5 distinct elements which is less than k, so we print the array i
8 min read