Smallest Unassigned Positive Shard ID in Constant Extra Space
Last updated: November 29, 2026
Quick Overview
Given an unsorted array of shard IDs (integers, possibly negative, zero or duplicated), return the smallest positive integer that is not present, in O(n) time and O(1) extra space.
Meta
November 29, 20260
0
0 solved
Given an unsorted array of shard IDs (integers, possibly negative, zero or duplicated), return the smallest positive integer that is not present, in O(n) time and O(1) extra space.
A Meta onsite Hard that looks like a hashing problem but forbids the hash set. The interviewer wants the observation that the answer lies in 1..n+1 and that the array itself can serve as the hash table.
What the Interviewer Expects
- Argues the answer is always in the range 1 to n + 1
- Uses cyclic placement to put value v at index v - 1
- Guards against infinite loops on duplicates
- Makes a final scan for the first index whose value is wrong
- Gives O(n) time with a clear amortized argument
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
- Solve it without mutating the input. What is the best you can do?
- Find the k smallest missing positive IDs.
- IDs are spread across many servers; how do you find the global answer?
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: ids, a list of n integers. Output: the smallest integer >= 1 not in the list. Modifying the input is allowed. Must run in O(n) time and O(1) extra space....
High-Level Design
With n slots, at most n distinct positives can be present, so the answer is at most n + 1. Treat index v - 1 as the home of value v. Walk the array; while the current value is in range 1..n and it...