Related
I am doing a question on leetcode, 66. Plus One.
You are given a large integer represented as integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
My solution is:
class Solution {
public int[] plusOne(int[] digits) {
int num = 0;
for (int a : digits) {
num = 10*num + a;
}
int n=num+1;
String str=String.valueOf(n);
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++){
arr[i]=str.charAt(i)-'0';
}
return arr;
}
}
I am getting many test cases failed, one being:
Input:
[9,8,7,6,5,4,3,2,1,0]
Output:
[1,2,8,6,6,0,8,6,1,9]
Expected:
[9,8,7,6,5,4,3,2,1,1]
Can anyone help me with it?
Think before you leap. And consider the edges.
Why would they do the seemingly idiotic move of storing an number, digit by digit, in an int array? Makes no sense, right?
Except... computers aren't magic. int can't represent any number. A computer's storage is not infinite. Specifically, an int covers 32 bits (4 bytes), and thus can only represent at most 2^32 different numbers. int 'uses' its alloted space of 2^32 by dividing it evenly amongst positive and negative numbers, but negative numbers get one more (because the '0' is in the positive space). In other words, all numbers from -2^31 to +2^31-1, inclusive.
9876543210 is larger than that.
You're trying to turn that array of digits into an int and that is a dead end. Once you do that, you get wrong answers and there is no fixing this. your algorithm is wrong. You can figure this stuff out, and you should always do that with leetcode-style problems, by first carefully reading the assignment. The assignment covers the limits. It says how large these arrays can be, and I'm sure it says that they can be quite large; large enough that the number inside it is larger than 2^31-1. Probably larger than 2^63-1 (which a long can reach).
Then you know the algorithm you need to write can't involve 'turn it into an int first'. That's usually the point (many problems are trivial if small, but become interesting once you make things large).
The algorithm they want you to write must not involve any conversion whatsoever. Increment the array in place. This isn't hard (just think about it: without converting anything, how do you turn [1, 2, 3] into [1, 2, 4]? That should be simple. Then think about how to deal with [1, 9, 9]. Finally, think about how to deal with [9, 9, 9]. Then you've covered all the cases and you have your answer.
In continuation to the detailed explanation of rzwitserloot, in case you are interested in code for the problem.
class Solution {
public int[] plusOne(int[] digits) {
int size = digits.length;
int i=0;
for(i = size-1 ; i >= 0 ; i--){
if (digits[i] != 9) {
digits[i] += 1;
break;
} else {
digits[i] = 0;
}
}
if(i == -1) {
int[] newDigits = new int[size+1];
newDigits[0] = 1;
return newDigits;
}
return digits;
}
}
This is a pretty trivial task, but in some test cases the value is too high to represent even as long, so the best candidate is BigInteger.
public int[] plusOne(int[] digits) {
BigInteger val = BigInteger.ZERO;
for (int i = 0; i < digits.length; i++)
val = val.multiply(BigInteger.TEN).add(BigInteger.valueOf(digits[i]));
val = val.add(BigInteger.ONE);
String str = val.toString();
digits = str.length() == digits.length ? digits : new int[str.length()];
for (int i = 0; i < digits.length; i++)
digits[i] = str.charAt(i) - '0';
return digits;
}
P.S. Sure, you can do this without BigInteger.
public int[] plusOne(int[] digits) {
boolean carry = true;
for (int i = digits.length - 1; carry && i >= 0; i--) {
carry = digits[i] == 9;
digits[i] = carry ? 0 : digits[i] + 1;
}
if (carry) {
int[] tmp = new int[digits.length + 1];
tmp[0] = 1;
System.arraycopy(digits, 0, tmp, 1, digits.length);
digits = tmp;
}
return digits;
}
Think about a mileage counter in a car. How does it work?
Whenever a 9 turns around, it turns the number left to it too.
So for incrementing by one, you'd start from the right, increment by one and if you incremented it to a 10, set it to a 0 instead and continue with the next digit to the left. If you reached the leftmost digit and still didnt finish, add a 1 to the left and set everything else to 0.
Example:
8
9 <- incremented rightmost
10 <- 9 turned to a 10, leftmost digit reached, add a 1 to the left and set everything else to 0
...
18
19 <- incremented rightmost
20 <- 9 turned to a 10, set to 0 instead, increment the next one to the left (1 -> 2), finished
...
108
109 <- incremented rightmost
110 <- 9 turned to a 10, set to 0 instead, increment the next one to the left (1 -> 2), finished
...
998
999 <- incremented rightmost
1000 <- 9 turned to a 10, set to 0 instead, increment the next one to the left, turned to a 10 too, set to 0 instead, ...
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Scratch {
public static void main(String[] args) {
int[] digits = new int[0];
for (int i = 0; i < 100; i++) {
digits = plusOne(digits);
System.out.println(IntStream.of(digits).mapToObj(Integer::toString).collect(Collectors.joining()));
}
}
public static int[] plusOne(int[] digits) {
boolean finished = false;
for (int i = digits.length - 1; !finished && i >= 0; i--) {
if (++digits[i] % 10 == 0) {
digits[i] = 0;
} else {
finished = true;
}
}
if (!finished) {
// not finished after exiting the loop: every digit was turned from a 9 to a 10 -> we need one digit more
// initialize a new array with a length of 1 more digit, set the leftmost (index 0) to 1 (everything else is 0 by default)
digits = new int[digits.length + 1];
digits[0] = 1;
}
return digits;
}
}
plus one in leetcode solve on dart language
class Solution {
List<int> plusOne(List<int> digits) {
for(int i=digits.length - 1; i>=0; i--){
if(digits[i] < 9){
++digits[i];
return digits;
}
digits[i]=0;
}
List<int> ans = List.filled(digits.length+1, 0);
ans[0]=1;
return ans;
}
}
Here is my solution:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Plus One.
Memory Usage: 40.8 MB, less than 92.31% of Java online submissions for Plus One. for Plus One.
public int[] plusOne(int[] digits) {
for(int i=digits.length-1;i>=0;i--) {
if(digits[i]<9) {
digits[i]=digits[i]+1;
return digits;
}else {
digits[i]=0;
if(i==0) {
digits= new int[digits.length+1];
digits[0]=1;
}
}
}
return digits;
}
My solution:
Runtime: 0 ms, Memory Usage: 2.1 MB,
play.golang link: https://go.dev/play/p/Vm28BdaIi2x
// function to add one digit based on diff scenarios
func plusOne(digits []int) []int {
i := len(digits) - 1
// while the index is valid and the value at [i] ==
// 9 set it as 0 and move index to previous value
for i >= 0 && digits[i] == 9 {
digits[i] = 0
i--
}
if i < 0 {
//leveraging golang's simplicity with append internal method for array
return append([]int{1}, digits...)
} else {
digits[i]++
}
return digits
}
I am trying to identify a solution (preferably in JAVA) for the given scenario :
Input :
Binary String : e.g. "1001"
N - Number Of Iterations
K - String index position
After each iteration, all the 1s become "01" and 0s become "10"
e.g.
initial value/input --> "1001"
after 1st iteration --> "01101001"
after 2nd iteration --> "1001011001101001"
...
...
after Nth iteration --> "100101011......[Kth index value]......00101010111.." (here our program needs to find the Kth index value that would be either 0 or 1)
Output :
value (either 0 or 1) at kth index after N iterations.
After N iterations, each original digit becomes 2N digits, so skip digits until we get close to K.
E.g. for input "1001", N=3, K=20, the 1st digit becomes 8 digits, so if we skip those 8 digits twice, i.e. skip 2 original digits = 16 K's, we're at the 3nd original digit (a 0), and have a remaining K=4.
We then apply an iteration on that digit, and get 0 -> "10". We can now restart the operation, with input "10", N=2, K=4.
Repeat until done. Solution in O(N), regardless of input length or value of K.
Of course, you could just brute-force it, but that won't perform well at higher values, since solution is O(L * 2N), with L being the input length.
// Brute-force solution
static char solve(String input, int n, int k) {
String s = input;
for (int i = 0; i < n; i++)
s = s.chars().mapToObj(c -> c == '0' ? "10" : "01").collect(Collectors.joining());
return s.charAt(k); // assuming k is 0-based
}
Compact version of solution described above:
// Optimized solution
static char solve(String input, int n, int k) {
for (; n > 0; k %= 1 << n--)
input = input.charAt(k / (1 << n)) == '0' ? "10" : "01";
return input.charAt(k);
}
I have two arrays A & B (size of the array is 1 to 100,000) that can take values only 1,2,3,4,5,6.
Now my task is to make minimum numbers to be changed in arrays such that the sum of both the arrays is the same.
Example 2:
A=[5,4,1,2,6,6] & B=[2], we have to make A as [1,1,1,1,1,1] so we have to change A 5 times and then B=[6] once, so function should return 6.
Example 3:
A=[1,2,3,4,3,2,1] and B[6], function should return -1.
Method signature looks like this.
public int task(int[] A, int[] B) {
int diff = Math.abs(A.length - B.length);
if(diff >=6) return -1;
//
}
I am able to get answer for example 3 with simple condition. Bit not for first 2 examples.
What approach should I follow to solve this program? As we can turn each and every element in A & B and do a comparison, but that is more complex.
The alghorithm can be as following:
Prepare data part
Go through all items in array A and B and find out how many of each number (1,2,3,4,5,6) is in each array. Preferable have 2d array that stores the indexes of those numbers, so you can easily access it later.
i.e. array A=[1,1,1,4,6,4] will be translated into new 2d array as
2darr=
[]
[0,1,2]
[]
[]
[3,5]
[]
[4]
so when you i.e. want to see how many 1 are there you can see that 2darr[1].length is 3. And when you want to find out where it is i.e. the 2darr[1][0] will get you index in source array and A[0] is indeed 1
In process you can also count the sum, but even without it, the sum now can be easily found out just going through lengths of each subarray in 2darray.
Alghoritm
To find the minimum amount of changes, you will first find out which sum is smaller and which bigger. Then the best change is to start changing 1 values to 6 in smaller array or changing 6 values to 1 in bigger arrays. Then 2 to 6 in smaller array and 5 to 1 in bigger array. And then continue with other numbers.
In process you can changing the arrays based on indexes you already have and do it as long as needed to get both arrays to same sum. This is detailed alghoritm that will show you how actually both arrays will look like to satisfy your needs. Its O(n), so there is definitely no way how to make it faster as you have to go through all fields just to get the sum.
I suggest to do it so you can see the actual result. On the other hand, if you think more deeply, it can be done more easily, if you just seek the right answer - you just need to know how many times each number in each array is and then just find out how many changes are needed just by simple math. You already know, you are just changing up to all 1 to 6 in smaller array and up to all 6 to 1 in bigger array and it can be just counted easily how many of them you need to change and if it is sufficient or you change all of them and then you will continue with 5 to 1 and 2 to 6 etc.
Example
Imagine that A.length is 500 and B.length is 300. The sum of A=1000and B=700. You find out that A has 30 repetitions of number 6 and B has 20 repetitions of number 1. In A you change all those 6 to 1, therefore reducing it by 30*5=150 to total of A=850 and in B you change all those 1 to 6 and increasing the value 20*5=100 and therefore B=800. You did 50 changes in total.
Then you continue with higher number in smaller array and with lower number in bigger array. You find out that A has 100 numbers of 5. Reducing 5 to 1 decreases value by 4 for each. Right now you have only 50 value difference. 50/4=12.5, therefore you need to change 13 numbers and you are done. The answer is that minimum amount of changes is 63.
The impossibility-criteria is a simple one as you suspect, but it is different from what you guess: it depends on the length of the arrays, which determines their minimal and maximal sums. The shorter array can not produce a sum which is greater than 6 times its length (all elements are 6s) and the longer array can not produce a sum which is less than its length (all elements are 1s):
if( Math.min(A.length, B.length) * 6 < Math.max(A.length ,B.length) )
return -1;
Then you need the sums and the statistics what the other answer describes, but maybe there is place for a slightly different explanation. In order to have the two sums meet, the smaller one can be increased and the larger one can be decreased. For having the minimum amount of steps, you always want to make the largest steps possible, via starting to replace 1s with 6s in the smaller sum (each replacement increasing the sum by 5) and 6s with 1s in the larger sum (each replacement decreasing it by 5), and so on.
As you do not want to generate the steps (at least to my understanding), actually you can track the difference only and also count the pairs together (6s in the larger-sum-array and 1s in the smaller-sum-array, then the same with 5-2, etc.). And in fact you can do this pairing even at the beginning, without knowing which one is the larger/smaller sum, because the pairs will stay pairs, just their direction changes.
Example is JavaScript so it can run here, but I try to write it as Java as possible:
function task(A,B){
if( Math.min(A.length, B.length) * 6 < Math.max(A.length, B.length) )
return -1;
var diff=0;
var statistics=[0,0,0,0,0,0]; // would be a new int[6] in Java
for(var item of A){ // for(int item : A) in Java
// this loop guesses that A has the larger sum
diff+=item;
statistics[item-1]++; // 1s are counted in [0], 2s in [1], ... 6s in [5]
}
for(var item of B){ // for(int item : B) in Java
// this loop guesses that B has the smaller sum
diff-=item;
statistics[6-item]++; // 1s are counted in [5], 2s in [4], ... 6s in [0]
}
if(diff<0){
// the guess was wrong, swaps are needed
diff=-diff;
for(var i=0;i<3;i++){
var swap=statistics[i];
statistics[i]=statistics[5-i];
statistics[5-i]=swap;
}
}
var log=[A.join()," ",B.join()," ",diff," ",statistics.join()].join(); // <-- this one...
// at this point
// - array indices are conveniently denoting step sizes
// - diff is non-negative
// - and we know there is a solution (so we won't run out of array indices for example)
var changes=0;
var i=5;
while(diff>0){
var step = Math.min(statistics[i], Math.ceil(diff/i));
// would better be "int step = Math.min(statistics[i], (diff+i-1)/i);" in Java
// as Math.ceil() produces a double
changes += step;
diff -= i*step;
i--;
}
return [changes," ",log].join(); // <-- ... and this
// are only visuals
return changes;
}
console.log(task([1,2,3,4,3,2,1],[6]));
console.log(task([6],[1,2,3,4,3,2,1]));
console.log(task([2,3,1,1,2],[5,4,6]));
console.log(task([5,4,6],[2,3,1,1,2]));
console.log(task([5,4,1,2,6,6],[2]));
console.log(task([2],[5,4,1,2,6,6]));
At the end I've just thrown it together in Java too: https://ideone.com/mP3Sel
As others have noted, we can solve this with a greedy algorithm. Count the frequencies of numbers for each array, then iterate from the outside in. For the array with the larger sum, iterate over the negative multipliers; for the array with the smaller sum, the positive. Choose the greatest absolute multiplier, then the max frequency available (and needed) each time, and as soon as the sum difference is equal or reverses sign, stop.
2 3 1 1 2 = 9
mult 5 4 3 2 1 0
freq 2 2 1 0 0 0
^ -->
5 4 6 = 15
mult 0 -1 -2 -3 -4 -5
freq 0 0 0 1 1 1
<-- ^
function f(A, B){
let freqSm = [0, 0, 0, 0, 0, 0];
let freqLg = [0, 0, 0, 0, 0, 0];
let smSum = 0;
let lgSum = 0;
let sm = 'A';
let lg = 'B';
A.map(x => {
freqSm[x-1]++;
smSum += x;
});
B.map(x => {
freqLg[x-1]++;
lgSum += x;
});
if (lgSum < smSum){
sm = 'B';
lg = 'A';
let [_freq, _sum] = [freqSm, smSum];
freqSm = freqLg;
freqLg = _freq;
smSum = lgSum;
lgSum = _sum;
}
const smMult = [5, 4, 3, 2, 1, 0];
const lgMult = [0,-1,-2,-3,-4,-5];
const changes = [];
let diff = lgSum - smSum;
function numTxt(count, num){
const ws = [, 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
const countTxt = count < 10 ? ws[count] : count;
return `${ countTxt } ${ num }${ count > 1 ? 's' : '' }`;
}
function incSm(i){
const rem = diff % smMult[i];
const mult = Math.min(freqSm[i], Math.ceil(diff / smMult[i]));
diff -= mult * smMult[i];
let txt;
if (diff < 0 && rem){
if (mult > 1)
txt = `Change ${ numTxt(mult-1, i+1) } to 6 and one to ${ i + 1 + rem } in ${ sm }.`;
else
txt = `Change one ${ i + 1 } to ${ i + 1 + rem } in ${ sm }.`;
} else {
txt = `Change ${ numTxt(mult, i+1) } to 6 in ${ sm }.`;
}
changes.push(txt);
}
function decLg(j){
const rem = diff % -lgMult[j];
const mult = Math.min(freqLg[j], Math.ceil(-diff / lgMult[j]));
diff += mult * lgMult[j];
let txt;
if (diff < 0 && rem){
if (mult > 1)
txt = `Change ${ numTxt(mult-1, j+1) } to 1 and one to ${ j + 1 - rem } in ${ lg }.`;
else
txt = `Change one ${ j + 1 } to ${ j + 1 - rem } in ${ lg }.`;
} else {
txt = `Change ${ numTxt(mult, j+1) } to 1 in ${ lg }.`;
}
changes.push(txt);
}
for (let i=0; i<6; i++){
const j = 5 - i;
if (freqSm[i] >= freqLg[j]){
if (freqSm[i]){
incSm(i);
if (diff <= 0)
return changes.join('\n');
}
if (freqLg[j]){
decLg(j);
if (diff <= 0)
return changes.join('\n');
}
} else {
if (freqLg[j]){
decLg(j);
if (diff <= 0)
return changes.join('\n');
}
if (freqSm[i]){
incSm(i);
if (diff <= 0)
return changes.join('\n');
}
}
}
return -1;
}
var input = [
[[2,3,1,1,2], [5,4,6]],
[[5,4,1,2,6,6], [2]],
[[1,2,3,4,3,2,1], [6]]
];
for (let [A, B] of input){
console.log(`A: ${ A }`);
console.log(`B: ${ B }`);
console.log(f(A, B));
console.log('');
}
I want to create a random String of numbers.
From 0-9.
10 digits long.
First digit cannot be a 0.
One of the digits has to be in the String 2 times and one has to not be there at all.
Or one digit has to be there 3 times, and 2 other digits can not be there at all.
To make this a little bit clearer here are some examples:
1223456789 - 10 digits, no starting zero, one digit (2) is there 2 times and one digit (0) is not there at all
1000345678 - 10 digits, no starting zero, one digit (0) is there 3 times and two digits (2,9) are not there at all
The starting zero is pretty easy caught with startsWith - method, but I have not found a way to check for the rest and I am not particularly good at regex while I am also not entirely sure you can even do this using regex.
For generating the random String itself, I have worked with the Random class as well as RandomStringUtils, both of which don't have restrictions on creating numbers.
Has anyone of you an idea how to achieve this?
Imagine you have 10 sacks, each one of them has its corresponding number embroided on it, from 0 to 9, like this:
.---.._
{------';
}====={
.´ '.
/ .´| \ inside there are
| | | <--- stones with '1' engraved
\: _|_ /
-__ =.´
You also have a coin to flip heads or tails on your hand.
.------..-
´ . /___ `.`.
; / / ´} ; ; ______________________________
: "|'__' // : : / |
' .|/__\. } \ ' ' /_ HEAD! You shall pick 3 |
' /"../ ' ' | stones from the 1st sack! |
; / \/ ͷ ; ; \____________________________/
`_/ ´ ´
" -------´-´
First, we will decide if we will have 3 repeating numbers or 2 repeating numbers. Flip the coin to decide! Tail is 3, Head is 2. We will call this result ͷ.
Remove the sack embroided with 0 (Zero) for a moment.
Now pick ͷ (2 or 3) stones from a random sack of the 9 sacks you have in front of you. Remember, you cannot start with 0, that is why we removed it for a moment! Remove the sack you just picked from the line of sacks, forever. You cannot pick from this one anymore. Put back the 0 (Zero) sack on the line.
Place one of the stones you just picked in front of yourself. Hold ͷ-1 in your hand.
Now repeat this until you have 9 stones in your hand:
Select a random sack, pick ONE stone from it and hold it in your hand. Remove the sack from the
line.
By the end of this process, you will have 9 stones in your hand, one in front of yourself. Shuffle up the ones in your hand. Place them in a straight line in front of yourself, next to the stone that was already in front of you.
You will end with 10 numbers, ͷ repetitions of the same number, won't start with zero, and the remaining sack(s) in front of you are just a side-effect of removing the sacks along the way.
What about trying to make what you want first using the rules then construct the rest.
Here is a possible idea
Using the first rule
One of the digits has to be in the String 2 times and one has to not be there at all.
Create a LinkedList then add the numbers 1 to 9 to it.
Generate a random number between 0-8 (range of the indexes of the list), use the index to retrieve a value out of the list (as in delete it) then add that to the String so the first number isn't 0.
Add 0 back to the list so it can be used somewhere else.
There are now 9 numbers left in the LinkedList with the first number being non zero and already in the String variable as per step 2. From here, generate another random number in the range of the LinkedList indexes. Whatever this number is, remove it from the LinkedList add it twice to the ArrayList.
There are now 8 numbers left in the LinkedList, 1 non zero number in the String. and 3 numbers in the ArrayList for a total of 4 numbers in your sequence that are confirmed to be correct. You have to get another 6 numbers to complete it. So far it would look something like this.
String sequence => "4"
ArrayList beingBuilt => [2, 6, 6]
LinkedList available => [1, 3, 4, 5, 7, 8, 9, 0]
Seems you only can have 10 numbers, loop 6 more times through the LinkedList using a random number to pluck at a random index, delete it from LinkedList add it to ArrayList.
After this the ArrayList should have 9 numbers, you could shuffle it to make it more random then convert it to a String and append to on the end of the sequence. Your rule should be satisfied now.
To make it more random you could manipulate how you pluck out numbers from the LinkedList and also the last rule you had you could change it for that too fairly simply. I used a LinkedList due to faster deletes, I did think about using a set but perhaps more work to handle the random number index being mapped to a number that actually exists in the set.
Just an idea though
The idea is: first generate a random string with 0-9 each once and not starts with 0, then: 1. replace one of the digital will another or 2.replace two digitals with another.
import java.util.Random;
public class Main {
public static void main(String[] args) {
System.out.println(generateRandomString());
System.out.println(generateRandomString());
}
public static String generateRandomString() {
String alphabet = "0123456789";
String result = "";
Random random = new Random();
// build a random string construct will 0-9 and each digital appear once
for (int i = 0; i < 10; i++) {
int index = random.nextInt(alphabet.length());
if (i == 0) { // first cannot be 0
index = random.nextInt(alphabet.length() - 1) + 1;
}
String c = alphabet.substring(index, index + 1);
result += c;
alphabet = alphabet.replace(c, "");
}
return random.nextInt(2) == 0 ? shuffle1(random, result) : shuffle2(random, result);
}
// One of the digits has to be in the String 2 times and one has to not be there at all.
private static String shuffle1(Random random, String result) {
int from = random.nextInt(10);
int to = random.nextInt(9) + 1;
while (from == to) {
to = random.nextInt(9) + 1;
}
result = result.replace(result.substring(to, to + 1), result.substring(from, from + 1));
return result;
}
// One digit has to be there 3 times, and 2 other digits can not be there at all
private static String shuffle2(Random random, String result) {
int from = random.nextInt(10);
int to1 = random.nextInt(9) + 1;
int to2 = random.nextInt(9) + 1;
while (from == to1) {
to1 = random.nextInt(9) + 1;
}
while (from == to2 || to2 == to1) {
to2 = random.nextInt(9) + 1;
}
result = result.replace(result.substring(to1, to1 + 1), result.substring(from, from + 1));
result = result.replace(result.substring(to2, to2 + 1), result.substring(from, from + 1));
return result;
}
}
If you're not too concerned about performance then the simplest thing would be to just generate random lists of numbers and check them against your conditions until you get one that works. Best to do the filtering as numbers and then convert to a string at the end rather than using regular expressions.
public String getRandomInts() {
Random random = new Random();
int[] ints;
do {
ints = random.ints(10, 0, 10).toArray();
} while (!meetsCriteria(ints));
return Arrays.stream(ints).mapToObj(String::valueOf).collect(Collectors.joining(""));
}
private boolean meetsCriteria(int[] ints) {
if (ints[0] == 0) {
return false;
}
if (frequency(ints, 0) == 1
&& frequency(ints, 1) == 8
&& frequency(ints, 2) == 1) {
return true;
}
if (frequency(ints, 0) == 2
&& frequency(ints, 1) == 7
&& frequency(ints, 3) == 1) {
return true;
}
return false;
}
private int frequency(int[] ints, int count) {
return (int) IntStream.range(0, 10)
.filter(n1 -> Arrays.stream(ints).filter(n2 -> n1 == n2).count() == count)
.count();
}
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I have an array of numbers from 1 to 100 (both inclusive). The size of the array is 100. The numbers are randomly added to the array, but there is one random empty slot in the array.
What is the quickest way to find that slot as well as the number that should be put in the slot? A Java solution is preferable.
You can do this in O(n). Iterate through the array and compute the sum of all numbers. Now, sum of natural numbers from 1 to N, can be expressed as Nx(N+1)/2. In your case N=100.
Subtract the sum of the array from Nx(N+1)/2, where N=100.
That is the missing number. The empty slot can be detected during the iteration in which the sum is computed.
// will be the sum of the numbers in the array.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
idx = i;
}
else
{
sum += arr[i];
}
}
// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;
System.out.println("missing number is: " + (total - sum) + " at index " + idx);
We can use XOR operation which is safer than summation because in programming languages if the given input is large it may overflow and may give wrong answer.
Before going to the solution, know that A xor A = 0. So if we XOR two identical numbers the value is 0.
Now, XORing [1..n] with the elements present in the array cancels the identical numbers. So at the end we will get the missing number.
// Assuming that the array contains 99 distinct integers between 1..99
// and empty slot value is zero
int XOR = 0;
for(int i=0; i<100; i++) {
if (ARRAY[i] != 0) // remove this condition keeping the body if no zero slot
XOR ^= ARRAY[i];
XOR ^= (i + 1);
}
return XOR;
//return XOR ^ ARRAY.length + 1; if your array doesn't have empty zero slot.
Let the given array be A with length N. Lets assume in the given array, the single empty slot is filled with 0.
We can find the solution for this problem using many methods including algorithm used in Counting sort. But, in terms of efficient time and space usage, we have two algorithms. One uses mainly summation, subtraction and multiplication. Another uses XOR. Mathematically both methods work fine. But programatically, we need to assess all the algorithms with main measures like
Limitations(like input values are large(A[1...N]) and/or number of
input values is large(N))
Number of condition checks involved
Number and type of mathematical operations involved
etc. This is because of the limitations in time and/or hardware(Hardware resource limitation) and/or software(Operating System limitation, Programming language limitation, etc), etc. Lets list and assess the pros and cons of each one of them.
Algorithm 1 :
In algorithm 1, we have 3 implementations.
Calculate the total sum of all the numbers(this includes the unknown missing number) by using the mathematical formula(1+2+3+...+N=(N(N+1))/2). Here, N=100. Calculate the total sum of all the given numbers. Subtract the second result from the first result will give the missing number.
Missing Number = (N(N+1))/2) - (A[1]+A[2]+...+A[100])
Calculate the total sum of all the numbers(this includes the unknown missing number) by using the mathematical formula(1+2+3+...+N=(N(N+1))/2). Here, N=100. From that result, subtract each given number gives the missing number.
Missing Number = (N(N+1))/2)-A[1]-A[2]-...-A[100]
(Note:Even though the second implementation's formula is derived from first, from the mathematical point of view both are same. But from programming point of view both are different because the first formula is more prone to bit overflow than the second one(if the given numbers are large enough). Even though addition is faster than subtraction, the second implementation reduces the chance of bit overflow caused by addition of large values(Its not completely eliminated, because there is still very small chance since (N+1) is there in the formula). But both are equally prone to bit overflow by multiplication. The limitation is both implementations give correct result only if N(N+1)<=MAXIMUM_NUMBER_VALUE. For the first implementation, the additional limitation is it give correct result only if Sum of all given numbers<=MAXIMUM_NUMBER_VALUE.)
Calculate the total sum of all the numbers(this includes the unknown missing number) and subtract each given number in the same loop in parallel. This eliminates the risk of bit overflow by multiplication but prone to bit overflow by addition and subtraction.
//ALGORITHM
missingNumber = 0;
foreach(index from 1 to N)
{
missingNumber = missingNumber + index;
//Since, the empty slot is filled with 0,
//this extra condition which is executed for N times is not required.
//But for the sake of understanding of algorithm purpose lets put it.
if (inputArray[index] != 0)
missingNumber = missingNumber - inputArray[index];
}
In a programming language(like C, C++, Java, etc), if the number of bits representing a integer data type is limited, then all the above implementations are prone to bit overflow because of summation, subtraction and multiplication, resulting in wrong result in case of large input values(A[1...N]) and/or large number of input values(N).
Algorithm 2 :
We can use the property of XOR to get solution for this problem without worrying about the problem of bit overflow. And also XOR is both safer and faster than summation. We know the property of XOR that XOR of two same numbers is equal to 0(A XOR A = 0). If we calculate the XOR of all the numbers from 1 to N(this includes the unknown missing number) and then with that result, XOR all the given numbers, the common numbers get canceled out(since A XOR A=0) and in the end we get the missing number. If we don't have bit overflow problem, we can use both summation and XOR based algorithms to get the solution. But, the algorithm which uses XOR is both safer and faster than the algorithm which uses summation, subtraction and multiplication. And we can avoid the additional worries caused by summation, subtraction and multiplication.
In all the implementations of algorithm 1, we can use XOR instead of addition and subtraction.
Lets assume, XOR(1...N) = XOR of all numbers from 1 to N
Implementation 1 => Missing Number = XOR(1...N) XOR (A[1] XOR A[2] XOR...XOR A[100])
Implementation 2 => Missing Number = XOR(1...N) XOR A[1] XOR A[2] XOR...XOR A[100]
Implementation 3 =>
//ALGORITHM
missingNumber = 0;
foreach(index from 1 to N)
{
missingNumber = missingNumber XOR index;
//Since, the empty slot is filled with 0,
//this extra condition which is executed for N times is not required.
//But for the sake of understanding of algorithm purpose lets put it.
if (inputArray[index] != 0)
missingNumber = missingNumber XOR inputArray[index];
}
All three implementations of algorithm 2 will work fine(from programatical point of view also). One optimization is, similar to
1+2+....+N = (N(N+1))/2
We have,
1 XOR 2 XOR .... XOR N = {N if REMAINDER(N/4)=0, 1 if REMAINDER(N/4)=1, N+1 if REMAINDER(N/4)=2, 0 if REMAINDER(N/4)=3}
We can prove this by mathematical induction. So, instead of calculating the value of XOR(1...N) by XOR all the numbers from 1 to N, we can use this formula to reduce the number of XOR operations.
Also, calculating XOR(1...N) using above formula has two implementations. Implementation wise, calculating
// Thanks to https://a3nm.net/blog/xor.html for this implementation
xor = (n>>1)&1 ^ (((n&1)>0)?1:n)
is faster than calculating
xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;
So, the optimized Java code is,
long n = 100;
long a[] = new long[n];
//XOR of all numbers from 1 to n
// n%4 == 0 ---> n
// n%4 == 1 ---> 1
// n%4 == 2 ---> n + 1
// n%4 == 3 ---> 0
//Slower way of implementing the formula
// long xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;
//Faster way of implementing the formula
// long xor = (n>>1)&1 ^ (((n&1)>0)?1:n);
long xor = (n>>1)&1 ^ (((n&1)>0)?1:n);
for (long i = 0; i < n; i++)
{
xor = xor ^ a[i];
}
//Missing number
System.out.println(xor);
This was an Amazon interview question and was originally answered here: We have numbers from 1 to 52 that are put into a 51 number array, what's the best way to find out which number is missing?
It was answered, as below:
1) Calculate the sum of all numbers stored in the array of size 51.
2) Subtract the sum from (52 * 53)/2 ---- Formula : n * (n + 1) / 2.
It was also blogged here: Software Job - Interview Question
Here is a simple program to find the missing numbers in an integer array
ArrayList<Integer> arr = new ArrayList<Integer>();
int a[] = { 1,3,4,5,6,7,10 };
int j = a[0];
for (int i=0;i<a.length;i++)
{
if (j==a[i])
{
j++;
continue;
}
else
{
arr.add(j);
i--;
j++;
}
}
System.out.println("missing numbers are ");
for(int r : arr)
{
System.out.println(" " + r);
}
Recently I had a similar (not exactly the same) question in a job interview and also I heard from a friend that was asked the exactly same question in an interview.
So here is an answer to the OP question and a few more variations that can be potentially asked.
The answers example are given in Java because, it's stated that:
A Java solution is preferable.
Variation 1:
Array of numbers from 1 to 100 (both inclusive) ... The numbers are randomly added to the array, but there is one random empty slot in the array
public static int findMissing1(int [] arr){
int sum = 0;
for(int n : arr){
sum += n;
}
return (100*(100+1)/2) - sum;
}
Explanation:
This solution (as many other solutions posted here) is based on the formula of Triangular number, which gives us the sum of all natural numbers from 1 to n (in this case n is 100). Now that we know the sum that should be from 1 to 100 - we just need to subtract the actual sum of existing numbers in given array.
Variation 2:
Array of numbers from 1 to n (meaning that the max number is unknown)
public static int findMissing2(int [] arr){
int sum = 0, max = 0;
for(int n : arr){
sum += n;
if(n > max) max = n;
}
return (max*(max+1)/2) - sum;
}
Explanation:
In this solution, since the max number isn't given - we need to find it. After finding the max number - the logic is the same.
Variation 3:
Array of numbers from 1 to n (max number is unknown), there is two random empty slots in the array
public static int [] findMissing3(int [] arr){
int sum = 0, max = 0, misSum;
int [] misNums = {};//empty by default
for(int n : arr){
sum += n;
if(n > max) max = n;
}
misSum = (max*(max+1)/2) - sum;//Sum of two missing numbers
for(int n = Math.min(misSum, max-1); n > 1; n--){
if(!contains(n, arr)){
misNums = new int[]{n, misSum-n};
break;
}
}
return misNums;
}
private static boolean contains(int num, int [] arr){
for(int n : arr){
if(n == num)return true;
}
return false;
}
Explanation:
In this solution, the max number isn't given (as in the previous), but it can also be missing of two numbers and not one. So at first we find the sum of missing numbers - with the same logic as before. Second finding the smaller number between missing sum and the last (possibly) missing number - to reduce unnecessary search. Third since Javas Array (not a Collection) doesn't have methods as indexOf or contains, I added a small reusable method for that logic. Fourth when first missing number is found, the second is the subtract from missing sum.
If only one number is missing, then the second number in array will be zero.
Variation 4:
Array of numbers from 1 to n (max number is unknown), with X missing (amount of missing numbers are unknown)
public static ArrayList<Integer> findMissing4(ArrayList<Integer> arr){
int max = 0;
ArrayList<Integer> misNums = new ArrayList();
int [] neededNums;
for(int n : arr){
if(n > max) max = n;
}
neededNums = new int[max];//zero for any needed num
for(int n : arr){//iterate again
neededNums[n == max ? 0 : n]++;//add one - used as index in second array (convert max to zero)
}
for(int i=neededNums.length-1; i>0; i--){
if(neededNums[i] < 1)misNums.add(i);//if value is zero, than index is a missing number
}
return misNums;
}
Explanation:
In this solution, as in the previous, the max number is unknown and there can be missing more than one number, but in this variation, we don't know how many numbers are potentially missing (if any). The beginning of the logic is the same - find the max number. Then I initialise another array with zeros, in this array index indicates the potentially missing number and zero indicates that the number is missing. So every existing number from original array is used as an index and its value is incremented by one (max converted to zero).
Note
If you want examples in other languages or another interesting variations of this question, you are welcome to check my Github repository for Interview questions & answers.
(sum of 1 to n) - (sum of all values in the array) = missing number
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) idx = i; else sum += arr[i];
}
System.out.println("missing number is: " + (5050 - sum) + " at index " + idx);
On a similar scenario, where the array is already sorted, it does not include duplicates and only one number is missing, it is possible to find this missing number in log(n) time, using binary search.
public static int getMissingInt(int[] intArray, int left, int right) {
if (right == left + 1) return intArray[right] - 1;
int pivot = left + (right - left) / 2;
if (intArray[pivot] == intArray[left] + (intArray[right] - intArray[left]) / 2 - (right - left) % 2)
return getMissingInt(intArray, pivot, right);
else
return getMissingInt(intArray, left, pivot);
}
public static void main(String args[]) {
int[] array = new int[]{3, 4, 5, 6, 7, 8, 10};
int missingInt = getMissingInt(array, 0, array.length-1);
System.out.println(missingInt); //it prints 9
}
Well, use a bloom filter.
int findmissing(int arr[], int n)
{
long bloom=0;
int i;
for(i=0; i<;n; i++)bloom+=1>>arr[i];
for(i=1; i<=n, (bloom<<i & 1); i++);
return i;
}
This is c# but it should be pretty close to what you need:
int sumNumbers = 0;
int emptySlotIndex = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
emptySlotIndex = i;
sumNumbers += arr[i];
}
int missingNumber = 5050 - sumNumbers;
The solution that doesn't involve repetitive additions or maybe the n(n+1)/2 formula doesn't get to you at an interview time for instance.
You have to use an array of 4 ints (32 bits) or 2 ints (64 bits). Initialize the last int with (-1 & ~(1 << 31)) >> 3. (the bits that are above 100 are set to 1) Or you may set the bits above 100 using a for loop.
Go through the array of numbers and set 1 for the bit position corresponding to the number (e.g. 71 would be set on the 3rd int on the 7th bit from left to right)
Go through the array of 4 ints (32 bit version) or 2 ints(64 bit version)
public int MissingNumber(int a[])
{
int bits = sizeof(int) * 8;
int i = 0;
int no = 0;
while(a[i] == -1)//this means a[i]'s bits are all set to 1, the numbers is not inside this 32 numbers section
{
no += bits;
i++;
}
return no + bits - Math.Log(~a[i], 2);//apply NOT (~) operator to a[i] to invert all bits, and get a number with only one bit set (2 at the power of something)
}
Example: (32 bit version) lets say that the missing number is 58. That means that the 26th bit (left to right) of the second integer is set to 0.
The first int is -1 (all bits are set) so, we go ahead for the second one and add to "no" the number 32. The second int is different from -1 (a bit is not set) so, by applying the NOT (~) operator to the number we get 64. The possible numbers are 2 at the power x and we may compute x by using log on base 2; in this case we get log2(64) = 6 => 32 + 32 - 6 = 58.
Hope this helps.
I think the easiest and possibly the most efficient solution would be to loop over all entries and use a bitset to remember which numbers are set, and then test for 0 bit. The entry with the 0 bit is the missing number.
This is not a search problem. The employer is wondering if you have a grasp of a checksum. You might need a binary or for loop or whatever if you were looking for multiple unique integers, but the question stipulates "one random empty slot." In this case we can use the stream sum. The condition: "The numbers are randomly added to the array" is meaningless without more detail. The question does not assume the array must start with the integer 1 and so tolerate with the offset start integer.
int[] test = {2,3,4,5,6,7,8,9,10, 12,13,14 };
/*get the missing integer*/
int max = test[test.length - 1];
int min = test[0];
int sum = Arrays.stream(test).sum();
int actual = (((max*(max+1))/2)-min+1);
//Find:
//the missing value
System.out.println(actual - sum);
//the slot
System.out.println(actual - sum - min);
Success time: 0.18 memory: 320576 signal:0
I found this beautiful solution here:
http://javaconceptoftheday.com/java-puzzle-interview-program-find-missing-number-in-an-array/
public class MissingNumberInArray
{
//Method to calculate sum of 'n' numbers
static int sumOfNnumbers(int n)
{
int sum = (n * (n+1))/ 2;
return sum;
}
//Method to calculate sum of all elements of array
static int sumOfElements(int[] array)
{
int sum = 0;
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
}
return sum;
}
public static void main(String[] args)
{
int n = 8;
int[] a = {1, 4, 5, 3, 7, 8, 6};
//Step 1
int sumOfNnumbers = sumOfNnumbers(n);
//Step 2
int sumOfElements = sumOfElements(a);
//Step 3
int missingNumber = sumOfNnumbers - sumOfElements;
System.out.println("Missing Number is = "+missingNumber);
}
}
function solution($A) {
// code in PHP5.5
$n=count($A);
for($i=1;$i<=$n;$i++) {
if(!in_array($i,$A)) {
return (int)$i;
}
}
}
Finding the missing number from a series of numbers. IMP points to remember.
the array should be sorted..
the Function do not work on multiple missings.
the sequence must be an AP.
public int execute2(int[] array) {
int diff = Math.min(array[1]-array[0], array[2]-array[1]);
int min = 0, max = arr.length-1;
boolean missingNum = true;
while(min<max) {
int mid = (min + max) >>> 1;
int leftDiff = array[mid] - array[min];
if(leftDiff > diff * (mid - min)) {
if(mid-min == 1)
return (array[mid] + array[min])/2;
max = mid;
missingNum = false;
continue;
}
int rightDiff = array[max] - array[mid];
if(rightDiff > diff * (max - mid)) {
if(max-mid == 1)
return (array[max] + array[mid])/2;
min = mid;
missingNum = false;
continue;
}
if(missingNum)
break;
}
return -1;
}
One thing you could do is sort the numbers using quick sort for instance. Then use a for loop to iterate through the sorted array from 1 to 100. In each iteration, you compare the number in the array with your for loop increment, if you find that the index increment is not the same as the array value, you have found your missing number as well as the missing index.
Below is the solution for finding all the missing numbers from a given array:
public class FindMissingNumbers {
/**
* The function prints all the missing numbers from "n" consecutive numbers.
* The number of missing numbers is not given and all the numbers in the
* given array are assumed to be unique.
*
* A similar approach can be used to find all no-unique/ unique numbers from
* the given array
*
* #param n
* total count of numbers in the sequence
* #param numbers
* is an unsorted array of all the numbers from 1 - n with some
* numbers missing.
*
*/
public static void findMissingNumbers(int n, int[] numbers) {
if (n < 1) {
return;
}
byte[] bytes = new byte[n / 8];
int countOfMissingNumbers = n - numbers.length;
if (countOfMissingNumbers == 0) {
return;
}
for (int currentNumber : numbers) {
int byteIndex = (currentNumber - 1) / 8;
int bit = (currentNumber - byteIndex * 8) - 1;
// Update the "bit" in bytes[byteIndex]
int mask = 1 << bit;
bytes[byteIndex] |= mask;
}
for (int index = 0; index < bytes.length - 2; index++) {
if (bytes[index] != -128) {
for (int i = 0; i < 8; i++) {
if ((bytes[index] >> i & 1) == 0) {
System.out.println("Missing number: " + ((index * 8) + i + 1));
}
}
}
}
// Last byte
int loopTill = n % 8 == 0 ? 8 : n % 8;
for (int index = 0; index < loopTill; index++) {
if ((bytes[bytes.length - 1] >> index & 1) == 0) {
System.out.println("Missing number: " + (((bytes.length - 1) * 8) + index + 1));
}
}
}
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<Integer>();
int n = 128;
int m = 5;
for (int i = 1; i <= n; i++) {
arrayList.add(i);
}
Collections.shuffle(arrayList);
for (int i = 1; i <= 5; i++) {
System.out.println("Removing:" + arrayList.remove(i));
}
int[] array = new int[n - m];
for (int i = 0; i < (n - m); i++) {
array[i] = arrayList.get(i);
}
System.out.println("Array is: " + Arrays.toString(array));
findMissingNumbers(n, array);
}
}
Lets say you have n as 8, and our numbers range from 0-8 for this example
we can represent the binary representation of all 9 numbers as follows
0000
0001
0010
0011
0100
0101
0110
0111
1000
in the above sequence there is no missing numbers and in each column the number of zeros and ones match, however as soon as you remove 1 value lets say 3 we get a in balance in the number of 0's and 1's across the columns. If the number of 0's in a column is <= the number of 1's our missing number will have a 0 at this bit position, otherwise if the number of 0's > the number of 1's at this bit position then this bit position will be a 1. We test the bits left to right and at each iteration we throw away half of the array for the testing of the next bit, either the odd array values or the even array values are thrown away at each iteration depending on which bit we are deficient on.
The below solution is in C++
int getMissingNumber(vector<int>* input, int bitPos, const int startRange)
{
vector<int> zeros;
vector<int> ones;
int missingNumber=0;
//base case, assume empty array indicating start value of range is missing
if(input->size() == 0)
return startRange;
//if the bit position being tested is 0 add to the zero's vector
//otherwise to the ones vector
for(unsigned int i = 0; i<input->size(); i++)
{
int value = input->at(i);
if(getBit(value, bitPos) == 0)
zeros.push_back(value);
else
ones.push_back(value);
}
//throw away either the odd or even numbers and test
//the next bit position, build the missing number
//from right to left
if(zeros.size() <= ones.size())
{
//missing number is even
missingNumber = getMissingNumber(&zeros, bitPos+1, startRange);
missingNumber = (missingNumber << 1) | 0;
}
else
{
//missing number is odd
missingNumber = getMissingNumber(&ones, bitPos+1, startRange);
missingNumber = (missingNumber << 1) | 1;
}
return missingNumber;
}
At each iteration we reduce our input space by 2, i.e N, N/2,N/4 ... = O(log N), with space O(N)
//Test cases
[1] when missing number is range start
[2] when missing number is range end
[3] when missing number is odd
[4] when missing number is even
Solution With PHP $n = 100;
$n*($n+1)/2 - array_sum($array) = $missing_number
and array_search($missing_number) will give the index of missing number
Here program take time complexity is O(logn) and space complexity O(logn)
public class helper1 {
public static void main(String[] args) {
int a[] = {1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12};
int k = missing(a, 0, a.length);
System.out.println(k);
}
public static int missing(int[] a, int f, int l) {
int mid = (l + f) / 2;
//if first index reached last then no element found
if (a.length - 1 == f) {
System.out.println("missing not find ");
return 0;
}
//if mid with first found
if (mid == f) {
System.out.println(a[mid] + 1);
return a[mid] + 1;
}
if ((mid + 1) == a[mid])
return missing(a, mid, l);
else
return missing(a, f, mid);
}
}
public class MissingNumber {
public static void main(String[] args) {
int array[] = {1,2,3,4,6};
int x1 = getMissingNumber(array,6);
System.out.println("The Missing number is: "+x1);
}
private static int getMissingNumber(int[] array, int i) {
int acctualnumber =0;
int expectednumber = (i*(i+1)/2);
for (int j : array) {
acctualnumber = acctualnumber+j;
}
System.out.println(acctualnumber);
System.out.println(expectednumber);
return expectednumber-acctualnumber;
}
}
Use sum formula,
class Main {
// Function to ind missing number
static int getMissingNo (int a[], int n) {
int i, total;
total = (n+1)*(n+2)/2;
for ( i = 0; i< n; i++)
total -= a[i];
return total;
}
/* program to test above function */
public static void main(String args[]) {
int a[] = {1,2,4,5,6};
int miss = getMissingNo(a,5);
System.out.println(miss);
}
}
Reference http://www.geeksforgeeks.org/find-the-missing-number/
simple solution with test data :
class A{
public static void main(String[] args){
int[] array = new int[200];
for(int i=0;i<100;i++){
if(i != 51){
array[i] = i;
}
}
for(int i=100;i<200;i++){
array[i] = i;
}
int temp = 0;
for(int i=0;i<200;i++){
temp ^= array[i];
}
System.out.println(temp);
}
}
//Array is shorted and if writing in C/C++ think of XOR implementations in java as follows.
int num=-1;
for (int i=1; i<=100; i++){
num =2*i;
if(arr[num]==0){
System.out.println("index: "+i+" Array position: "+ num);
break;
}
else if(arr[num-1]==0){
System.out.println("index: "+i+ " Array position: "+ (num-1));
break;
}
}// use Rabbit and tortoise race, move the dangling index faster,
//learnt from Alogithimica, Ameerpet, hyderbad**
If the array is randomly filled, then at the best you can do a linear search in O(n) complexity. However, we could have improved the complexity to O(log n) by divide and conquer approach similar to quick sort as pointed by giri given that the numbers were in ascending/descending order.
This Program finds missing numbers
<?php
$arr_num=array("1","2","3","5","6");
$n=count($arr_num);
for($i=1;$i<=$n;$i++)
{
if(!in_array($i,$arr_num))
{
array_push($arr_num,$i);print_r($arr_num);exit;
}
}
?>
Now I'm now too sharp with the Big O notations but couldn't you also do something like (in Java)
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] != i+1){
System.out.println(i+1);
}
}
where numbers is the array with your numbers from 1-100.
From my reading of the question it did not say when to write out the missing number.
Alternatively if you COULD throw the value of i+1 into another array and print that out after the iteration.
Of course it might not abide by the time and space rules. As I said. I have to strongly brush up on Big O.
========Simplest Solution for sorted Array===========
public int getMissingNumber(int[] sortedArray)
{
int missingNumber = 0;
int missingNumberIndex=0;
for (int i = 0; i < sortedArray.length; i++)
{
if (sortedArray[i] == 0)
{
missingNumber = (sortedArray[i + 1]) - 1;
missingNumberIndex=i;
System.out.println("missingNumberIndex: "+missingNumberIndex);
break;
}
}
return missingNumber;
}
Another homework question. A sequential search is the best that you can do. As for a Java solution, consider that an exercise for the reader. :P