PPractick

DSA interview question

Replace Elements by Their Rank

Easy · Data structures · Topics: heap, sorting, hash map

The problem

A contest dashboard wants to show each score's rank instead of the raw number: the smallest score gets rank 1, the next distinct score rank 2, and so on, with equal scores sharing a rank. Process the values in increasing order with a min-heap of (value, index) pairs. Each time the popped value differs from the previous one, the rank goes up by one, and the rank is written back to that element's original index.

Example: [20, 15, 26, 2, 98, 6] → [4, 3, 5, 1, 6, 2].

Function signature

vector<int> replaceWithRank(const vector<int>& arr);

Test cases

InputOutputExplanation
[20, 15, 26, 2, 98, 6][4, 3, 5, 1, 6, 2]Sorted: 2, 6, 15, 20, 26, 98
[2, 2, 1, 6][2, 2, 1, 3]Equal values share a rank
[-5, 10, -5, 0][1, 3, 1, 2]
[1, 1, 1][1, 1, 1]
[5][1]

(Confirm: ranks are dense (no gaps after ties) and start at 1.)

How interviewers phrase it

Clarifying questions to ask

  1. Dense ranks (1, 1, 2) or competition ranks (1, 1, 3)? (Dense.)
  2. Do equal values share a rank? (Yes.)
  3. Can values be negative? (Yes.)

Follow-ups to expect

  1. "Why use a heap?"
  2. "Sorting alternative?"
  3. "How do ties work?"
  4. "What's this used for?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in