← Questions

Rank the values of an array of distinct integers

0
GleanCoding

You get an array of distinct integers. Replace each value with its rank: the smallest value gets 1, the next smallest 2, and so on. It is the one-row case of ranking a matrix, where only cells that share a row or a column constrain each other.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • array_ranks(nums: list[int]) -> list[int] — the rank of each element, in the original order.

Example

array_ranks([40, 10, 30, 20])  ->  [4, 1, 3, 2]
array_ranks([-5, 100, 7])      ->  [1, 3, 2]
array_ranks([8])               ->  [1]

Constraints

  • 1 <= len(nums) <= 10^5.
  • -10^9 <= nums[i] <= 10^9, all distinct.

Clarifying questions

  • Are the values guaranteed distinct? If not, do equal values share a rank?
  • Rank from smallest or from largest?
  • Return a new array, or overwrite the input?

What a strong answer covers

  • Sort a copy, build a hash map from value to its position plus one, then map the original array: O(n log n) time, O(n) space.
  • Why hashing matters: the lookup back into original order is O(1) per element because the values are distinct.
  • When the value range is small, counting sort gives O(n + range).
  • Tests: one element, negatives, already sorted and reversed input.

Follow-ups

  • Equal values must share a rank, with no gaps (dense ranking).
  • The 2D version: a matrix of distinct values where a larger value in the same row or column must get a strictly larger rank, with ranks as small as possible.
  • Values stream in: report the rank of each new value among those seen so far.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding