File: largest-subarray-length-k/solution.py

Date: 2026-06-06

Time: 17:17

largest-subarray-length-k/solution.py

Purpose

This file solves LeetCode problem 1708: Largest Subarray Length K. Given an array of distinct integers and a length k, it returns the lexicographically largest contiguous subarray of exactly length k. It's a premium/easy-tier problem that tests understanding of lexicographic ordering and the insight that — with distinct elements — only the first element of the subarray matters for comparison.

Key Components

Solution.largestSubarray(nums, k) — The single method. Takes a list of distinct integers and an integer k, returns a List[int].

Contract: nums has at least k elements; all elements are distinct.

Patterns

Greedy scan for maximum starting element. The key insight: because all elements are distinct, comparing two subarrays of length k lexicographically is determined entirely by the first element that differs — and since subarrays are contiguous slices of the same array, that first element is the starting element itself. Two subarrays starting at different positions can't share the same first element (distinctness guarantee), so the lexicographically largest subarray is the one that starts with the largest value among all valid starting positions [0, n-k].

The loop on line 13 scans positions 1 through n - k (inclusive), tracking maxidx. Line 15 returns the slice nums[maxidx:max_idx + k].

This is O(n) time, O(k) space (for the returned slice) — optimal for this problem.

Dependencies

Imports: List from typing — standard type hint, no runtime dependency.

Imported by: largest-subarray-length-k/test_solution.py directly. The "Imported By" list in the prompt is an artifact of the repo structure — those test files import their own local Solution class, not this one.

Flow

1. Compute n = len(nums).

2. Initialize max_idx = 0 — the first valid starting position.

3. Iterate i from 1 to n - k (inclusive). If nums[i] > nums[maxidx], update maxidx = i.

4. Return the slice nums[maxidx:maxidx + k].

The loop range range(1, n - k + 1) ensures we only consider starting indices where a full window of length k fits. When k == n, the range is empty and the method correctly returns the entire array.

Invariants

Error Handling

None. The method assumes valid inputs per LeetCode constraints (1 <= k <= len(nums) <= 10^5, all elements distinct). No bounds checking, no empty-array guard. This is standard for LeetCode solution files in this repo.

Topics to Explore

Beliefs