HARD Arrays & Hashing (with constraints)

41. First Missing Positive

๐Ÿ“– Problem

Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ First missing positive is in range [1, n+1] where n is array length
  • โ†’ Use the array itself as a hash map by marking positions
  • โ†’ Place each number in its correct position (number 1 at index 0, etc.)
  • โ†’ Time: O(n), Space: O(1)
  • โ†’ Using hash set: O(n) time, O(n) space
  • โ†’ Sorting: O(n log n) time, O(1) space

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขFirst missing positive is in range [1, n+1] where n is array length
  • โ€ขUse the array itself as a hash map by marking positions
  • โ€ขPlace each number in its correct position (number 1 at index 0, etc.)

Common Pitfalls

  • โ€ขTime: O(n), Space: O(1)
  • โ€ขUsing hash set: O(n) time, O(n) space
  • โ€ขSorting: O(n log n) time, O(1) space

๐Ÿงช Test Cases

Hidden tests on submit: 5

Test Case 1
Not run
Input:
firstMissingPositive(nums: number[]);
Expected:
Computed from hidden reference
Test Case 2
Not run
Input:
firstMissingPositive([...test1]);
Expected:
Computed from hidden reference
Test Case 3
Not run
Input:
firstMissingPositive([...test2]);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit