Skip to content
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

added some questions #708

Merged
merged 7 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
61 changes: 61 additions & 0 deletions docs/leetcode-Solutions/Rotate-image.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
---
id: rotate-image
sidebar_position: 5
title: Rotate Image
sidebar_label: Rotate Image
description: "This document explains the Rotate Image problem, including its description, approach, and implementation in C++."
tags: [leetcode, algorithms, problem-solving]
---

# rotate-image

## Description
You are given an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image **in-place**, which means you have to modify the input 2D matrix directly. **Do not** allocate another 2D matrix and do the rotation.

### Example:
**Input**: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
**Output**: `[[7,4,1],[8,5,2],[9,6,3]]`

**Input**: `matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]`
**Output**: `[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]`

## Approach
To rotate the matrix by 90 degrees in-place, the approach can be divided into two steps:

1. **Transpose the Matrix**: Convert the rows of the matrix into columns. This can be done by swapping `matrix[i][j]` with `matrix[j][i]` for all `i` and `j`.

2. **Reverse Each Row**: Once the matrix is transposed, reverse each row. This will complete the 90-degree rotation.

### Steps:
1. **Transpose** the matrix: Swap `matrix[i][j]` with `matrix[j][i]` for all `i` and `j`.
2. **Reverse each row** of the matrix.

## C++ Implementation

```cpp
#include <vector>
#include <algorithm>

class Solution {
public:
void rotate(std::vector<std::vector<int>>& matrix) {
int n = matrix.size();

// Step 1: Transpose the matrix
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
std::swap(matrix[i][j], matrix[j][i]);
}
}

// Step 2: Reverse each row
for (int i = 0; i < n; ++i) {
std::reverse(matrix[i].begin(), matrix[i].end());
}
}
};
```
Time Complexity: O(n^2) <br/>
Space Complexity: O(1)
74 changes: 74 additions & 0 deletions docs/leetcode-Solutions/group-anagrams.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
id: group-anagrams
sidebar_position: 6
title: Group Anagrams
sidebar_label: Group Anagrams
description: "This document explains the Group Anagrams problem, including its description, approach, and implementation in C++."
tags: [leetcode, algorithms, problem-solving]
---

# group-anagrams

## Description
Given an array of strings `strs`, group the anagrams together. You can return the answer in **any order**.

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.

### Example:
**Input**: `strs = ["eat","tea","tan","ate","nat","bat"]`
**Output**: `[["bat"],["nat","tan"],["ate","eat","tea"]]`

**Input**: `strs = [""]`
**Output**: `[[""]]`

**Input**: `strs = ["a"]`
**Output**: `[["a"]]`

## Approach
To group the anagrams, we can follow this approach:

1. **Sort each string**: For each string in the input array, sort the characters. This sorted version of the string will serve as a key because anagrams will result in the same sorted string.
2. **Use a hash map**: Use a hash map (unordered_map in C++) where the key is the sorted string and the value is a list of anagrams that correspond to that key.
3. **Group anagrams**: For each string, insert it into the hash map using its sorted version as the key. Finally, return the values of the hash map as the groups of anagrams.

### Steps:
1. Create a hash map to store the sorted string as the key and the original strings as the values.
2. Iterate over each string in the input array:
- Sort the string.
- Use the sorted string as the key and append the original string to the list of values for that key in the hash map.
3. Return the values of the hash map, which are the groups of anagrams.

## C++ Implementation

```cpp
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

class Solution {
public:
std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) {
std::unordered_map<std::string, std::vector<std::string>> anagramMap;

// Step 1: Iterate through each string
for (const std::string& str : strs) {
std::string sortedStr = str;
std::sort(sortedStr.begin(), sortedStr.end()); // Sort the string

// Step 2: Add the original string to the correct group in the map
anagramMap[sortedStr].push_back(str);
}

// Step 3: Collect the groups of anagrams from the map
std::vector<std::vector<std::string>> result;
for (const auto& entry : anagramMap) {
result.push_back(entry.second);
}

return result;
}
};
```
time complexity of this approach is O(n * k log k) <br/>
The space complexity is O(n * k) where n is the number of strings and k is the maximum length of a string
70 changes: 70 additions & 0 deletions docs/leetcode-Solutions/jumpgame2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
---
id: jump-game-ii
sidebar_position: 7
title: Jump Game II
sidebar_label: Jump Game II
description: "This document explains the Jump Game II problem, including its description, approach, and implementation in C++."
tags: [leetcode, algorithms, problem-solving]
---

