-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday4_find_missing_integer.cpp
More file actions
65 lines (53 loc) · 1.98 KB
/
day4_find_missing_integer.cpp
File metadata and controls
65 lines (53 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Good morning! Here's your coding interview problem for today.
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
*/
#include <gtest/gtest.h>
using namespace std;
int find_missing_positive_integer(vector<int> &array)
{
/*
Idea: The size of the array is greater or equal than the first missing positive number
We can place element of the array to an index corresponding to it's position (ex: 1 -> index 0, 2 -> index 3)
And iterate over the array to find with index is missing
Space complexity: constant except for the input array
Time complexity: place_element can be at worse n but only once because it will place all element.
So complexity is O(n)
*/
const size_t len{array.size()};
for (auto &e : array)
{
while (1 <= e && e <= len)
{
const size_t index{static_cast<size_t>(e) - 1};
if (array[index] == e)
break;
swap(array[index], e);
}
}
for (size_t i = 1; i < len; i++)
{
if (array[i - 1] != i)
return i;
}
return len;
}
TEST(FIND_MISSING_POSITIVE_INTEGER, find_missing_positive_integer)
{
vector<int> array1{3, 4, -1, 1};
vector<int> array2{1, 2, 0};
vector<int> array3{0, 0, 0, 0, 0};
vector<int> array4{5};
EXPECT_EQ(find_missing_positive_integer(array1), 2);
EXPECT_EQ(find_missing_positive_integer(array2), 3);
EXPECT_EQ(find_missing_positive_integer(array3), 1);
EXPECT_EQ(find_missing_positive_integer(array4), 1);
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}