Skip to content

Commit 7c66128

Browse files
Merge branch 'CodeHarborHub:main' into lc-sol-3033
2 parents cb5012d + 00a97d2 commit 7c66128

File tree

3 files changed

+257
-1
lines changed

3 files changed

+257
-1
lines changed

dsa-problems/leetcode-problems/0600-0699.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ export const problems = [
597597
"problemName": "697. Degree of an Array",
598598
"difficulty": "Easy",
599599
"leetCodeLink": "https://leetcode.com/problems/degree-of-an-array",
600-
"solutionLink": "#"
600+
"solutionLink": "/dsa-solutions/lc-solutions/0600-0699/degree-of-an-array"
601601
},
602602
{
603603
"problemName": "698. Partition to K Equal Sum Subsets",
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
---
2+
id: arithmetic-slices
3+
title: Arithmetic Slices (LeetCode)
4+
sidebar_label: 0413-Arithmetic Slices
5+
tags:
6+
- Array
7+
- Dynamic Programming
8+
description: Given an integer array nums, return the number of arithmetic subarrays of nums.
9+
sidebar_position: 0413
10+
---
11+
12+
## Problem Description
13+
14+
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
15+
- For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences.
16+
17+
Given an integer array nums, return the number of arithmetic subarrays of nums.
18+
19+
A subarray is a contiguous subsequence of the array.
20+
21+
### Example 1
22+
23+
- **Input:** `nums = [1,2,3,4]`
24+
- **Output:** `3`
25+
- **Explanation:** We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
26+
27+
### Example 2
28+
29+
- **Input:** ` nums = [1]`
30+
- **Output:** `0`
31+
32+
### Constraints
33+
34+
- `1 <= nums.length <= 5000`
35+
- `-1000 <= nums[i] <= 1000`
36+
37+
## Approach
38+
- 1. Initialize Variables: Before looping through the nums, we initialize the ans variable to 0. This variable will accumulate the total count of arithmetic subarrays. We also initialize a cnt variable to 0; it keeps track of consecutive pairs with the same difference. The d variable, which holds the current common difference between pairs, is set to a number outside the valid range (3000) to handle the edge case at the beginning of the array.
39+
40+
- 2. Loop through pairwise(nums): We iterate over each pair (a, b) in pairwise(nums). Here, a and b represent consecutive elements in nums.
41+
42+
- 3. Check the Difference and Update Counter: We compare the difference b - a with the current d. If they're equal, increment cnt by 1, because this extends the current arithmetic subarray sequence by one element. If they're different, update d to the new difference b - a and reset cnt to 0, because we're starting to count a new set of arithmetic subarrays.
43+
44+
- 4. Update the Answer: Add the current cnt to ans in each iteration. By adding cnt, we're accounting for all the new arithmetic subarrays that end at the current element b. The reason adding cnt works is that for each extension of an arithmetic subarray by one element, we introduce exactly cnt new subarrays where cnt is the count of previous consecutive elements that were part of such subarrays.
45+
46+
- 5. Return Result: After the loop completes, ans represents the total number of arithmetic subarrays in nums, which is then returned as the final answer.
47+
48+
### Solution Code
49+
50+
#### Python
51+
52+
```python
53+
from itertools import pairwise
54+
55+
class Solution:
56+
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
57+
total_slices = 0
58+
current_sequence_length = 0
59+
previous_difference = 3000
60+
for current_num, next_num in pairwise(nums):
61+
current_difference = next_num - current_num
62+
if current_difference == previous_difference:
63+
current_sequence_length += 1
64+
else:
65+
previous_difference = current_difference
66+
current_sequence_length = 0
67+
total_slices += current_sequence_length
68+
return total_slices
69+
```
70+
71+
#### C++
72+
```c++
73+
class Solution {
74+
public:
75+
int numberOfArithmeticSlices(vector<int>& nums) {
76+
int totalSlices = 0;
77+
int currentStreak = 0;
78+
int previousDifference = 3000;
79+
for (int i = 0; i < nums.size() - 1; ++i) {
80+
int currentDifference = nums[i + 1] - nums[i];
81+
if (currentDifference == previousDifference) {
82+
++currentStreak;
83+
} else {
84+
previousDifference = currentDifference;
85+
currentStreak = 0;
86+
}
87+
totalSlices += currentStreak;
88+
}
89+
return totalSlices;
90+
}
91+
};
92+
93+
```
94+
95+
#### Java
96+
```Java
97+
class Solution {
98+
public int numberOfArithmeticSlices(int[] nums) {
99+
int arithmeticSliceCount = 0;
100+
int currentSliceLength = 0;
101+
int difference = 3000;
102+
for (int i = 0; i < nums.length - 1; ++i) {
103+
if (nums[i + 1] - nums[i] == difference) {
104+
++currentSliceLength;
105+
} else {
106+
difference = nums[i + 1] - nums[i];
107+
currentSliceLength = 0;
108+
}
109+
arithmeticSliceCount += currentSliceLength;
110+
}
111+
return arithmeticSliceCount;
112+
}
113+
}
114+
115+
```
116+
117+
118+
119+
120+
#### Conclusion
121+
- Time Complexity
122+
The time complexity is o(n).
123+
124+
- Space Complexity
125+
The space complexity is O(1).
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
---
2+
id: degree-of-an-array
3+
title: Degree of an Array
4+
sidebar_label: 0697 - Degree of an Array
5+
tags:
6+
- Hash Table
7+
- Array
8+
- Sliding Window
9+
description: "This is a solution to the Degree of an Array problem on LeetCode."
10+
---
11+
12+
## Problem Description
13+
14+
Given a non-empty array of non-negative integers `nums`, the **degree** of this array is defined as the maximum frequency of any one of its elements.
15+
16+
Your task is to find the smallest possible length of a (contiguous) subarray of `nums`, that has the same degree as `nums`.
17+
18+
### Examples
19+
20+
**Example 1:**
21+
22+
```
23+
Input: nums = [1,2,2,3,1]
24+
Output: 2
25+
Explanation:
26+
The input array has a degree of 2 because both elements 1 and 2 appear twice.
27+
Of the subarrays that have the same degree:
28+
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
29+
The shortest length is 2. So return 2.
30+
```
31+
32+
**Example 2:**
33+
34+
```
35+
Input: nums = [1,2,2,3,1,4,2]
36+
Output: 6
37+
Explanation:
38+
The degree is 3 because the element 2 is repeated 3 times.
39+
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
40+
```
41+
42+
### Constraints
43+
44+
- `nums.length` will be between 1 and 50,000.
45+
- `nums[i]` will be an integer between 0 and 49,999.
46+
47+
## Solution for Degree of an Array
48+
49+
### Approach: Left and Right Index
50+
#### Intuition and Algorithm
51+
52+
An array that has degree `d`, must have some element `x` occur `d` times. If some subarray has the same degree, then some element `x` (that occurred d times), still occurs `d` times. The shortest such subarray would be from the first occurrence of `x` until the last occurrence.
53+
54+
For each element in the given array, let's know `left`, the index of its first occurrence; and `right`, the index of its last occurrence. For example, with `nums = [1,2,3,2,5]` we have `left[2] = 1` and `right[2] = 3`.
55+
56+
Then, for each element `x` that occurs the maximum number of times, `right[x] - left[x] + 1` will be our candidate answer, and we'll take the minimum of those candidates.
57+
58+
## Code in Different Languages
59+
60+
<Tabs>
61+
<TabItem value="java" label="Java">
62+
<SolutionAuthor name="@Shreyash3087"/>
63+
64+
```java
65+
class Solution {
66+
public int findShortestSubArray(int[] nums) {
67+
Map<Integer, Integer> left = new HashMap(),
68+
right = new HashMap(), count = new HashMap();
69+
70+
for (int i = 0; i < nums.length; i++) {
71+
int x = nums[i];
72+
if (left.get(x) == null) {
73+
left.put(x, I);
74+
}
75+
right.put(x, i);
76+
count.put(x, count.getOrDefault(x, 0) + 1);
77+
}
78+
79+
int ans = nums.length;
80+
int degree = Collections.max(count.values());
81+
for (int x: count.keySet()) {
82+
if (count.get(x) == degree) {
83+
ans = Math.min(ans, right.get(x) - left.get(x) + 1);
84+
}
85+
}
86+
return ans;
87+
}
88+
}
89+
```
90+
91+
</TabItem>
92+
<TabItem value="python" label="Python">
93+
<SolutionAuthor name="@Shreyash3087"/>
94+
95+
```python
96+
class Solution(object):
97+
def findShortestSubArray(self, nums):
98+
left, right, count = {}, {}, {}
99+
for i, x in enumerate(nums):
100+
if x not in left:
101+
left[x] = i
102+
right[x] = i
103+
count[x] = count.get(x, 0) + 1
104+
105+
ans = len(nums)
106+
degree = max(count.values())
107+
for x in count:
108+
if count[x] == degree:
109+
ans = min(ans, right[x] - left[x] + 1)
110+
111+
return ans
112+
```
113+
</TabItem>
114+
</Tabs>
115+
116+
## Complexity Analysis
117+
118+
### Time Complexity: $O(N)$
119+
120+
> **Reason**: where N is the length of `nums`. Every loop is through $O(N)$ items with $O(1)$ work inside the for-block.
121+
122+
### Space Complexity: $O(N)$
123+
124+
> **Reason**: the space used by `left`, `right`, and `count`.
125+
126+
127+
## References
128+
129+
- **LeetCode Problem**: [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/description/)
130+
131+
- **Solution Link**: [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/solutions/)

0 commit comments

Comments
 (0)