The challenge
An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted.
Example:
- The starting array sequence is
[1,2,3,4,5,6,7,8,9]
- The mixed array with one deleted number is
[3,2,4,6,7,8,1,9]
- Your function should return the int
5
.
If no number was deleted from the array and no difference with it, your function should return the int ``.
Note that N may be 1 or less (in the latter case, the first array will be []
).
The solution in Java code
Option 1:
import java.util.stream.IntStream;
public class Solution {
public static int findDeletedNumber(int[] arr, int[] mixedArr) {
return IntStream.of(arr).sum() - IntStream.of(mixedArr).sum();
}
}
Option 2:
import java.util.Arrays;
public class Solution {
public static int findDeletedNumber(int[] arr, int[] mixedArr) {
return Arrays.stream(arr)
.filter(arrElement -> Arrays.stream(mixedArr).noneMatch(mixedElement -> arrElement == mixedElement))
.findFirst()
.orElse(0);
}
}
Option 3:
import static java.util.stream.IntStream.of;
class Solution {
static int findDeletedNumber(int[] arr, int[] mixedArr) {
return arr.length == mixedArr.length ? 0 : arr.length * (arr.length + 1) / 2 - of(mixedArr).sum();
}
}
Test cases to validate our solution
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void basicTests() {
assertEquals(2, Solution.findDeletedNumber(new int[]{1,2,3,4,5}, new int[]{3,4,1,5}));
assertEquals(5, Solution.findDeletedNumber(new int[]{1,2,3,4,5,6,7,8,9}, new int[]{1,9,7,4,6,2,3,8}));
assertEquals(0, Solution.findDeletedNumber(new int[]{1,2,3,4,5,6,7,8,9}, new int[]{5,7,6,9,4,8,1,2,3}));
}
}