Largest Subarray Length K - Problem

An array A is larger than some array B if for the first index i where A[i] != B[i], we have A[i] > B[i].

For example, consider 0-indexing: [1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2. Similarly, [1,4,4,4] < [2,1,1,1], since at index 0, 1 < 2.

A subarray is a contiguous subsequence of the array. Given an integer array nums of distinct integers, return the largest subarray of nums of length k.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,3,2,5], k = 3
Output: [4,3,2]
💡 Note: Possible subarrays: [1,4,3], [4,3,2], [3,2,5]. Compare lexicographically: [4,3,2] > [1,4,3] (4 > 1) and [4,3,2] > [3,2,5] (4 > 3)
Example 2 — Larger Array
$ Input: nums = [1,2,3,4], k = 2
Output: [3,4]
💡 Note: Possible subarrays: [1,2], [2,3], [3,4]. Compare: [3,4] > [2,3] (3 > 2) and [3,4] > [1,2] (3 > 1)
Example 3 — Single Element
$ Input: nums = [1,4,3,2,5], k = 1
Output: [5]
💡 Note: All subarrays of length 1: [1], [4], [3], [2], [5]. The largest is [5] since 5 is the maximum element

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ nums.length
  • 1 ≤ nums[i] ≤ 109
  • All integers in nums are distinct

Visualization

Tap to expand
Largest Subarray Length K INPUT nums = [1, 4, 3, 2, 5], k = 3 1 i=0 4 i=1 3 i=2 2 i=3 5 i=4 Possible Subarrays (k=3): [1, 4, 3] starts at i=0 [4, 3, 2] starts at i=1 [3, 2, 5] starts at i=2 Find subarray with largest first element for k elements ALGORITHM STEPS 1 Find Search Range Max start index: n-k = 5-3 = 2 2 Find Max First Element Search indices 0 to 2 for max 1 < 4 > 3 3 Record Best Index maxIdx = 1 (value 4 is max) 4 Extract Subarray Return nums[1:1+3] // Greedy: find max start maxIdx = 0; for(i=0; i<=n-k; i++) if(nums[i]>nums[maxIdx]) maxIdx = i; return nums[maxIdx:maxIdx+k] FINAL RESULT Largest Subarray Found: 4 3 2 Output: [4, 3, 2] Why [4,3,2] is largest? Compare at first index: [4,3,2] vs [1,4,3]: 4 > 1 [4,3,2] vs [3,2,5]: 4 > 3 [4,3,2] is lexicographically largest OK - Verified Key Insight: The greedy approach works because we only need to find the maximum element among valid starting positions. Since all elements are distinct, the subarray starting with the maximum first element will always be the largest. Time Complexity: O(n-k) | Space Complexity: O(k) for the result array TutorialsPoint - Largest Subarray Length K | Greedy Approach
Asked in
Google 35 Amazon 28 Microsoft 22
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen