Problem 562611 · hard · Phase 05 Advanced Algorithms & Graphs

Rebuild the Photo Line

greedy · sorting · list insertion

A class photo line got shuffled. For each student you know [h, k]: their height h and the number k of students standing in front of them whose height is at least h. Given the shuffled list people, return the original line (front first) as a list of [h, k] pairs. The input always describes a valid line.

Examples

Input:  people = [[2, 3], [6, 0], [4, 2], [5, 0], [3, 1]]
Output: [[5, 0], [3, 1], [6, 0], [2, 3], [4, 2]]
Explanation: In front of the 4 stand 5, 3, 6, 2; exactly two of them (5 and 6) are at least 4.

Constraints

  • 0 <= len(people) <= 2000, 1 <= h <= 10**6.
  • Heights may repeat.
  • Target complexity: O(n^2) with list insertion is fine.

Goals

  • Place tall people first so shorter ones never disturb their counts
  • Use the count as an insertion index
  • Sort ties so equal heights end up in the right order
Starting Python…