Is the below function O(n) time and O(1) space, where n = |A|?
<pre><code>def firstMissingPositive(self, A):
    least = 1024*1024*1024
    # worst case n ops
    for i in A:
        if i &lt; least and i &gt; 0:
            least = i
    if least &gt; 1:
        return 1
    else:
        # should be O(n)
        A_set = set(A)
        # worst case n ops again
        while True:
            least += 1
            if least not in A_set:
                return least
</code></pre>

<p>I only ask because it seemed too simple for the given problem, which most people here may have seen on Leetcode or someplace similar. Is there something I'm not aware of in Python's implementation of set or dict? Lookup should be O(1) and converting a list to a set should be O(n) from what I understand.</p>

<p>It's not <code>O(1)</code> space, it's <code>O(n)</code> space, since you need to build the set. </p>

<p>As for the time, according to <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">the Python wiki</a>, set containment takes <code>O(n)</code> worst case. So your algorithm is thus <code>O(n^2)</code>. Note this is worst case - the average time for set containment is <code>O(1)</code> and so the average time complexity for your algorithm is indeed <code>O(n)</code>.</p>

<p>You can get the worst-case down to <code>O(n log n)</code> by using an ordered set, but then the average-time will be <code>O(n log n)</code> as well.</p>

python algorithm time-complexity