Skip to content

Commit 2fc9875

Browse files
Merge branch 'CodeHarborHub:main' into lcsol-3028
2 parents 1f80123 + 0b8f4f8 commit 2fc9875

File tree

9 files changed

+973
-3
lines changed

9 files changed

+973
-3
lines changed

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,7 @@ export const problems = [
573573
"problemName": "693. Binary Number with Alternating Bits",
574574
"difficulty": "Easy",
575575
"leetCodeLink": "https://leetcode.com/problems/binary-number-with-alternating-bits",
576-
"solutionLink": "#"
576+
"solutionLink": "/dsa-solutions/lc-solutions/0600-0699/binary-number-with-alternating-bits"
577577
},
578578
{
579579
"problemName": "694. Number of Distinct Islands",
@@ -591,13 +591,13 @@ export const problems = [
591591
"problemName": "696. Count Binary Substrings",
592592
"difficulty": "Easy",
593593
"leetCodeLink": "https://leetcode.com/problems/count-binary-substrings",
594-
"solutionLink": "#"
594+
"solutionLink": "/dsa-solutions/lc-solutions/0600-0699/count-binary-substrings"
595595
},
596596
{
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: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
---
2+
id: sort-characters-by-frequency
3+
title: Sort Characters By Frequency (LeetCode)
4+
sidebar_label: 0451-Sort Characters By Frequency
5+
tags:
6+
- Hash Table
7+
- String
8+
- Sorting
9+
- Heap(Priority Queue)
10+
- Bucket Sort
11+
- Counting
12+
description: Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
13+
sidebar_position: 0451
14+
---
15+
16+
## Problem Description
17+
18+
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
19+
20+
Return the sorted string. If there are multiple answers, return any of them.
21+
22+
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
23+
24+
### Example 1
25+
26+
- **Input:** ` s = "tree" `
27+
- **Output:** `"eert"`
28+
- **Explanation:** 'e' appears twice while 'r' and 't' both appear once.So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
29+
30+
### Example 2
31+
32+
- **Input:** ` s = "cccaaa" `
33+
- **Output:** `"aaaccc"`
34+
- **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.Note that "cacaca" is incorrect, as the same characters must be together.
35+
36+
### Example 3
37+
38+
- **Input:** ` s = "Aabb" `
39+
- **Output:** `"bbAa"`
40+
- **Explanation:** "bbaA" is also a valid answer, but "Aabb" is incorrect.Note that 'A' and 'a' are treated as two different characters.
41+
42+
43+
44+
### Constraints
45+
46+
- `1 <= s.length <= 5 * 105`
47+
- `s consists of uppercase and lowercase English letters and digits.`
48+
49+
## Approach
50+
51+
- 1. Count the occurrences: We need to go through the string and count the occurrences of each character. This can be done efficiently by using a hash table or a counter data structure where each character is a key, and its count is the value.
52+
53+
- 2. Sort based on counts: Once we have the counts, the next step is to sort the characters by these counts in descending order. We want the characters with higher counts to come first.
54+
55+
- 3. With these counts, we can construct a new string.
56+
57+
58+
59+
### Solution Code
60+
61+
#### C++
62+
63+
```c++
64+
class Solution {
65+
public:
66+
string frequencySort(string s) {
67+
unordered_map<char, int> frequencyMap;
68+
for (char ch : s) {
69+
++frequencyMap[ch];
70+
}
71+
vector<char> uniqueChars;
72+
for (auto& keyValue : frequencyMap) {
73+
uniqueChars.push_back(keyValue.first);
74+
}
75+
sort(uniqueChars.begin(), uniqueChars.end(), [&](char a, char b) {
76+
return frequencyMap[a] > frequencyMap[b];
77+
});
78+
string result;
79+
for (char ch : uniqueChars) {
80+
result += string(frequencyMap[ch], ch);
81+
}
82+
return result;
83+
}
84+
};
85+
86+
```
87+
88+
#### java
89+
```java
90+
class Solution {
91+
public String frequencySort(String s) {
92+
Map<Character, Integer> frequencyMap = new HashMap<>(52);
93+
for (int i = 0; i < s.length(); ++i) {
94+
frequencyMap.merge(s.charAt(i), 1, Integer::sum);
95+
}
96+
List<Character> characters = new ArrayList<>(frequencyMap.keySet());
97+
characters.sort((a, b) -> frequencyMap.get(b) - frequencyMap.get(a));
98+
StringBuilder sortedString = new StringBuilder();
99+
for (char c : characters) {
100+
for (int frequency = frequencyMap.get(c); frequency > 0; --frequency) {
101+
sortedString.append(c);
102+
}
103+
}
104+
return sortedString.toString();
105+
}
106+
}
107+
108+
```
109+
110+
#### Python
111+
```python
112+
class Solution:
113+
def frequencySort(self, s: str) -> str:
114+
char_frequency = Counter(s)
115+
sorted_characters = sorted(char_frequency.items(), key=lambda item: -item[1])
116+
frequency_sorted_string = ''.join(character * frequency for character, frequency in sorted_characters)
117+
return frequency_sorted_string
118+
```
119+
120+
#### Conclusion
121+
The above solutions use two-pointers approach to reverse the string.
122+
- 1. Time complexity: O(n logn)
123+
- 2. Space complexity: O(n)

0 commit comments

Comments
 (0)