From 682da678eeada65ff35764429b4e4b1f1f323a10 Mon Sep 17 00:00:00 2001 From: abhishek farshwal Date: Mon, 14 Oct 2024 20:16:13 +0530 Subject: [PATCH 1/5] added group-anagram question --- docs/leetcode-Solutions/group-anagrams.md | 74 +++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 docs/leetcode-Solutions/group-anagrams.md diff --git a/docs/leetcode-Solutions/group-anagrams.md b/docs/leetcode-Solutions/group-anagrams.md new file mode 100644 index 000000000..e99147794 --- /dev/null +++ b/docs/leetcode-Solutions/group-anagrams.md @@ -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 +#include +#include +#include + +class Solution { +public: + std::vector> groupAnagrams(std::vector& strs) { + std::unordered_map> 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> result; + for (const auto& entry : anagramMap) { + result.push_back(entry.second); + } + + return result; + } +}; +``` +time complexity of this approach is O(n * k log k)
+The space complexity is O(n * k) where n is the number of strings and k is the maximum length of a string \ No newline at end of file From 52edde63775faaeeda1527259e0e098493b6b56b Mon Sep 17 00:00:00 2001 From: abhishek farshwal Date: Mon, 14 Oct 2024 20:16:57 +0530 Subject: [PATCH 2/5] added jumpgame 2 question --- docs/leetcode-Solutions/jumpgame2.md | 70 ++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 docs/leetcode-Solutions/jumpgame2.md diff --git a/docs/leetcode-Solutions/jumpgame2.md b/docs/leetcode-Solutions/jumpgame2.md new file mode 100644 index 000000000..0fc5c6d7d --- /dev/null +++ b/docs/leetcode-Solutions/jumpgame2.md @@ -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 +#include + +class Solution { +public: + int jump(std::vector& 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)
+The space complexity is O(1) \ No newline at end of file From 01a7f56204d5c27e8e0381cbee61f4cb27b13395 Mon Sep 17 00:00:00 2001 From: abhishek farshwal Date: Mon, 14 Oct 2024 20:17:43 +0530 Subject: [PATCH 3/5] added Rotate-image question --- docs/leetcode-Solutions/Rotate-image.md | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/leetcode-Solutions/Rotate-image.md diff --git a/docs/leetcode-Solutions/Rotate-image.md b/docs/leetcode-Solutions/Rotate-image.md new file mode 100644 index 000000000..1368d1d82 --- /dev/null +++ b/docs/leetcode-Solutions/Rotate-image.md @@ -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 +#include + +class Solution { +public: + void rotate(std::vector>& 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)
+Space Complexity: O(1) \ No newline at end of file From 2ff459dad05b2c073acc484081d00bbd728e0c08 Mon Sep 17 00:00:00 2001 From: abhishek farshwal Date: Mon, 14 Oct 2024 20:18:21 +0530 Subject: [PATCH 4/5] added valid-parenthesis question --- docs/leetcode-Solutions/valid-parenthesis.md | 79 ++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 docs/leetcode-Solutions/valid-parenthesis.md diff --git a/docs/leetcode-Solutions/valid-parenthesis.md b/docs/leetcode-Solutions/valid-parenthesis.md new file mode 100644 index 000000000..93a3ce3c0 --- /dev/null +++ b/docs/leetcode-Solutions/valid-parenthesis.md @@ -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 +#include + +class Solution { +public: + bool isValid(std::string s) { + std::stack st; + std::unordered_map 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)
+Space Complexity: O(n) \ No newline at end of file From 37f84289a7db167a609d68e0d72439e4b4f9f3a0 Mon Sep 17 00:00:00 2001 From: abhishek farshwal Date: Tue, 15 Oct 2024 20:55:07 +0530 Subject: [PATCH 5/5] added leetcode questions --- .../first-missing-positive.md | 67 ++++++++++++++++ docs/leetcode-Solutions/pow(x,n).md | 68 ++++++++++++++++ docs/leetcode-Solutions/remove--element.md | 65 +++++++++++++++ .../search-insert-position.md | 80 +++++++++++++++++++ 4 files changed, 280 insertions(+) create mode 100644 docs/leetcode-Solutions/first-missing-positive.md create mode 100644 docs/leetcode-Solutions/pow(x,n).md create mode 100644 docs/leetcode-Solutions/remove--element.md create mode 100644 docs/leetcode-Solutions/search-insert-position.md diff --git a/docs/leetcode-Solutions/first-missing-positive.md b/docs/leetcode-Solutions/first-missing-positive.md new file mode 100644 index 000000000..c0641e817 --- /dev/null +++ b/docs/leetcode-Solutions/first-missing-positive.md @@ -0,0 +1,67 @@ +--- +id: first-missing-positive +sidebar_position: 6 +title: First Missing Positive +sidebar_label: First Missing Positive +description: "This document explains the First Missing Positive problem, including its description, approach, and implementation in C++." +tags: [leetcode, algorithms, problem-solving] +--- + +# First Missing Positive + +## Description +Given an unsorted integer array `nums`, return the smallest missing positive integer. + +You must implement an algorithm that runs in **O(n)** time and uses constant extra space. + +### Example: +**Input**: `nums = [1,2,0]` +**Output**: `3` + +**Input**: `nums = [3,4,-1,1]` +**Output**: `2` + +**Input**: `nums = [7,8,9,11,12]` +**Output**: `1` + +## Approach +The goal is to find the smallest missing positive integer in linear time and constant space. + +### Steps: +1. **Index Mapping**: Since the smallest missing positive integer must lie between `1` and `n+1` (where `n` is the length of the array), we can try to place each number in its correct position, i.e., `nums[i] = i+1`. For example, `nums[i]` should be placed at index `nums[i] - 1`. +2. **Cycle Sort**: We can iterate through the array, and whenever we find a number between `1` and `n`, we place it in its correct index. We keep swapping elements until all numbers are either at their correct positions or are out of range. +3. **Find the Missing Positive**: After rearranging the array, the first index `i` where `nums[i] != i + 1` gives the first missing positive. If no such index is found, the missing positive is `n+1`. + +## C++ Implementation + +```cpp +#include +using namespace std; + +class Solution { +public: + int firstMissingPositive(vector& nums) { + int n = nums.size(); + + // Step 1: Place each number in its correct index + for (int i = 0; i < n; i++) { + while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) { + swap(nums[i], nums[nums[i] - 1]); // Swap to place nums[i] at its correct position + } + } + + // Step 2: Find the first missing positive number + for (int i = 0; i < n; i++) { + if (nums[i] != i + 1) { + return i + 1; // First missing positive + } + } + + return n + 1; // If all positions are correct, return n + 1 + } +}; +``` +### Time Complexity +**O(n): We iterate through the array twice, once for the rearrangement and once to find the missing positive, so the time complexity is linear.** +### Space Complexity +**O(1): The algorithm uses constant extra space since it modifies the input array in place.** \ No newline at end of file diff --git a/docs/leetcode-Solutions/pow(x,n).md b/docs/leetcode-Solutions/pow(x,n).md new file mode 100644 index 000000000..9aaf89891 --- /dev/null +++ b/docs/leetcode-Solutions/pow(x,n).md @@ -0,0 +1,68 @@ +--- +id: pow-x-n +sidebar_position: 7 +title: Pow(x, n) +sidebar_label: Pow(x, n) +description: "This document explains the Pow(x, n) problem, including its description, approach, and implementation in C++." +tags: [leetcode, algorithms, problem-solving] +--- + +# Pow(x, n) + +## Description +Implement `pow(x, n)`, which calculates `x` raised to the power `n` (i.e., `x^n`). + +### Example 1: +**Input**: `x = 2.00000`, `n = 10` +**Output**: `1024.00000` + +### Example 2: +**Input**: `x = 2.10000`, `n = 3` +**Output**: `9.26100` + +### Example 3: +**Input**: `x = 2.00000`, `n = -2` +**Output**: `0.25000` +**Explanation**: `2^(-2) = 1 / (2^2) = 1 / 4 = 0.25` + +## Approach +The goal is to efficiently compute `x^n` using **binary exponentiation** (also known as exponentiation by squaring), which reduces the time complexity to logarithmic. + +### Steps: +1. **Handle Negative Exponent**: If `n` is negative, we can convert the problem into `pow(1/x, -n)` to deal with the negative exponent. +2. **Binary Exponentiation**: The key observation is that: + - If `n` is even, then `x^n = (x^(n/2))^2`. + - If `n` is odd, then `x^n = x * x^(n-1)`. +3. **Iterative Method**: Use an iterative approach to calculate the power in logarithmic time. + +## C++ Implementation + +```cpp +class Solution { +public: + double myPow(double x, int n) { + long long N = n; // Use long long to handle n = -2^31 case + if (N < 0) { + x = 1 / x; + N = -N; + } + + double result = 1; + double current_product = x; + + while (N > 0) { + if (N % 2 == 1) { + result *= current_product; // If N is odd, multiply the result by current_product + } + current_product *= current_product; // Square the base + N /= 2; // Divide the exponent by 2 + } + + return result; + } +}; +``` +### Time Complexity +**O(log n): Each step either squares the base or multiplies it to the result, halving the exponent at each step.** +### Space Complexity +**O(1): The algorithm uses constant extra space.** \ No newline at end of file diff --git a/docs/leetcode-Solutions/remove--element.md b/docs/leetcode-Solutions/remove--element.md new file mode 100644 index 000000000..a6446892c --- /dev/null +++ b/docs/leetcode-Solutions/remove--element.md @@ -0,0 +1,65 @@ +--- +id: remove-element +sidebar_position: 5 +title: Remove Element +sidebar_label: Remove Element +description: "This document explains the Remove Element problem, including its description, approach, and implementation in C++." +tags: [leetcode, algorithms, problem-solving] +--- + +# Remove Element + +## Description +Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` **in-place**. The relative order of the elements may be changed. + +Since it is impossible to change the length of the array in some languages, you must instead have the result placed in the first part of the array. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. + +Return `k` after placing the final result in the first `k` slots of `nums`. + +Do not allocate extra space for another array. You must do this by modifying the input array **in-place** with O(1) extra memory. + +### Example: +**Input**: `nums = [3,2,2,3], val = 3` +**Output**: `2, nums = [2,2,_]` +**Explanation**: The first two elements of `nums` are `2`. It does not matter what is left beyond the returned length. + +**Input**: `nums = [0,1,2,2,3,0,4,2], val = 2` +**Output**: `5, nums = [0,1,4,0,3,_,_,_]` +**Explanation**: The first five elements of `nums` are `0`, `1`, `4`, `0`, and `3`. It does not matter what is left beyond the returned length. + +## Approach +The goal is to remove all occurrences of `val` from `nums` in place. We can achieve this by using a two-pointer approach: + +1. **Two Pointers**: One pointer (`i`) iterates through the array, and the other pointer (`k`) keeps track of the position where the next valid element (not equal to `val`) should be placed. +2. For each element in the array: + - If `nums[i]` is not equal to `val`, assign it to `nums[k]` and increment `k`. +3. Finally, return `k`, which represents the length of the modified array with all occurrences of `val` removed. + +## C++ Implementation + +```cpp +#include +using namespace std; + +class Solution { +public: + int removeElement(vector& nums, int val) { + int k = 0; // Counter for the new length + + // Loop through the array + for (int i = 0; i < nums.size(); i++) { + // If the current element is not equal to val, move it to the position k + if (nums[i] != val) { + nums[k] = nums[i]; + k++; // Increment the counter + } + } + + return k; // Return the new length of the array + } +}; +``` +### Time Complexity +**O(n): We traverse the array once, so the time complexity is linear in terms of the array size n.** +### Space Complexity +**O(1): The solution uses constant space, as we are modifying the input array in place.** \ No newline at end of file diff --git a/docs/leetcode-Solutions/search-insert-position.md b/docs/leetcode-Solutions/search-insert-position.md new file mode 100644 index 000000000..a6759303e --- /dev/null +++ b/docs/leetcode-Solutions/search-insert-position.md @@ -0,0 +1,80 @@ +--- +id: search-insert-position +sidebar_position: 4 +title: Search Insert Position +sidebar_label: Search Insert Position +description: "This document explains the Search Insert Position problem, including its description, approach, and implementation in C++." +tags: [leetcode, algorithms, problem-solving] +--- + +# Search Insert Position + +## Description +Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. + +You must write an algorithm with O(log n) runtime complexity. + +### Example: +**Input**: `nums = [1,3,5,6], target = 5` +**Output**: `2` + +**Input**: `nums = [1,3,5,6], target = 2` +**Output**: `1` + +**Input**: `nums = [1,3,5,6], target = 7` +**Output**: `4` + +## Approach +The problem requires O(log n) runtime complexity, which suggests that a **binary search** is the optimal solution. + +Steps: +1. **Binary Search**: We divide the array in halves, and search the target in the appropriate half based on the value comparison. +2. If the target is found, return the index. +3. If the target is not found, return the index where it would fit in a sorted order. + +### Binary Search Explanation: +- Start with two pointers: `low = 0` and `high = size of the array - 1`. +- Calculate the middle index: `mid = low + (high - low) / 2`. +- Compare `nums[mid]` with `target`: + - If `nums[mid] == target`, return `mid`. + - If `nums[mid] > target`, search the left half by updating `high = mid - 1`. + - If `nums[mid] < target`, search the right half by updating `low = mid + 1`. +- If the loop ends without finding the target, `low` will be the correct insertion position. + +## C++ Implementation + +```cpp +#include +using namespace std; + +class Solution { +public: + int searchInsert(vector& nums, int target) { + int low = 0, high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + // Check if the mid is the target + if (nums[mid] == target) { + return mid; + } + // Target is smaller, search left half + else if (nums[mid] > target) { + high = mid - 1; + } + // Target is larger, search right half + else { + low = mid + 1; + } + } + + // If not found, return the position where it would be inserted + return low; + } +}; +``` +### Time Complexity +**O(log n): We are dividing the array in half at each step, so the time complexity is logarithmic.** +### Space Complexity +**O(1): The space complexity is constant because no extra space is used apart from a few variables.** \ No newline at end of file