Skip to content

Commit 1273db0

Browse files
authored
Merge pull request #1131 from mahek0620/valid-anagram
Added lc 242 and 243
2 parents dc52a4c + ee76ef4 commit 1273db0

File tree

2 files changed

+300
-0
lines changed

2 files changed

+300
-0
lines changed
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
---
2+
id: valid-anagram
3+
title: Valid Anagram
4+
sidebar_label: 0242 Valid Anagram
5+
tags:
6+
- String
7+
- Hash Table
8+
- Sorting
9+
- LeetCode
10+
- Python
11+
- Java
12+
- C++
13+
description: "This is a solution to the Valid Anagram problem on LeetCode."
14+
---
15+
16+
## Problem Description
17+
18+
Given two strings `s` and `t`, return true if `t` is an anagram of `s`, and false otherwise.
19+
20+
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
21+
22+
### Examples
23+
24+
**Example 1:**
25+
26+
```
27+
Input: s = "anagram", t = "nagaram"
28+
Output: true
29+
```
30+
31+
**Example 2:**
32+
33+
```
34+
Input: s = "rat", t = "car"
35+
Output: false
36+
```
37+
38+
### Constraints
39+
40+
- $1 <= s.length, t.length <= 5 * 10^4$
41+
- s and t consist of lowercase English letters.
42+
43+
## Solution for Valid Anagram Problem
44+
45+
### Approach
46+
47+
To determine if two strings `s` and `t` are anagrams, we can use the following approach:
48+
49+
1. **Character Counting**: Count the occurrences of each character in both strings using arrays of size 26 (since there are 26 lowercase letters).
50+
2. **Comparison**: Compare the two arrays. If they are identical, then `t` is an anagram of `s`.
51+
52+
### Code in Different Languages
53+
54+
<Tabs>
55+
<TabItem value="Python" label="Python" default>
56+
<SolutionAuthor name="@mahek0620"/>
57+
```python
58+
59+
class Solution:
60+
def isAnagram(self, s: str, t: str) -> bool:
61+
if len(s) != len(t):
62+
return False
63+
64+
# Initialize arrays to count occurrences of each character
65+
count_s = [0] * 26
66+
count_t = [0] * 26
67+
68+
# Count occurrences of each character in s
69+
for char in s:
70+
count_s[ord(char) - ord('a')] += 1
71+
72+
# Count occurrences of each character in t
73+
for char in t:
74+
count_t[ord(char) - ord('a')] += 1
75+
76+
# Compare the two arrays
77+
return count_s == count_t
78+
```
79+
</TabItem>
80+
<TabItem value="Java" label="Java">
81+
<SolutionAuthor name="@mahek0620"/>
82+
```java
83+
84+
class Solution {
85+
public boolean isAnagram(String s, String t) {
86+
if (s.length() != t.length()) {
87+
return false;
88+
}
89+
90+
// Initialize arrays to count occurrences of each character
91+
int[] count_s = new int[26];
92+
int[] count_t = new int[26];
93+
94+
// Count occurrences of each character in s
95+
for (char ch : s.toCharArray()) {
96+
count_s[ch - 'a']++;
97+
}
98+
99+
// Count occurrences of each character in t
100+
for (char ch : t.toCharArray()) {
101+
count_t[ch - 'a']++;
102+
}
103+
104+
// Compare the two arrays
105+
return Arrays.equals(count_s, count_t);
106+
}
107+
}
108+
```
109+
</TabItem>
110+
<TabItem value="C++" label="C++">
111+
<SolutionAuthor name="@mahek0620"/>
112+
```cpp
113+
114+
#include <vector>
115+
using namespace std;
116+
117+
class Solution {
118+
public:
119+
bool isAnagram(string s, string t) {
120+
if (s.length() != t.length()) {
121+
return false;
122+
}
123+
124+
// Initialize arrays to count occurrences of each character
125+
vector<int> count_s(26, 0);
126+
vector<int> count_t(26, 0);
127+
128+
// Count occurrences of each character in s
129+
for (char ch : s) {
130+
count_s[ch - 'a']++;
131+
}
132+
133+
// Count occurrences of each character in t
134+
for (char ch : t) {
135+
count_t[ch - 'a']++;
136+
}
137+
138+
// Compare the two arrays
139+
return count_s == count_t;
140+
}
141+
};
142+
```
143+
144+
</TabItem>
145+
</Tabs>
146+
147+
### Complexity Analysis
148+
149+
- **Time complexity**: O(n), where n is the length of the strings `s` and `t`. We iterate through both strings once to count characters and compare counts, which are both O(n).
150+
- **Space complexity**: O(1) for the fixed-size arrays in Python and O(26) = O(1) for arrays in Java and C++, since there are only 26 lowercase letters.
151+
152+
## References
153+
154+
- **LeetCode Problem:** [Valid Anagram](https://leetcode.com/problems/valid-anagram/)
155+
- **Solution Link:** [Valid Anagram Solution on LeetCode](https://leetcode.com/problems/valid-anagram/solution/)
156+
- **Author's GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
---
2+
id: shortest-word-distance
3+
title: Shortest Word Distance Solution
4+
sidebar_label: 0243 Shortest Word Distance
5+
tags:
6+
- Array
7+
- Two Pointers
8+
- LeetCode
9+
- Python
10+
- Java
11+
- C++
12+
description: "This is a solution to the Shortest Word Distance problem on LeetCode."
13+
---
14+
15+
## Problem Description
16+
17+
Given a list of words `words` and two words `word1` and `word2`, return the shortest distance between these two words in the list.
18+
19+
### Examples
20+
21+
**Example 1:**
22+
```
23+
Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
24+
Output: 3
25+
```
26+
27+
### Constraints
28+
29+
- You may assume that `words` contains at least two words.
30+
- All the words in `words` are guaranteed to be unique.
31+
- `word1` and `word2` are two distinct words in the list.
32+
33+
## Solution for Shortest Word Distance Problem
34+
35+
### Approach
36+
37+
To find the shortest distance between two words `word1` and `word2` in a list of words `words`, we can use the following approach:
38+
39+
1. **Two Pointers**: Use two pointers to track the most recent indices of `word1` and `word2` as we iterate through the list.
40+
2. **Update Distance**: For each occurrence of `word1` or `word2`, update the minimum distance found so far if possible.
41+
42+
### Code in Different Languages
43+
44+
<Tabs>
45+
<TabItem value="Python" label="Python" default>
46+
<SolutionAuthor name="@mahek0620"/>
47+
```python
48+
49+
class Solution:
50+
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
51+
index1 = -1
52+
index2 = -1
53+
min_distance = float('inf')
54+
55+
for i in range(len(words)):
56+
if words[i] == word1:
57+
index1 = i
58+
elif words[i] == word2:
59+
index2 = i
60+
61+
if index1 != -1 and index2 != -1:
62+
min_distance = min(min_distance, abs(index1 - index2))
63+
64+
return min_distance
65+
```
66+
</TabItem>
67+
<TabItem value="Java" label="Java">
68+
<SolutionAuthor name="@mahek0620"/>
69+
```java
70+
71+
import java.util.*;
72+
73+
class Solution {
74+
public int shortestDistance(String[] words, String word1, String word2) {
75+
int index1 = -1;
76+
int index2 = -1;
77+
int minDistance = Integer.MAX_VALUE;
78+
79+
for (int i = 0; i < words.length; i++) {
80+
if (words[i].equals(word1)) {
81+
index1 = i;
82+
} else if (words[i].equals(word2)) {
83+
index2 = i;
84+
}
85+
86+
if (index1 != -1 && index2 != -1) {
87+
minDistance = Math.min(minDistance, Math.abs(index1 - index2));
88+
}
89+
}
90+
91+
return minDistance;
92+
}
93+
}
94+
```
95+
</TabItem>
96+
<TabItem value="C++" label="C++">
97+
<SolutionAuthor name="@mahek0620"/>
98+
```cpp
99+
100+
#include <vector>
101+
#include <string>
102+
#include <algorithm>
103+
#include <climits>
104+
using namespace std;
105+
106+
class Solution {
107+
public:
108+
int shortestDistance(vector<string>& words, string word1, string word2) {
109+
int index1 = -1;
110+
int index2 = -1;
111+
int minDistance = INT_MAX;
112+
113+
for (int i = 0; i < words.size(); i++) {
114+
if (words[i] == word1) {
115+
index1 = i;
116+
} else if (words[i] == word2) {
117+
index2 = i;
118+
}
119+
120+
if (index1 != -1 && index2 != -1) {
121+
minDistance = min(minDistance, abs(index1 - index2));
122+
}
123+
}
124+
125+
return minDistance;
126+
}
127+
};
128+
```
129+
130+
</TabItem>
131+
</Tabs>
132+
133+
### Complexity Analysis
134+
135+
- **Time complexity**: O(n), where n is the number of elements in the `words` array. We iterate through the array once.
136+
- **Space complexity**: O(1) in additional space, as we use only a few extra variables regardless of the input size.
137+
138+
## References
139+
140+
- **LeetCode Problem:** [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/)
141+
- **Solution Link:** [Shortest Word Distance Solution on LeetCode](https://leetcode.com/problems/shortest-word-distance/solution/)
142+
- **Author's GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)
143+
144+

0 commit comments

Comments
 (0)