not working for some test cases.the code seems fine although.can u plz check wats the problem
Subarray with distinct elements
hey @AY_Codess
Just a changes inside the sum fun :
while (j < n && !hs.contains(arr[j])) {
hs.add(arr[j]); instead of arr[i ]
j++;
}
correct code :
import java.io.;
import java.util.;
import java.math.*;
public class Main {
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = scn.nextInt();
System.out.println((int) (sum(arr, n) % (7 + Math.pow(10, 9))));
}
public static int sum(int[] arr, int n) {
HashSet<Integer> hs = new HashSet<>();
int j = 0, ans = 0;
for (int i = 0; i < n; i++) {
while (j < n && !hs.contains(arr[j])) {
hs.add(arr[j]);
j++;
}
ans += ((j - i) * (j - i + 1)) / 2;
hs.remove(arr[i]);
}
return ans;
}
}