Smallest Unused Positive Port Number in an Unsorted Allocation List
Last updated: November 29, 2026
Quick Overview
Given an unsorted list of integers representing currently allocated port numbers (which may include duplicates, zeros and negatives from bad data), return the smallest positive integer not in the list, in O(n) time and O(1) extra space.
0
0
0 solved
Given an unsorted list of integers representing currently allocated port numbers (which may include duplicates, zeros and negatives from bad data), return the smallest positive integer not in the list, in O(n) time and O(1) extra space.
A Google onsite question themed on allocating the next free port or worker ID in a Borg-like scheduler. A hash set is the easy answer; the interviewer then forbids extra memory and looks for the in-place cyclic placement (or sign marking) trick, with a solid argument that the answer lies in [1, n+1].
What the Interviewer Expects
- Argues the answer is always in 1..n+1
- Gives the hash set solution first
- Places each value v at index v-1 using in-place swaps
- Avoids infinite loops on duplicates
- Proves the swap loop is O(n) total
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Do it without modifying the input array; what is the best you can do?
- Return the k smallest missing positive numbers.
- How would you support allocate and free operations repeatedly in O(log n)?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: list
portsof integers, length n, arbitrary values. - Output: the smallest positive integer not present.
- Constraints: O(n) time, O(1) extra space; modifying the input is allowed....
High-Level Design
With n numbers, at most n of the values 1..n can be present, so the answer is in 1..n+1. That lets us use the array itself as a hash table indexed by value: value v belongs at index v-1. Walk the arra...