Skip to content

Commit

Permalink
Count distincts in every sub-array
Browse files Browse the repository at this point in the history
  • Loading branch information
AnghelLeonard committed Feb 27, 2020
1 parent c208a92 commit 2ff1ab1
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Chapter10/CountDistinctInSubarray/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coding.challenge</groupId>
<artifactId>CountDistinctInSubarray</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>13</maven.compiler.target>
</properties>
<name>CountDistinctInSubarray</name>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package coding.challenge;

import java.util.HashMap;
import java.util.Map;

public final class Arrays {

private Arrays() {
throw new AssertionError("Cannot be instantiated");
}

public static void find(int[] m, int n) {

if (m == null) {
throw new IllegalArgumentException("The given array cannot be null");
}

if (n <= 0) {
throw new IllegalArgumentException("The given sub-array size cannot be <= 0");
}

// store frequency of elements in current window of size n
Map<Integer, Integer> frequency = new HashMap<>();

// count distinct elements in every sub-array of size n
int countDistinct = 0;

for (int i = 0; i < m.length; i++) {

// skip first n elements
if (i >= n) {
// Remove first element from the sub-array
frequency.putIfAbsent(m[i - n], 0);
frequency.put(m[i - n], frequency.get(m[i - n]) - 1);

// reduce distinct count if we are left with 0
if (frequency.get(m[i - n]) == 0) {
countDistinct--;
}
}

// add current element to the sub-array
frequency.putIfAbsent(m[i], 0);
frequency.put(m[i], frequency.get(m[i]) + 1);

// element is for the first time in current window?
if (frequency.get(m[i]) == 1) {
countDistinct++;
}

if (i >= n - 1) {
System.out.println("Distinct elements in the "
+ "sub-array [" + (i - n + 1) + ", " + i + "]" + " is "
+ countDistinct);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package coding.challenge;

public class Main {

public static void main(String[] args) {

int[] m = {7, 11, 11, -5, 13, 13, 13, 15, -4, -3, -4, 15, -2, 0, 0, 0, 14, 3, 7, 42, 3};
int k = 5;

System.out.println("Array: " + java.util.Arrays.toString(m));

Arrays.find(m, k);
}
}

0 comments on commit 2ff1ab1

Please sign in to comment.