Leetcode 406: Queue Reconstruction by Height

grid47
grid47
Exploring patterns and algorithms
Sep 27, 2024 5 min read

A series of people with heights, arranging themselves in a queue with each step glowing as they are positioned.
Solution to LeetCode 406: Queue Reconstruction by Height Problem

You are given an array of people, where each person is represented by two integers: their height hi and the number of people ki in front of them who have a height greater than or equal to hi. Your task is to reconstruct the queue based on these attributes.
Problem
Approach
Steps
Complexity
Input: You are given an array people where each element represents a person with their height and the number of people taller or of equal height in front of them.
Example: For people = [[6, 0], [5, 0], [4, 3], [3, 2], [2, 2], [1, 4]], the reconstructed queue is [[4, 3], [5, 0], [6, 0], [3, 2], [2, 2], [1, 4]].
Constraints:
• 1 <= people.length <= 2000
• 0 <= hi <= 10^6
• 0 <= ki < people.length
• It is guaranteed that the queue can be reconstructed.
Output: Return the reconstructed queue where each element represents a person with their height and the number of people taller or of equal height in front of them.
Example: For people = [[7, 0], [4, 2], [7, 1], [6, 0], [5, 1], [5, 2]], the reconstructed queue is [[7, 0], [5, 1], [6, 0], [5, 2], [7, 1], [4, 2]].
Constraints:
Goal: Reconstruct the queue by sorting the people by height in descending order and inserting each person based on their ki value.
Steps:
• 1. Sort the people in descending order based on their height. If two people have the same height, sort by their ki value in ascending order.
• 2. For each person, insert them at the index specified by their ki value in the current reconstructed queue.
• 3. Return the reconstructed queue.
Goal: The input satisfies the following constraints:
Steps:
• 1 <= people.length <= 2000
• 0 <= hi <= 10^6
• 0 <= ki < people.length
• It is guaranteed that the queue can be reconstructed.
Assumptions:
• The input list contains valid people data and can always be reconstructed into a valid queue.
Input: For people = [[6, 0], [5, 0], [4, 3], [3, 2], [2, 2], [1, 4]], the reconstructed queue is [[4, 3], [5, 0], [6, 0], [3, 2], [2, 2], [1, 4]].
Explanation: Sort the people by height in descending order and insert them into the queue based on their ki values.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus