KatInterview

Rank Selection Plus Longest Leave-Assisted Break

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsliding-windowtwo-pointers

Last updated

Combines selecting the element at a 0-indexed rank in descending order with a sliding window finding the longest stretch containing at most a given number of workdays.

Write one function that answers two unrelated questions and returns both answers in a list.

Part A: Value at a given rank

You get a list of integers values and a 0-indexed rank rank. Imagine the list sorted from largest to smallest. Report the element at position rank in that ordering.

  • rank = 0 is the largest value.
  • rank = 1 is the second largest value, and so on.
  • Duplicates count separately. Each copy occupies its own position in the sorted order, so this is not about distinct values.

Part B: Longest break using leave days

You get a list days describing a year. Each entry is one of two strings:

  • "H": a holiday, already free.
  • "W": a workday.

You also get leave, the number of workdays you may convert into days off by taking leave. A day counts as part of a break if it is a holiday, or if it is a workday you chose to cover with leave. You may cover at most leave workdays.

Find the largest possible length of a run of consecutive days in which every day is off. If days is empty, the answer is 0.

Output

Return a list of two integers: [value_at_rank, longest_break].

Constraints

  • 0 <= rank < len(values) (so values is non-empty).
  • values contains integers, possibly negative or repeated.
  • days contains only the strings "H" and "W"; it may be empty.
  • leave >= 0.
  • The two parts use independent inputs and do not influence each other.

Examples

Example 1

Input: rank_and_longest_break([5, -3, 9, 1], 0, ['W', 'H', 'H', 'W', 'W', 'H', 'W'], 2)

Output: [9, 5]

Example 2

Input: rank_and_longest_break([5, -3, 9, 1], 1, ['W', 'H', 'H', 'W', 'W', 'H', 'W'], 2)

Output: [5, 5]

Example 3

Input: rank_and_longest_break([5, -3, 9, 1], 3, ['W', 'H', 'H', 'W', 'W', 'H', 'W'], 2)

Output: [-3, 5]

Hints

Hint 1

For Part A, a min-heap that keeps only the rank + 1 largest values seen so far has the answer at its root. Watch the off-by-one from 0-indexing.

Hint 2

For Part B, reframe the question: what is the longest contiguous segment that contains at most `leave` workdays?

Hint 3

Use two pointers. Expand the right end, count workdays in the window, and move the left end forward while the count exceeds `leave`; record the window length after each step.