Skip to content

Commit

Permalink
problem(442):find-all-duplicates-in-an-array
Browse files Browse the repository at this point in the history
  • Loading branch information
zyberzebra committed Mar 25, 2024
1 parent 42c2ff4 commit 44b6cbc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/main/java/problems/FindAllDuplicatesInAnArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package problems;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
* <a href="https://leetcode.com/problems/find-all-duplicates-in-an-array">find-all-duplicates-in-an-array</a>
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FindAllDuplicatesInAnArray {
static List<Integer> findDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return Collections.emptyList();
}
int max = Arrays.stream(nums).max().getAsInt();
int[] count = new int[max + 1];
for (int num : nums) {
count[num]++;
}
List<Integer> duplicates = new ArrayList<>();
for (int i = 0; i < count.length; i++) {
if (count[i] > 1) {
duplicates.add(i);
}
}
return duplicates;
}


}
29 changes: 29 additions & 0 deletions src/test/java/problems/FindAllDuplicatesInAnArrayTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package problems;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.List;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;

class FindAllDuplicatesInAnArrayTest {

public static Stream<Arguments> numbers() {
return Stream.of(
Arguments.of(new int[]{4,3,2,7,8,2,3,1}, List.of(2,3)),
Arguments.of(new int[]{1,1,2}, List.of(1)),
Arguments.of(new int[]{1}, List.of()),
Arguments.of(new int[]{}, List.of()),
Arguments.of(null, List.of())
);
}

@ParameterizedTest
@MethodSource("numbers")
void findDuplicates(int[] arr, List<Integer> expected) {
assertThat(FindAllDuplicatesInAnArray.findDuplicates(arr)).isEqualTo(expected);
}
}

0 comments on commit 44b6cbc

Please sign in to comment.