KatInterview

Maximum Vacation Length and Efficient Distinct Value Counting

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingsliding-windowbinary-searchtwo-pointer

Last updated

Tests sliding window technique for contiguous subarrays with constraints and binary search optimization for counting distinct values in sorted arrays.

Write a function that solves two independent subproblems and returns both answers as a list [answer_a, answer_b].

Problem A: Maximum Vacation Length

You have a calendar represented as an array where each element is either 'w' (workday) or 'h' (holiday). You can use up to budget paid time-off days to turn workdays into days off.

Find the maximum number of consecutive days off you can create.

When you use PTO on a workday, it becomes a day off for the purpose of building a consecutive streak. Holidays are already days off and don't require PTO.

Problem B: Counting Distinct Values Efficiently

You are given a sorted array (non-decreasing order) that contains many duplicate values. The number of distinct values is much smaller than the array length.

Count how many distinct values exist in the array using an approach faster than visiting every element when duplicates are common.

Parameters

  • calendar: List of strings, each either 'w' or 'h'
  • budget: Non-negative integer, the number of PTO days available
  • sorted_arr: List of integers in non-decreasing order

Return Value

Return [max_vacation_days, distinct_count] where:

  • max_vacation_days: Maximum length of consecutive days off achievable
  • distinct_count: Number of distinct values in sorted_arr

Constraints

  • 0 ≤ len(calendar) ≤ 100,000
  • 0 ≤ budget ≤ len(calendar)
  • 0 ≤ len(sorted_arr) ≤ 1,000,000
  • sorted_arr is sorted in non-decreasing order
  • -10^9 ≤ sorted_arr[i] ≤ 10^9
  • If calendar is empty, the maximum vacation length is 0
  • If sorted_arr is empty, the distinct count is 0

Examples

Example 1

Input: vacation_and_distinct_count(['w', 'h', 'h', 'w', 'h', 'w'], 2, [1, 1, 1, 2, 2, 5, 5, 5, 9])

Output: [5, 4]

Example 2

Input: vacation_and_distinct_count(['w', 'w', 'h', 'w'], 1, [-3, -3, -3, -1, 0, 0, 4])

Output: [2, 4]

Example 3

Input: vacation_and_distinct_count(['h', 'h', 'h'], 0, [-2, -2, 7, 7])

Output: [3, 2]

Example 4

Input: vacation_and_distinct_count([], 3, [])

Output: [0, 0]

Hints

Hint 1

For Problem A: Think about maintaining a window where you track how many workdays are inside it. What happens when the window has too many workdays?

Hint 2

For Problem B: In a sorted array, all occurrences of the same value form one continuous segment. Can you jump to the end of each segment without examining every element?

Hint 3

For Problem A: A two-pointer sliding window approach can solve this in one pass through the calendar array.