-
-
Notifications
You must be signed in to change notification settings - Fork 211
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'ajay-dhangar:main' into main
- Loading branch information
Showing
24 changed files
with
3,694 additions
and
811 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
--- | ||
id: merge-k-sorted-arrays | ||
title: Merge K Sorted Arrays | ||
sidebar_label: GFG | ||
tags: [GFG, Arrays, Sorting, Heap, DSA] | ||
description: Given k sorted arrays with each of size k arranged in the form of a matrix of size k * k. The task is to merge them into one sorted array. | ||
--- | ||
|
||
# Partition Equal Subset Sum Algorithm (GFG) | ||
|
||
## Description | ||
|
||
The **Merge K Sorted Arrays** problem is an intuitive problem based on Priority Queue where we have to merge k sorted arrays into one final sorted array. | ||
|
||
### Problem Definition | ||
|
||
Given: | ||
|
||
- A 2D array of integers `arr` of size k\*k. | ||
|
||
Objective: | ||
|
||
- Merge these arrays into 1 sorted array. Return the merged sorted array. | ||
|
||
### Algorithm Overview | ||
|
||
1. **Min Heap Approach**: | ||
|
||
- Creating a `MinHeap` and Insert the `first` element `of all the k arrays`. | ||
- Remove the `top most` element of Minheap and `put` it in the output array. | ||
- And insert the `next` element `from`the `array of removed` elements. | ||
- To get the `result` the step must continue until there is no element left in the MinHeap. | ||
|
||
2. **Return** `result`, which is the final sorted array after merging k sorted arrays. | ||
|
||
### Time Complexity | ||
|
||
- **Time Complexity**: O(K^2\* log(K)), where insertion and deletion in a Min Heap requires log K time and for all K^2 elements it takes (K^2 \* log(K)) time | ||
- **Space Complexity**: O(K) for the result array. | ||
|
||
### C++ Implementation | ||
|
||
```cpp | ||
#include <vector> | ||
using namespace std; | ||
|
||
//User function Template for C++ | ||
|
||
|
||
class Solution | ||
{ | ||
public: | ||
|
||
class triplet{ | ||
public: | ||
int val; | ||
int arr; | ||
int i_indx; | ||
}; | ||
|
||
struct cmp{ | ||
bool operator()(triplet a , triplet b){ | ||
return (a.val > b.val); | ||
} | ||
}; | ||
//Function to merge k sorted arrays. | ||
vector<int> mergeKArrays(vector<vector<int>> arr, int k) | ||
{ | ||
//code here | ||
priority_queue<triplet , vector<triplet> , cmp> pq_min; | ||
|
||
|
||
for(int i = 0 ; i < k ; i++){ | ||
pq_min.push({arr[i][0] , i , 0});// pushing the first element of each array | ||
//Heap Node => { element , array-number , indx of element in that array} | ||
} | ||
|
||
vector<int> ans; | ||
|
||
while(ans.size() != k*k){ | ||
|
||
triplet f = pq_min.top(); | ||
pq_min.pop(); | ||
|
||
ans.push_back(f.val); | ||
|
||
int arr_indx = f.arr , i = f.i_indx; | ||
i = i+1; | ||
|
||
if(i < arr[arr_indx].size()){ | ||
pq_min.push({arr[arr_indx][i] , arr_indx , i}); //Pushing the next of that array from which popped out elements belongs to | ||
} | ||
} | ||
|
||
return ans; | ||
} | ||
}; | ||
|
||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
--- | ||
id: sliding-window-maximum | ||
title: Sliding Window Maximum | ||
sidebar_label: LeetCode 239 | ||
tags: [LeetCode , Arrays, Queue , Sliding Window , Heap (Priority Queue) , Monotonic Queue] | ||
description: Given array of integers nums , with sliding window of size k which is moving from the very left of the array to the very right.Return the max for each sliding window. | ||
--- | ||
|
||
# Sliding Window Maximum (LeetCode 239) | ||
|
||
## Description | ||
|
||
The **Sliding Window Maximum** problem involves finding the maximum value in each subarray of fixed size k that slides across array from left to right. | ||
|
||
### Problem Definition | ||
|
||
Given: | ||
|
||
- An array of integers `nums` of size N , with a sliding window of size K , moving from left to right , every time sliding window shifts to right by 1 position. | ||
|
||
Objective: | ||
|
||
- Return the max for each sliding window of size K. | ||
|
||
### Algorithm Overview | ||
|
||
1. **Using Deque*: | ||
|
||
- Create a `Deque`, `dq` of `capacity k`, that stores only useful elements of current window of k elements. | ||
- An element is `useful` if it is in current window and is `greater` than all other `elements on right side` of it in current window. | ||
- Process all array elements one by one and maintain dq to contain useful elements of current window and these useful elements are maintained in sorted order. | ||
- The element at `front` of the dq is the `largest` and `element at rear/back` of dq `is` the `smallest of current window`. | ||
|
||
2. **Return** `result`, which is the final array containing max of each sliding window of size k. | ||
|
||
### Time Complexity | ||
|
||
- **Time Complexity**: O(N) time | ||
- **Space Complexity**: O(K) for the deque. | ||
|
||
### C++ Implementation | ||
|
||
```cpp | ||
#include <vector> | ||
using namespace std; | ||
|
||
//User function Template for C++ | ||
|
||
class Solution { | ||
public: | ||
vector<int> maxSlidingWindow(vector<int>& a, int k) { | ||
|
||
|
||
vector<int> ans; int n = a.size(); | ||
deque<int> dq; | ||
|
||
int i = 0; | ||
for(int j = 0 ; j < n ; j++){ | ||
|
||
while(!dq.empty() && dq.back() < a[j]){ | ||
//pop all the elements from the back if smaller than the current element since max of that window is the current element since greater than all of them. | ||
dq.pop_back(); | ||
} | ||
|
||
dq.push_back(a[j]); // push the current element | ||
|
||
if(j-i+1 == k){ | ||
ans.push_back(dq.front()); // max of that window is the deque front | ||
|
||
if(dq.front() == a[i]){ | ||
// if after shifting the window by 1 step the deque front is window's front element that need to be popped b/c now window is changed ,and so window max also. | ||
dq.pop_front(); | ||
} | ||
|
||
i++; | ||
} | ||
} | ||
|
||
return ans; | ||
|
||
} | ||
}; | ||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
--- | ||
id: balanced-parentheses | ||
title: Balanced Parentheses | ||
sidebar_label: Balanced Parentheses | ||
description: "The Balanced Parentheses problem involves determining whether a given string of parentheses is valid, meaning every opening bracket has a corresponding closing bracket in the correct order." | ||
tags: [dsa, algorithms, stack] | ||
--- | ||
|
||
### Definition: | ||
The Balanced Parentheses problem is a classic problem in computer science that checks if a string containing parentheses is valid. A string is considered valid if every opening parenthesis has a corresponding closing parenthesis and they are properly nested. | ||
|
||
### Problem Statement: | ||
Given a string `s` consisting of parentheses (i.e., `(`, `)`, `{`, `}`, `[`, `]`), determine if the input string is valid. An input string is valid if: | ||
- Open brackets are closed by the same type of brackets. | ||
- Open brackets are closed in the correct order. | ||
|
||
### Algorithm Steps: | ||
|
||
1. **Initialize a Stack:** Use a stack to keep track of opening parentheses. | ||
2. **Iterate through the string:** For each character in the string: | ||
- If it is an opening bracket, push it onto the stack. | ||
- If it is a closing bracket, check if the stack is not empty and the top of the stack is the corresponding opening bracket; if so, pop the stack. If not, return false. | ||
3. **Final Check:** After processing all characters, if the stack is empty, return true (all brackets are matched); otherwise, return false. | ||
|
||
### Steps Involved: | ||
**1. Stack Structure:** | ||
- Use a stack data structure to store opening brackets. | ||
|
||
**2. Functions:** | ||
- `isValid(s: str) -> bool:` Checks if the parentheses in the string are balanced. | ||
|
||
### Time Complexity: | ||
- The time complexity of the `isValid` function is `O(n)`, where `n` is the length of the string. This is because we scan through the string once, and each push/pop operation on the stack takes constant time. | ||
|
||
### Space Complexity: | ||
- The space complexity is `O(n)` in the worst case, where all characters in the string are opening brackets, and they are stored in the stack. | ||
|
||
### Sample Input: | ||
"()" "()[]{}" "(]" "([)]" "{[]}" | ||
|
||
### Sample Output: | ||
true true false false true | ||
|
||
### Explanation of Sample: | ||
- The input strings are evaluated for balanced parentheses. | ||
- `()`, `()[]{}`, and `{[]}` are valid, while `(]` and `([)]` are not, due to mismatched or improperly nested brackets. | ||
|
||
### Python Implementation: | ||
|
||
```python | ||
def isValid(s: str) -> bool: | ||
stack = [] | ||
mapping = {")": "(", "}": "{", "]": "["} | ||
|
||
for char in s: | ||
if char in mapping: | ||
top_element = stack.pop() if stack else '#' | ||
if mapping[char] != top_element: | ||
return False | ||
else: | ||
stack.append(char) | ||
|
||
return not stack | ||
|
||
# Sample Test Cases | ||
test_cases = ["()", "()[]{}", "(]", "([)]", "{[]}"] | ||
for case in test_cases: | ||
print(f"{case}: {isValid(case)}") | ||
|
||
``` | ||
|
||
### C++ Implementation: | ||
```cpp | ||
#include <iostream> | ||
#include <stack> | ||
#include <unordered_map> | ||
using namespace std; | ||
|
||
bool isValid(string s) { | ||
stack<char> stack; | ||
unordered_map<char, char> mapping = {{')', '('}, {'}', '{'}, {']', '['}}; | ||
|
||
for (char &c : s) { | ||
if (mapping.count(c)) { | ||
char top_element = stack.empty() ? '#' : stack.top(); | ||
stack.pop(); | ||
if (mapping[c] != top_element) { | ||
return false; | ||
} | ||
} else { | ||
stack.push(c); | ||
} | ||
} | ||
|
||
return stack.empty(); | ||
} | ||
|
||
// Sample Test Cases | ||
int main() { | ||
string test_cases[] = {"()", "()[]{}", "(]", "([)]", "{[]}"}; | ||
for (const string& case : test_cases) { | ||
cout << case << ": " << (isValid(case) ? "true" : "false") << endl; | ||
} | ||
return 0; | ||
} | ||
``` |
Oops, something went wrong.