Skip to content

Added lc 242 and 243 #1131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions dsa-solutions/lc-solutions/0200-0299/0242-valid-anagram.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
---
id: valid-anagram
title: Valid Anagram
sidebar_label: 0242 Valid Anagram
tags:
- String
- Hash Table
- Sorting
- LeetCode
- Python
- Java
- C++
description: "This is a solution to the Valid Anagram problem on LeetCode."
---

## Problem Description

Given two strings `s` and `t`, return true if `t` is an anagram of `s`, and false otherwise.

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.

### Examples

**Example 1:**

```
Input: s = "anagram", t = "nagaram"
Output: true
```

**Example 2:**

```
Input: s = "rat", t = "car"
Output: false
```

### Constraints

- $1 <= s.length, t.length <= 5 * 10^4$
- s and t consist of lowercase English letters.

## Solution for Valid Anagram Problem

### Approach

To determine if two strings `s` and `t` are anagrams, we can use the following approach:

1. **Character Counting**: Count the occurrences of each character in both strings using arrays of size 26 (since there are 26 lowercase letters).
2. **Comparison**: Compare the two arrays. If they are identical, then `t` is an anagram of `s`.

### Code in Different Languages

<Tabs>
<TabItem value="Python" label="Python" default>
<SolutionAuthor name="@mahek0620"/>
```python

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

# Initialize arrays to count occurrences of each character
count_s = [0] * 26
count_t = [0] * 26

# Count occurrences of each character in s
for char in s:
count_s[ord(char) - ord('a')] += 1

# Count occurrences of each character in t
for char in t:
count_t[ord(char) - ord('a')] += 1

# Compare the two arrays
return count_s == count_t
```
</TabItem>
<TabItem value="Java" label="Java">
<SolutionAuthor name="@mahek0620"/>
```java

class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}

// Initialize arrays to count occurrences of each character
int[] count_s = new int[26];
int[] count_t = new int[26];

// Count occurrences of each character in s
for (char ch : s.toCharArray()) {
count_s[ch - 'a']++;
}

// Count occurrences of each character in t
for (char ch : t.toCharArray()) {
count_t[ch - 'a']++;
}

// Compare the two arrays
return Arrays.equals(count_s, count_t);
}
}
```
</TabItem>
<TabItem value="C++" label="C++">
<SolutionAuthor name="@mahek0620"/>
```cpp

#include <vector>
using namespace std;

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}

// Initialize arrays to count occurrences of each character
vector<int> count_s(26, 0);
vector<int> count_t(26, 0);

// Count occurrences of each character in s
for (char ch : s) {
count_s[ch - 'a']++;
}

// Count occurrences of each character in t
for (char ch : t) {
count_t[ch - 'a']++;
}

// Compare the two arrays
return count_s == count_t;
}
};
```

</TabItem>
</Tabs>

### Complexity Analysis

- **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).
- **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.

## References

- **LeetCode Problem:** [Valid Anagram](https://leetcode.com/problems/valid-anagram/)
- **Solution Link:** [Valid Anagram Solution on LeetCode](https://leetcode.com/problems/valid-anagram/solution/)
- **Author's GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)
144 changes: 144 additions & 0 deletions dsa-solutions/lc-solutions/0200-0299/0243-shortest-word-distanc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
---
id: shortest-word-distance
title: Shortest Word Distance Solution
sidebar_label: 0243 Shortest Word Distance
tags:
- Array
- Two Pointers
- LeetCode
- Python
- Java
- C++
description: "This is a solution to the Shortest Word Distance problem on LeetCode."
---

## Problem Description

Given a list of words `words` and two words `word1` and `word2`, return the shortest distance between these two words in the list.

### Examples

**Example 1:**
```
Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output: 3
```

### Constraints

- You may assume that `words` contains at least two words.
- All the words in `words` are guaranteed to be unique.
- `word1` and `word2` are two distinct words in the list.

## Solution for Shortest Word Distance Problem

### Approach

To find the shortest distance between two words `word1` and `word2` in a list of words `words`, we can use the following approach:

1. **Two Pointers**: Use two pointers to track the most recent indices of `word1` and `word2` as we iterate through the list.
2. **Update Distance**: For each occurrence of `word1` or `word2`, update the minimum distance found so far if possible.

### Code in Different Languages

<Tabs>
<TabItem value="Python" label="Python" default>
<SolutionAuthor name="@mahek0620"/>
```python

class Solution:
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
index1 = -1
index2 = -1
min_distance = float('inf')

for i in range(len(words)):
if words[i] == word1:
index1 = i
elif words[i] == word2:
index2 = i

if index1 != -1 and index2 != -1:
min_distance = min(min_distance, abs(index1 - index2))

return min_distance
```
</TabItem>
<TabItem value="Java" label="Java">
<SolutionAuthor name="@mahek0620"/>
```java

import java.util.*;

class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int index1 = -1;
int index2 = -1;
int minDistance = Integer.MAX_VALUE;

for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
index1 = i;
} else if (words[i].equals(word2)) {
index2 = i;
}

if (index1 != -1 && index2 != -1) {
minDistance = Math.min(minDistance, Math.abs(index1 - index2));
}
}

return minDistance;
}
}
```
</TabItem>
<TabItem value="C++" label="C++">
<SolutionAuthor name="@mahek0620"/>
```cpp

#include <vector>
#include <string>
#include <algorithm>
#include <climits>
using namespace std;

class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
int index1 = -1;
int index2 = -1;
int minDistance = INT_MAX;

for (int i = 0; i < words.size(); i++) {
if (words[i] == word1) {
index1 = i;
} else if (words[i] == word2) {
index2 = i;
}

if (index1 != -1 && index2 != -1) {
minDistance = min(minDistance, abs(index1 - index2));
}
}

return minDistance;
}
};
```

</TabItem>
</Tabs>

### Complexity Analysis

- **Time complexity**: O(n), where n is the number of elements in the `words` array. We iterate through the array once.
- **Space complexity**: O(1) in additional space, as we use only a few extra variables regardless of the input size.

## References

- **LeetCode Problem:** [Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/)
- **Solution Link:** [Shortest Word Distance Solution on LeetCode](https://leetcode.com/problems/shortest-word-distance/solution/)
- **Author's GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)


Loading