neetcode-gh / leetcode

Leetcode solutions
MIT License
5.52k stars 2.27k forks source link

Wrong complexity in longest consecutive sequence (C++) #3145

Closed samuel-c-allan closed 10 months ago

samuel-c-allan commented 10 months ago

Quite possibly I misunderstand complexity but it seems the complexity for the C++ "longest consecutive sequence" is wrong. I am referencing the following code: https://github.com/neetcode-gh/leetcode/blob/c6ac275aef98787ff204f688ebd07a8cbb7f20db/cpp/0128-longest-consecutive-sequence.cpp#L14-L28

It seems the worst-case time complexity is actually O(n^2). To see this assume that the input is an array sorted in strictly decreasing order (e.g. 13 12 11 10 ... 1). It goes through the loop on line 17 n times and inside the loop, the loop on line 19 is executed 0 times, then once, then twice, e.t.c. this leads to an O(n^2) complexity.

samuel-c-allan commented 10 months ago

Nevermind I misunderstood