Fewest Increments So Every Assigned Port Number Is Unique

Last updated: November 29, 2026

Quick Overview

Services on a host requested port numbers, possibly with collisions. Each increment raises one requested port by 1; return the minimum total increments so that all ports become distinct.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Services on a host requested port numbers, possibly with collisions. Each increment raises one requested port by 1; return the minimum total increments so that all ports become distinct.

A Google screen favorite dressed as port allocation. The interviewer checks that you sort and assign each port the smallest free value at or above its request, and asks how to do it in linear time with a counting array.

What the Interviewer Expects
  • Sort the requested ports
  • Assign each the max of its request and previous assigned plus one
  • Sum the increments
  • Explain why smallest-free assignment is optimal
  • Mention a counting approach for bounded values
Key Topics to Cover
Greedy
Sorting
Counting
Arrays
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Ports may also be decremented, at the same cost.
  • Ports must stay below 65536; report failure if impossible.
  • Return the final assignment in original order.
  • Values up to 10^9 with n up to 10^5: avoid the counting array.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: list of ints. Allowed move: increase any element by 1. Output: minimum number of moves so all elements are distinct....

High-Level Design

Sort ascending. Walk through keeping next_free, the smallest value not yet assigned that is at least as large as all earlier assignments. Each port gets max(request, next_free), and the cost is th...


Submit Your Answer
Markdown supported