Skip to content

Commit 2d7ee0a

Browse files
committed
Sync LeetCode submission Runtime - 884 ms (69.74%), Memory - 38 MB (50.00%)
1 parent 9f9a2ad commit 2d7ee0a

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, you are asked to construct the array <code>ans</code> of size <code>n-k+1</code> where <code>ans[i]</code> is the number of <strong>distinct</strong> numbers in the subarray <code>nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]]</code>.</p>
2+
3+
<p>Return <em>the array </em><code>ans</code>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [1,2,3,2,2,1,3], k = 3
10+
<strong>Output:</strong> [3,2,2,2,3]
11+
<strong>Explanation: </strong>The number of distinct elements in each subarray goes as follows:
12+
- nums[0:2] = [1,2,3] so ans[0] = 3
13+
- nums[1:3] = [2,3,2] so ans[1] = 2
14+
- nums[2:4] = [3,2,2] so ans[2] = 2
15+
- nums[3:5] = [2,2,1] so ans[3] = 2
16+
- nums[4:6] = [2,1,3] so ans[4] = 3
17+
</pre>
18+
19+
<p><strong class="example">Example 2:</strong></p>
20+
21+
<pre>
22+
<strong>Input:</strong> nums = [1,1,1,1,2,3,4], k = 4
23+
<strong>Output:</strong> [1,2,3,4]
24+
<strong>Explanation: </strong>The number of distinct elements in each subarray goes as follows:
25+
- nums[0:3] = [1,1,1,1] so ans[0] = 1
26+
- nums[1:4] = [1,1,1,2] so ans[1] = 2
27+
- nums[2:5] = [1,1,2,3] so ans[2] = 3
28+
- nums[3:6] = [1,2,3,4] so ans[3] = 4
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
36+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
37+
</ul>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Approach 1: Hash Map
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def distinctNumbers(self, nums: List[int], k: int) -> List[int]:
8+
n = len(nums)
9+
answer = [0] * (n - k + 1)
10+
11+
freq = {}
12+
13+
# Process first window
14+
for num in nums[:k]:
15+
freq[num] = freq.get(num, 0) + 1
16+
answer[0] = len(freq)
17+
18+
# Slide window and update freq
19+
for pos in range(k, n):
20+
left = nums[pos - k]
21+
freq[left] -= 1
22+
if freq[left] == 0:
23+
del freq[left]
24+
25+
right = nums[pos]
26+
freq[right] = freq.get(right, 0) + 1
27+
28+
answer[pos - k + 1] = len(freq)
29+
30+
return answer
31+

0 commit comments

Comments
 (0)