Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to find the missing number in a vector containing numbers from 1 to n in O(1) time complexity with C++

1 Answer

0 votes
#include <iostream>
#include <vector>

/*
The essence of O(1) complexity is that the algorithm performs a fixed number of operations, 
no matter how large or small the input is. This characteristic ensures that the performance 
remains consistent and does not degrade with increasing input size.
*/

int findMissingNumber(const std::vector<int>& vec) {
    int size = vec.size(); 
    // the formula for the sum of the first n natural numbers 
    long expected_sum = (long)(size + 1) * (size + 2) / 2; 
    long actual_sum = 0;//N(n + 1)/2

    for (int num : vec) actual_sum += num; 

    return (int)(expected_sum - actual_sum);

}

int main() {
    std::vector<int> vec = {1, 2, 4, 5, 6}; 
    
    std::cout << "Missing number: " << findMissingNumber(vec) << std::endl;
}



/*
run:

Missing number: 3

*/

 



answered Dec 9, 2025 by avibootz

Related questions

...