Skip to content

Commit 274d2d4

Browse files
committed
Solved problem 268 : Missing Number
1 parent 52a63ef commit 274d2d4

File tree

2 files changed

+65
-3
lines changed

2 files changed

+65
-3
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* Problem: 268
3+
* Name: Missing Number
4+
* Difficulty: Easy
5+
* Topic: Bit Manipulation
6+
* Link: https://leetcode.com/problems/
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
using namespace std;
11+
12+
// Binary Search
13+
/* When the n numbers are ordered, if the number at index i is equal to i,
14+
* then all number before it are in the correct positions, so the lowerBound
15+
* can be incremented; otherwise, there is a number missing before i, and the
16+
* upperBound should be decremented
17+
* Eventually they will converge to the index/value missing and return it
18+
*/
19+
// Time Complexity: O(n log n)
20+
// Space Complexity: O(1)
21+
int missingNumberSort(vector<int>& nums) {
22+
sort(nums.begin(), nums.end());
23+
int lowerBound = 0;
24+
int upperBound = nums.size();
25+
while (lowerBound < upperBound){
26+
int midValue = lowerBound + (upperBound - lowerBound) / 2;
27+
if (nums[midValue] > midValue){
28+
upperBound = midValue;
29+
}
30+
else {
31+
lowerBound = midValue + 1;
32+
}
33+
}
34+
return lowerBound;
35+
}
36+
37+
// Sum of the sequence
38+
/* Using the gaussian formula for the sum of the first n values of a sequence
39+
* we can obtain the total sum of the sequence and iterate through the loop
40+
* subtracting the numbers that are there, the result will be the missing number
41+
*/
42+
// Time Complexity: O(n)
43+
// Space Complexity: O(1)
44+
int missingNumberMath(vector<int>& nums) {
45+
int result = ((nums.size()+1) * (0 + nums.size())) / 2;
46+
for (const int &n : nums){
47+
result -= n;
48+
}
49+
return result;
50+
}
51+
52+
// Bit Manipulation (XOR)
53+
// Time Complexity: O(n)
54+
// Space Complexity: O(1)
55+
int missingNumber(vector<int>& nums) {
56+
int result = nums.size();
57+
for (int idx = 0; idx < nums.size(); idx++){
58+
result ^= idx;
59+
result ^= nums[idx];
60+
}
61+
return result;
62+
}

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
### Problems Solved
1818

19-
| Total | 35 |
19+
| Total | 36 |
2020
|:---:|:---:|
2121

2222
#### Search By Topic
@@ -27,7 +27,7 @@
2727
| Backtracking | 0 |
2828
| Binary Search | 2 |
2929
| Binary Trees | 7 |
30-
| Bit Manipulation | 4 |
30+
| Bit Manipulation | 5 |
3131
| Dynamic Programming 1D | 1 |
3232
| Dynamic Programming 2D | 0 |
3333
| Graphs | 1 |
@@ -46,7 +46,7 @@
4646

4747
| Difficulty | Number |
4848
|:---|---:|
49-
| Easy | 34 |
49+
| Easy | 35 |
5050
| Medium | 1 |
5151
| Hard | 0 |
5252

0 commit comments

Comments
 (0)