Skip to the code
+50 XP

#74 Smallest Unused Port

hard

A local dev tool needs a free port number for a new server. The numbers already in use are in ports, which may also hold junk values (zero, negative, repeated, or huge).

Write smallestUnusedPort(ports) that returns the smallest positive whole number not in ports. Do it in O(n) time with O(1) extra memory; you may reorder ports.

Example 1

Input: ports = [2,5,1,-4,3]
Output: 4

1, 2, and 3 are taken, so 4 is the smallest free number.

Example 2

Input: ports = [9,8,10]
Output: 1

1 is not used.

Constraints

  • 0 <= ports.length <= 5 * 10^5
  • -2^31 <= ports[i] <= 2^31 - 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).