The problem is old and simple but I wanted to try it in a different way. With some extra memory I have created an OOP-based solution. Hopefully it doesn't hurt in the interview.
import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
static class Solution {
private int[] items;
private List<Integer> duplicates;
Solution(int[] items) {
this.items = items;
this.duplicates = new ArrayList<>();
if (items.length > 1) {
solve();
}
}
private void solve() {
Set<Integer> appeared = new HashSet<>();
for (int item : items) {
if (!appeared.add(item)) {
duplicates.add(item);
}
}
}
public boolean hasDuplicate() {
return duplicates.size() > 0 ? true : false;
}
}
private static int[] readInput() {
Scanner s = new Scanner(System.in);
int N = s.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static void tests() {
// Falsy
System.out.println(new Solution(new int[]{}).hasDuplicate());
System.out.println(new Solution(new int[]{1}).hasDuplicate());
System.out.println(new Solution(new int[]{1, 2}).hasDuplicate());
System.out.println(new Solution(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE}).hasDuplicate());
// Truthy
System.out.println(new Solution(new int[]{1, 1}).hasDuplicate());
System.out.println(new Solution(new int[]{Integer.MAX_VALUE, Integer.MAX_VALUE}).hasDuplicate());
System.out.println(new Solution(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE}).hasDuplicate());
}
public static void main(String[] args) {
//System.out.println(new Solution(readInput()).hasDuplicate());
tests();
}
}
Note: I cannot use JUnit
or any testing framework during the interview.