In: Computer Science
Using Java please
You are given an array of integers arr. Your task is to count the number of contiguous subarrays, such that each element of the subarray appears at least twice. E.g For arr = [0, 0, 0], the output should be duplicatesOnSegment(arr) = 3.
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
import java.util.Scanner;
import java.util.HashMap;
public class Hello
{
// function to count the number of contiguous
subarrays, such that each element of the subarray appears at least
twice
public static int duplicatesOnSegment(int[] arr)
{
// get the length of array
int n = arr.length;
// initialize ans = 0
int ans = 0;
// iterate over the array
for(int i=0;i<n;i++)
{
// declare a hashmap
HashMap<Integer, Integer> hmap = new HashMap<Integer,
Integer>();
// initialize a counter count_unique to count unique numbers
int count_unique=0;
// iterate from i to 0
for(int j=i;j>=0;j--)
{
int x = arr[j];
// if the element is present in hashmap then increment its
frequency
if (hmap.containsKey(x))
{
hmap.put(x, hmap.get(x) + 1);
}
// otherwise initialize its frequency to 1
else
{
hmap.put(x, 1);
}
// now if the element is present in the map then get its
value
if(hmap.get(x)!=-1)
{
int val=hmap.get(x);
// if value is 1 then increment count_unique
if(val==1)
count_unique++;
// if the value is 2 then decrement count_unique
else if(val==2)
count_unique--;
}
// if the count_unique counter becomes 0 then increment
answer
if(count_unique==0)
{
ans++;
}
}
}
return ans;
}
// main function
public static void main(String []args)
{
// make an object of Scanner class
Scanner sc = new Scanner(System.in);
// input the size of array
int n = sc.nextInt();
// declare an array of size n
int[] arr = new int[n];
// input array elements
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
// call the function
int res = duplicatesOnSegment(arr);
// print the result
System.out.println(res);
}
}