Skip to content

Commit 66399c5

Browse files
Merge branch 'CodeHarborHub:main' into lc-sol-3033
2 parents 2f1009b + 9ec2bd6 commit 66399c5

File tree

3 files changed

+271
-1
lines changed

3 files changed

+271
-1
lines changed

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

Lines changed: 1 addition & 1 deletion
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",
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)
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
---
2+
id: binary-number-with-alternating-bits
3+
title: Binary Number with Alternating Bits
4+
sidebar_label: 0693 - Binary Number with Alternating Bits
5+
tags:
6+
- Bit Manipulation
7+
- String
8+
- Bitmask
9+
description: "This is a solution to the Binary Number with Alternating Bits problem on LeetCode."
10+
---
11+
12+
## Problem Description
13+
14+
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
15+
16+
### Examples
17+
18+
**Example 1:**
19+
20+
```
21+
Input: n = 5
22+
Output: true
23+
Explanation: The binary representation of 5 is: 101
24+
```
25+
26+
**Example 2:**
27+
28+
```
29+
Input: n = 7
30+
Output: false
31+
Explanation: The binary representation of 7 is: 111.
32+
```
33+
34+
### Constraints
35+
36+
- $$1 \leq n \leq 2^{31} - 1$$
37+
38+
## Solution for Binary Number with Alternating Bits
39+
40+
### Approach 1: Convert to String
41+
#### Intuition and Algorithm
42+
43+
Let's convert the given number into a string of binary digits. Then, we should simply check that no two adjacent digits are the same.
44+
45+
## Code in Different Languages
46+
47+
<Tabs>
48+
<TabItem value="java" label="Java">
49+
<SolutionAuthor name="@Shreyash3087"/>
50+
51+
```java
52+
class Solution {
53+
public boolean hasAlternatingBits(int n) {
54+
String bits = Integer.toBinaryString(n);
55+
for (int i = 0; i < bits.length() - 1; i++) {
56+
if (bits.charAt(i) == bits.charAt(i+1)) {
57+
return false;
58+
}
59+
}
60+
return true;
61+
}
62+
}
63+
```
64+
65+
</TabItem>
66+
<TabItem value="python" label="Python">
67+
<SolutionAuthor name="@Shreyash3087"/>
68+
69+
```python
70+
class Solution(object):
71+
def hasAlternatingBits(self, n):
72+
bits = bin(n)
73+
return all(bits[i] != bits[i+1]
74+
for i in xrange(len(bits) - 1))
75+
```
76+
</TabItem>
77+
</Tabs>
78+
79+
## Complexity Analysis
80+
81+
### Time Complexity: $O(1)$
82+
83+
> **Reason**: For arbitrary inputs, we do $O(w)$ work, where w is the number of bits in `n`. However, $w \leq 32$.
84+
85+
### Space Complexity: $O(1)$
86+
87+
> **Reason**: or alternatively $O(w)$.
88+
89+
### Approach 2: Divide By Two
90+
#### Algorithm
91+
92+
We can get the last bit and the rest of the bits via `n % 2` and `n // 2` operations. Let's remember `cur`, the last bit of `n`. If the last bit ever equals the last bit of the remaining, then two adjacent bits have the same value, and the answer is `False`. Otherwise, the answer is `True`.
93+
94+
Also note that instead of `n % 2` and `n // 2`, we could have used operators `n & 1` and `n >>= 1` instead.
95+
96+
## Code in Different Languages
97+
98+
<Tabs>
99+
<TabItem value="java" label="Java">
100+
<SolutionAuthor name="@Shreyash3087"/>
101+
102+
```java
103+
class Solution {
104+
public boolean hasAlternatingBits(int n) {
105+
int cur = n % 2;
106+
n /= 2;
107+
while (n > 0) {
108+
if (cur == n % 2) return false;
109+
cur = n % 2;
110+
n /= 2;
111+
}
112+
return true;
113+
}
114+
}
115+
```
116+
117+
</TabItem>
118+
<TabItem value="python" label="Python">
119+
<SolutionAuthor name="@Shreyash3087"/>
120+
121+
```python
122+
class Solution(object):
123+
def hasAlternatingBits(self, n):
124+
n, cur = divmod(n, 2)
125+
while n:
126+
if cur == n % 2: return False
127+
n, cur = divmod(n, 2)
128+
return True
129+
```
130+
</TabItem>
131+
</Tabs>
132+
133+
## Complexity Analysis
134+
135+
### Time Complexity: $O(1)$
136+
137+
> **Reason**: For arbitrary inputs, we do $O(w)$ work, where w is the number of bits in n. However, $w \leq 32$.
138+
139+
### Space Complexity: $O(1)$
140+
141+
> **Reason**: constant space is used.
142+
143+
## References
144+
145+
- **LeetCode Problem**: [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/description/)
146+
147+
- **Solution Link**: [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/solutions/)

0 commit comments

Comments
 (0)