Katkat

Build the Largest Available Sequence

AmazonSoftware Engineer · Online Assessment

Last updated

This problem tests your ability to use a greedy approach combined with a frequency map to construct the lexicographically largest sequence under specific constraints.

Problem Statement

You are given an array of integers nums and an integer k. You need to construct a sequence of length k by repeatedly picking the largest available integer from nums.

However, there is a constraint: you cannot pick the same integer more than limit times consecutively. Specifically, if you have already picked the same integer limit times in a row, the next element in your sequence must be a different integer from the remaining available numbers. If no other integers are available to break the sequence, the construction stops.

Write a function constructLargestSequence(nums, k, limit) that returns the lexicographically largest sequence of length k. If it is impossible to construct a sequence of length k, return an empty list.

Function Signature

def constructLargestSequence(nums: List[int], k: int, limit: int) -> List[int]:

Examples

Example 1: Input: nums = [4, 4, 3, 3, 3], k = 4, limit = 2 Output: [4, 4, 3, 3] Explanation: We pick two 4s, then we are forced to pick a 3. We pick two 3s, and we have reached length 4.

Example 2: Input: nums = [5, 5, 5, 2], k = 3, limit = 1 Output: [5, 2, 5] Explanation: We pick 5, then are forced to pick 2, then we can pick 5 again.

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • 1 <= limit <= len(nums)
  • nums elements are between 1 and 10^6.

Hints

Hint 1

Use a frequency map or a max-priority queue to keep track of available numbers and their counts.

Hint 2

Always attempt to pick the largest available number first, unless you have already hit the consecutive limit for that number.

Hint 3

If you cannot pick the largest number due to the limit constraint, pick the next largest available number, then add the first number back to the pool for the next step.

Follow-up questions

  • How would your approach change if the limit constraint applied to the total number of times an integer appears in the sequence, rather than just consecutively?
  • What is the time complexity of your solution using a max-heap, and can it be optimized if the range of values in `nums` is small?
  • How would you modify the algorithm to return the lexicographically smallest sequence instead?