Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of Count of Unique Numbers in all Subarrays
Next article icon

Find sum of count of duplicate numbers in all subarrays of given array

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N. The task it to find the sum of count of duplicate numbers in all subarrays of given array arr[]. For example array {1, 2, 3, 2, 3, 2} has two duplicate elements (i.e, 2 and 3 come more than one time in the array).

Examples:

Input: N = 2, arr = {3,3}
Output: 1
Explanation: All subarrays of the arr are {3}, {3,3}, {3} have values 0, 1, 0 respectively, so the answer is 1.

Input: N = 4, arr = {1, 2, 1, 2}
Output: 4
Explanation: All subarrays of the arr are {1},{1,2},{1,2,1},{1,2,1,2},{2},{2,1},{2,1,2},{1},{1,2},{2} have values 0,0,1,2,0,0,1,0,0,0 respectively, so answer is 4.

Approach: This can be solved with the following idea:

To avoid considering all possible subarrays, we can use below approach:

We can first create a map that stores the positions of each distinct element in the array. Then, for each distinct element, we calculate the contribution of subarrays that contain this element. This avoids the need to iterate through all subarrays explicitly.

Step-by-step approach:

  • Initialize an unordered map mp of arrays m to store all positions of each distinct element in the array.
  • Iterate through the array arr and populate the map. For each element, append its position to the corresponding entry in the map.
  • Initialize a variable ans for answer.
  • Iterate through the entries in the mp:
    • If an element appears only once, continue to the next element as there can be no subarray with distinct elements that appear more than once.
    • For elements that appear more than once, calculate their contribution to the count of subarrays:
      • Initialize a variable prev to -1 to represent the position before the first occurrence of the element.
      • Iterate through the positions of the element and calculate the contribution of subarrays containing this element. The contribution is determined by the product of the distance to the previous occurrence of the element and the distance to the next occurrence.
      • Update ans with the calculated contribution, taking the modulo operation to avoid integer overflow.
      • Update prev to the current position.
  • Return the final value of ans.

Below is the implementation of the above approach:

C++
// C++ Implementation #include <bits/stdc++.h> #include <iostream> using namespace std;  // Function to find the values of subarrays int ValueOfSubarrays(int N, vector<int>& arr) {      int i = 0;      // Initailze a map     unordered_map<int, vector<int> > mp;      // Iterate in array     while (i < arr.size()) {          mp[arr[i]].push_back(i);         i++;     }      i = 0;     int mod = 1e9 + 7;     long long prev = -1;     long long ans = 0;      // Interate in map     for (auto a : mp) {         prev = -1;          // I frequency is 1         if (a.second.size() == 1) {             continue;         }         int j = 0;          // Iterate to find the impact of each element         while (j < a.second.size() - 1) {             ans += (a.second[j] - prev)                    * (N - a.second[j + 1]);             ans %= mod;             prev = a.second[j];             j++;         }     }      // Return the value     return ans; }  // Driver code int main() {      int N = 5;     vector<int> arr = { 1, 2, 2, 3, 2 };      // Function call     cout << ValueOfSubarrays(N, arr);     return 0; } 
Java
import java.util.*;  public class SubarraysValue {      // Function to find the values of subarrays     static int valueOfSubarrays(int N, ArrayList<Integer> arr) {          int i = 0;          // Initialize a map         HashMap<Integer, ArrayList<Integer>> mp = new HashMap<>();          // Iterate in array         while (i < arr.size()) {             if (!mp.containsKey(arr.get(i))) {                 mp.put(arr.get(i), new ArrayList<>());             }             mp.get(arr.get(i)).add(i);             i++;         }          i = 0;         int mod = (int) 1e9 + 7;         long prev = -1;         long ans = 0;          // Iterate in map         for (Map.Entry<Integer, ArrayList<Integer>> entry : mp.entrySet()) {             prev = -1;              // If frequency is 1             if (entry.getValue().size() == 1) {                 continue;             }             int j = 0;              // Iterate to find the impact of each element             while (j < entry.getValue().size() - 1) {                 ans += (entry.getValue().get(j) - prev) * (N - entry.getValue().get(j + 1));                 ans %= mod;                 prev = entry.getValue().get(j);                 j++;             }         }          // Return the value         return (int) ans;     }      // Driver code     public static void main(String[] args) {          int N = 5;         ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 2, 3, 2));          // Function call         System.out.println(valueOfSubarrays(N, arr));     } } 
Python3
def value_of_subarrays(N, arr):     # Initialize a dictionary to store indices of each element     mp = {}      # Iterate in array     i = 0     while i < len(arr):         if arr[i] not in mp:             mp[arr[i]] = []         mp[arr[i]].append(i)         i += 1      i = 0     mod = 10**9 + 7     prev = -1     ans = 0      # Iterate in the dictionary     for key, value in mp.items():         prev = -1          # If frequency is 1, no impact on subarrays         if len(value) == 1:             continue          j = 0          # Iterate to find the impact of each element         while j < len(value) - 1:             ans += (value[j] - prev) * (N - value[j + 1])             ans %= mod             prev = value[j]             j += 1      # Return the value     return ans  # Driver code if __name__ == "__main__":     N = 5     arr = [1, 2, 2, 3, 2]      # Function call     print(value_of_subarrays(N, arr)) 
C#
using System; using System.Collections.Generic;  public class SubarraysValue {     // Function to find the values of subarrays     static int ValueOfSubarrays(int N, List<int> arr)     {         int i = 0;          // Initialize a dictionary         Dictionary<int, List<int>> mp = new Dictionary<int, List<int>>();          // Iterate in array         while (i < arr.Count)         {             if (!mp.ContainsKey(arr[i]))             {                 mp[arr[i]] = new List<int>();             }              mp[arr[i]].Add(i);             i++;         }          i = 0;         int mod = (int)1e9 + 7;         long prev = -1;         long ans = 0;          // Iterate in dictionary         foreach (var a in mp)         {             prev = -1;              // If frequency is 1             if (a.Value.Count == 1)             {                 continue;             }              int j = 0;              // Iterate to find the impact of each element             while (j < a.Value.Count - 1)             {                 ans += (a.Value[j] - prev) * (N - a.Value[j + 1]);                 ans %= mod;                 prev = a.Value[j];                 j++;             }         }          // Return the value         return (int)ans;     }      // Driver code     public static void Main()     {         int N = 5;         List<int> arr = new List<int> { 1, 2, 2, 3, 2 };          // Function call         Console.WriteLine(ValueOfSubarrays(N, arr));     } } //this code is contributed by Aman 
JavaScript
function valueOfSubarrays(N, arr) {     // Initialize a Map to store indices of each element     let mp = new Map();      // Iterate in array     for (let i = 0; i < arr.length; i++) {         if (!mp.has(arr[i])) {             mp.set(arr[i], []);         }         mp.get(arr[i]).push(i);     }      let mod = 10**9 + 7;     let prev = -1;     let ans = 0;      // Iterate in the Map     for (let [key, value] of mp) {         prev = -1;          // If frequency is 1, no impact on subarrays         if (value.length === 1) {             continue;         }          let j = 0;          // Iterate to find the impact of each element         while (j < value.length - 1) {             ans += (value[j] - prev) * (N - value[j + 1]);             ans %= mod;             prev = value[j];             j++;         }     }      // Return the value     return ans; }  // Driver code let N = 5; let arr = [1, 2, 2, 3, 2];  // Function call console.log(valueOfSubarrays(N, arr)); 

Output
7

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Sum of Count of Unique Numbers in all Subarrays

S

suru21
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • Hash
  • Geeks Premier League 2023
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Sum of Count of Unique Numbers in all Subarrays
    Given an array of n integers, the task is to count the sum of unique numbers in all subarrays. Examples: Input: [2, 1, 2]Output: 9Explanation: There are total 6 subarrays which are [2], [2, 1], [2, 1, 2], [1], [1, 2], [2]. The count of unique numbers in these subarrays is 1, 2, 2, 1, 2, 1 respective
    15+ min read
  • Count number of distinct pairs whose sum exists in the given array
    Given an array of N positive integers. Count the number of pairs whose sum exists in the given array. While repeating pairs will not be counted again. And we can't make a pair using same position element. Eg : (2, 1) and (1, 2) will be considered as only one pair. Please read all examples carefully.
    7 min read
  • Find all duplicate and missing numbers in given permutation array of 1 to N
    Given an array arr[] of size N consisting of the first N natural numbers, the task is to find all the repeating and missing numbers over the range [1, N] in the given array. Examples: Input: arr[] = {1, 1, 2, 3, 3, 5}Output: Missing Numbers: [4, 6]Duplicate Numbers: [1, 3]Explanation:As 4 and 6 are
    8 min read
  • Count of Subarrays not containing all elements of another Array
    Given two arrays nums[] of size N and target[]. The task is to find the number of non-empty subarrays of nums[] that do not contain every number in the target[]. As the answer can be very large, calculate the result modulo 109+7. Examples: Input: nums = {1, 2, 2}, target = {1, 2}Output: 4Explanation
    12 min read
  • Count of distinct pair sum in given Array
    Given an array arr[] of size N, the task is to find the total number of unique pair sums possible from the array elements. Examples: Input: arr[] = {6, 1, 4, 3}Output: 5Explanation: All pair possible are {6, 1}, {6, 4}, {6, 3}, {1, 4}, {1, 3}, {4, 3}. Sums of these pairs are 7, 10, 9, 5, 4, 7. So un
    4 min read
  • Count of Subarrays with sum equals k in given Binary Array
    Given a binary array arr[] and an integer k, the task is to find the count of non-empty subarrays with a sum equal to k. Examples: Input: arr[] = {1, 0, 1, 1, 0, 1}, k = 2Output: 6Explanation: All valid subarrays are: {1, 0, 1}, {0, 1, 1}, {1, 1}, {1, 0, 1}, {0, 1, 1, 0}, {1, 1, 0}. Input: arr[] = {
    10 min read
  • Count of Subarrays in an array containing numbers from 1 to the length of subarray
    Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array. Examples: Input: arr[] = {4, 1, 3, 2, 5, 6} Output: 5 Explanation: Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1
    7 min read
  • Find duplicates in an Array with values 1 to N using counting sort
    Given a constant array of N elements which contain elements from 1 to N - 1, with any of these numbers appearing any number of times.Examples: Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explana
    11 min read
  • Number of sub-arrays that have at least one duplicate
    Given an array arr of n elements, the task is to find the number of the sub-arrays of the given array that contain at least one duplicate element. Examples: Input: arr[] = {1, 2, 3} Output: 0 There is no sub-array with duplicate elements. Input: arr[] = {4, 3, 4, 3} Output: 3 Possible sub-arrays are
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences