Missing element

Pages: 12
Clever with XOR but the second ^= should probably be ^ to avoid modifying the vector elements. This mistake would not have happened if the parameter was marked const.
Last edited on
Fair enough. I was mistaken about the order/associativity of operations in the original.

Try again:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int solution( const vector<int> &A )
{
   int result = A.size() + 1;
   for ( int i = 0; i < A.size(); i++ ) result ^= ( A[i] ^ ( i + 1 ) );
   return result;
}

int main()
{
   const int N = 100000;
   vector<int> V( N );   iota( V.begin(), V.end(), 1 );   V[4242-1] = N + 1;
   cout << solution( V ) << '\n';
}
Last edited on
Array or vector doesn't matter. By calculating the difference on each iteration the answer won't exceed the limit by the look of it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int array[]{1,6,4,3,5,2};
    int sz = sizeof(array)/sizeof(int);
    
    int missing_number{0};
    
    for (size_t i = 0; i < sz; i++)
    {
        missing_number += i + 1 - array[i];
    }
    missing_number += (sz+1);
    
    std::cout << "Missing number: " << missing_number << '\n';
    return 0;
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12