KatInterview

Repeated Values and Longest Two-Distinct Subarray

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingsliding-windowhashingtwo-pointers

Last updated

Tests hash-based duplicate detection alongside a sliding window that finds the longest subarray containing exactly two distinct integer values.

You are given an integer array nums. Your function must compute two independent properties and return them as a two-element list [result1, result2].

Property 1 — Any Repeated Value

Return True if at least one integer value appears more than once anywhere in nums. Return False if every element is distinct (no value repeats).

Property 2 — Longest Subarray with Exactly Two Distinct Values

Find the length of the longest contiguous subarray that contains exactly two distinct integer values.

Rules and tie-breaks:

  • A subarray is a contiguous slice nums[i..j] for some 0 <= i <= j < len(nums).
  • "Exactly two distinct values" means the set of values in the subarray has cardinality 2. A subarray whose elements are all the same (cardinality 1) does not qualify, regardless of its length.
  • If multiple subarrays tie for the longest, return that shared length (no need to identify which one).
  • If no subarray with exactly two distinct values exists (e.g., the array has fewer than two distinct values total), return 0.

Return Format

Return a Python list of two elements:

[result1, result2]
  • result1 is a bool (True or False).
  • result2 is an int.

Note: in Python True == 1 and False == 0, so the return type is compatible with List[int].

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The two properties are independent: Property 1 does not affect Property 2 and vice versa.
  • You may assume the input is a list of integers (no other types).

Examples

Example 1

Input: analyze_array([1, 2, 3, 1])

Output: [True, 2]

Example 2

Input: analyze_array([1, 2, 1, 3, 3, 3])

Output: [True, 4]

Example 3

Input: analyze_array([1, 2, 1, 2])

Output: [True, 4]

Hints

Hint 1

For Property 1, compare the length of the array with the size of its set — if the set is smaller, a duplicate exists.

Hint 2

For Property 2, maintain a sliding window with left and right pointers. Store the last index at which each distinct value in the window was seen. When a third distinct value enters, evict the one whose last occurrence is earliest and move left just past that index.

Hint 3

Only update the answer when the window contains exactly two distinct values; windows with one distinct value are not counted.