# jump-game-ii

## Description
You are given a **0-indexed** array of integers `nums` of length `n`. Each element `nums[i]` represents the maximum number of steps you can jump forward from that index.

Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.

### Example:
**Input**: `nums = [2,3,1,1,4]`
**Output**: `2`
**Explanation**: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

**Input**: `nums = [2,3,0,1,4]`
**Output**: `2`

## Approach
To solve this problem, the key idea is to use a **greedy algorithm** to keep track of the maximum distance we can reach as we jump through the array.

### Steps:
1. **Initialize** variables to keep track of:
- `jumps`: the number of jumps made to reach the last index.
- `current_end`: the farthest index we can reach with the current jump.
- `farthest`: the farthest index we can reach from any position within the range of the current jump.

2. Iterate over the array:
- For each position `i`, update `farthest` as the maximum of `farthest` and `i + nums[i]` (the farthest point you can jump to from index `i`).
- If we reach the `current_end`, it means we must jump, so increment the `jumps` counter and update `current_end` to `farthest`.

3. Continue this process until we reach the last index.

## C++ Implementation

```cpp
#include <vector>
#include <algorithm>

class Solution {
public:
int jump(std::vector<int>& nums) {
int jumps = 0;
int current_end = 0;
int farthest = 0;

// Iterate until the second last element
for (int i = 0; i < nums.size() - 1; ++i) {
// Update the farthest point we can reach
farthest = std::max(farthest, i + nums[i]);

// If we have reached the end of the current jump range
if (i == current_end) {
++jumps; // We must make a jump
current_end = farthest; // Update the end point for the next jump
}
}

return jumps;
}
};
```
The time complexity is O(n) <br/>
The space complexity is O(1)
79 changes: 79 additions & 0 deletions docs/leetcode-Solutions/valid-parenthesis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
id: valid-parentheses
sidebar_position: 4
title: Valid Parentheses
sidebar_label: Valid Parentheses
description: "This document explains the Valid Parentheses problem, including its description, approach, and implementation in C++."
tags: [leetcode, algorithms, problem-solving]
---

# valid-parentheses

## Description
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['`, and `']'`, determine if the input string is valid.

An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

### Example:
**Input**: `s = "()[]{}"`
**Output**: `true`

**Input**: `s = "(]"`
**Output**: `false`

## Approach
To determine if the input string contains valid parentheses, we can use the following approach:

1. **Stack Data Structure**: Use a stack to track the opening parentheses as we encounter them.
2. **Matching Closing Parentheses**: When encountering a closing parenthesis, check if the stack is not empty and if the top element matches the corresponding opening parenthesis. If it does, pop the top element from the stack.
3. **Valid String**: The string is valid if at the end, the stack is empty (i.e., every opening parenthesis has been closed in the correct order).

### Steps:
- Traverse each character of the string:
- If it's an opening parenthesis (`'('`, `'{'`, `'['`), push it onto the stack.
- If it's a closing parenthesis (`')'`, `'}'`, `']'`), check if it matches the top of the stack. If it matches, pop the top; if it doesn't, return false.
- After processing all characters, return true if the stack is empty, indicating all parentheses are properly matched.

## C++ Implementation

```cpp
#include <stack>
#include <unordered_map>

class Solution {
public:
bool isValid(std::string s) {
std::stack<char> st;
std::unordered_map<char, char> mappings = {
{')', '('},
{'}', '{'},
{']', '['}
};

for (char c : s) {
// If the character is a closing bracket
if (mappings.find(c) != mappings.end()) {
// Get the top element of the stack, or a dummy value if the stack is empty
char topElement = st.empty() ? '#' : st.top();

// If the mapping for the closing bracket doesn't match the stack's top element, return false
if (topElement == mappings[c]) {
st.pop();
} else {
return false;
}
} else {
// If it's an opening bracket, push it onto the stack
st.push(c);
}
}

// If the stack is empty, then we have a valid string
return st.empty();
}
};
```
Time Complexity: O(n) <br/>
Space Complexity: O(n)