Find the Unique Number Using Java


The challenge

There is an array with some numbers. All numbers are equal except for one. Try to find it!

Solution.findUniq(new double[]{ 1, 1, 1, 2, 1, 1 }); // => 2
Solution.findUniq(new double[]{ 0, 0, 0.55, 0, 0 }); // => 0.55

It’s guaranteed that array contains at least 3 numbers.

The tests contain some very huge arrays, so think about performance.

The solution in Java code

Option 1:

import java.util.Arrays;
 public class Solution {
    public static double findUniq(double[] arr) {
      Arrays.sort(arr);
      return arr[0] == arr[1] ? arr[arr.length-1]:arr[0];
    }
}

Option 2:

public class Solution {
  public static double findUniq(double arr[]) {
    final double x = arr[arr[0] == arr[1] ? 0 : 2];
    for (double y : arr)
      if (y != x)
        return y;
    throw new RuntimeException("no unique number found");
  }
}

Option 3:

import java.util.Arrays;
import java.util.Map.Entry;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

class Solution {
    static double findUniq(final double[] array) {
        return Arrays.stream(array).boxed()
                .collect(groupingBy(identity(), counting()))
                .entrySet().stream()
                .filter(e -> e.getValue() == 1)
                .findFirst()
                .map(Entry::getKey)
                .orElse(0.0);
    }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class FindUniqTest {
    private double precision = 0.0000000000001;
    
    @Test
    public void sampleTestCases() {
        assertEquals(1.0, Solution.findUniq(new double[]{0, 1, 0}), precision);
        assertEquals(2.0, Solution.findUniq(new double[]{1, 1, 1, 2, 1, 1}), precision);
    }
}