Merge branch 'main' of https://github.com/MakeContributions/DSA into added-new-algorithm

pull/1056/head
Pranav-Rustagi 2022-10-20 18:59:32 +05:30
commit c2f2a4cb20
12 changed files with 408 additions and 12 deletions

View File

@ -8,7 +8,9 @@ jobs:
codespell: codespell:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- uses: actions/setup-python@v2 - uses: actions/setup-python@v4
with:
python-version: 3.x
- run: pip install codespell - run: pip install codespell
- run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./docs/es,./docs/tr,./.github,./algorithms/CSharp/test" - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./docs/es,./docs/tr,./.github,./algorithms/CSharp/test"

View File

@ -0,0 +1,70 @@
#include <bits/stdc++.h>
using namespace std;
bool areBracketsBalanced (string expr)
{
stack < char >s;
char x;
// Traversing the Expression
for (int i = 0; i < expr.length (); i++)
if (expr[i] == '(' || expr[i] == '[' ||expr[i] == '{')
{
// Push the element in the stack
s.push (expr[i]);
continue;
}
// IF current current character is not opening
// bracket, then it must be closing. So stack
// cannot be empty at this point.
if (s.empty ())
return false;
switch (expr[i])
{
case ')': // Store the top element in a
x = s.top ();
s.pop ();
if (x == '{' || x == '[')
return false;
break;
case '}': // Store the top element in b
x = s.top ();
s.pop ();
if (x == '(' || x == '[')
return false;
break;
case ']': x = s.top ();
s.pop ();
if (x == '(' || x == '{')
return false;
break;
}
}
return (s.empty ());
}
// Driver code
int main ()
{
string expr = "{()}[]";
// Function call
if (areBracketsBalanced (expr))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
// Output:-
// Enter the brackets to check if its balanced or not : [{}]
// Balanced
// Enter the brackets to check if its balanced or not : {]
Not Balanced

View File

@ -20,7 +20,7 @@ int maxSubArrSum_A(int a[],int n){
return maxSum; return maxSum;
} }
// Appraoch B - Cumulative Sum Approach O(n^2) // Approach B - Cumulative Sum Approach O(n^2)
int maxSubArrSum_B(int a[],int n){ int maxSubArrSum_B(int a[],int n){
int currSum[n+1]; currSum[0] = 0; int currSum[n+1]; currSum[0] = 0;
for(int i=1;i<=n;++i){ for(int i=1;i<=n;++i){

View File

@ -0,0 +1,76 @@
// Rod Cutting Problem
// Given a rod of length n and a list of rod prices of length i, where 1 <= i <= n, find the optimal way to cut the rod into smaller rods to maximize profit.
// Rod Cutting Optimal Approach
// We will solve this problem in a bottom-up manner. (iteratively)
// In the bottom-up approach, we solve smaller subproblems first, then move on to larger subproblems.
// The following bottom-up approach computes dp[i], which stores maximum profit achieved from the rod of length i from 1 to len.
// It uses the value of smaller values i already computed.
// Space complexity: O(n)
// Time complexity: O(n^n)
// Solution
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Function to find the maximum revenue from cutting a rod of length (len)
// where the rod of length (i) has cost (prices[i - 1])
int RodCutting(vector<int> &prices, int len)
{
// (dp) stores the maximum revenue achieved from cutting a rod of length (from 1 to len)
vector<int> dp(len + 1, 0);
// If the rod length is negative (invalid) or zero there's no revenue from it
if (len <= 0)
{
return 0;
}
// Cut a rod of length (i)
for (int i = 1; i <= len; i++)
{
// divide the rod of length (i) into two rods of lengths (j) and (i - j)
// and store the maximum revenue
for (int j = 0; j < i; j++)
{
// (dp[i]) stores the maximum revenue achieved from cutting a rod of length (i)
dp[i] = max(dp[i], prices[j] + dp[i - j - 1]);
}
}
// (dp[len]) contains the maximum revenue from cutting a rod of length (len)
return dp[len];
}
int main()
{
int len;
cout << "Enter the rod length :";
cin >> len;
vector<int> prices(len);
for (int i = 1; i <= len; i++)
{
cout << "Enter the price of the rod of length " << i << " :";
cin >> prices[i - 1];
}
cout << "Maximum revenue = " << RodCutting(prices, len);
return 0;
}
// Input and output:
// 1. prices[] = [1, 5, 8, 9, 10, 17, 17, 20]
// rod length = 4
// Best: Cut the rod into two pieces of length 2 each to gain revenue of 5 + 5 = 10
// 2. prices[] = [1, 5, 8, 9, 10, 17, 17, 20]
// rod length = 8
// Best: Cut the rod into two pieces of length 2 and 6 to gain revenue of 5 + 17 = 22
// 3. prices[] = [3, 5, 8, 9, 10, 17, 17, 20]
// rod length = 8
// Best: Cut the rod into eight pieces of length 1 to gain revenue of 8 * 3 = 24

View File

@ -31,7 +31,7 @@
- [Next permutation](Arrays/next-permutation.cpp) - [Next permutation](Arrays/next-permutation.cpp)
- [Maximum Minimum Average of numbers](Arrays/max-min-avg.cpp) - [Maximum Minimum Average of numbers](Arrays/max-min-avg.cpp)
- [Sparse Matrix](Arrays/sparse_matrix.cpp) - [Sparse Matrix](Arrays/sparse_matrix.cpp)
- [Balanced Parenthesis](Arrays/balanced-parenthesis.cpp)
## Dynamic-Programming ## Dynamic-Programming
@ -42,6 +42,7 @@
- [Matrix chain Multiplication](Dynamic-Programming/matrix-chain-multiplication.cpp) - [Matrix chain Multiplication](Dynamic-Programming/matrix-chain-multiplication.cpp)
- [Edit Distance](Dynamic-Programming/edit-distance.cpp) - [Edit Distance](Dynamic-Programming/edit-distance.cpp)
- [Fibonacci](Dynamic-Programming/fibonacci.cpp) - [Fibonacci](Dynamic-Programming/fibonacci.cpp)
- [Rod Cutting](Dynamic-Programming/rod-cutting.cpp)
## Graphs ## Graphs
@ -156,6 +157,8 @@
## Trie ## Trie
- [Trie for searching](Trie/trie_search.cpp) - [Trie for searching](Trie/trie_search.cpp)
- [Trie for insert search and prefix_search](Trie/trie_insert_search_startWith.cpp)
- [Trie for delete](Trie/trie_delete.cpp)
# Maths # Maths

View File

@ -0,0 +1,44 @@
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 1e9;
#define inf2 2e18;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31);}
size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); }
};
struct TrieNode{ TrieNode* child[26]; bool isEnd;
TrieNode(){ isEnd = false; for(int i = 0; i<26; i++){ child[i] = NULL; } }
};
struct TrieNode* rootTrie;
void addTrie(string& s){ TrieNode* curr = rootTrie; for(int i = 0; i<s.length(); i++){ int n = s[i] - 'a';if(curr->child[n] == NULL){curr->child[n] = new TrieNode();} curr = curr->child[n]; } curr->isEnd = true; }
bool searchTrie(string& s){TrieNode* curr = rootTrie;for(int i = 0; i<s.length(); i++){int n = s[i] - 'a';if(!curr->child[n]) return false;curr = curr->child[n];}return curr->isEnd;}
bool startsWithTrie(string s) {int n = s.length();TrieNode* curr = rootTrie;for(int i =0 ; i<n; i++){int k = s[i] - 'a';if(curr->child[k] == NULL) return false;curr = curr->child[k];}return true;}
bool isEmpty(TrieNode* rootTrie){ for (int i = 0; i < ALPHABET_SIZE; i++){if(rootTrie->child[i])return false;}return true;}
void remove(TrieNode* rootTrie, string key, int depth = 0){if (!rootTrie)return NULL;if (depth == key.size()) {if (rootTrie->isEnd)rootTrie->isEnd = false;if (isEmpty(rootTrie)) {delete (rootTrie);rootTrie = NULL;}return rootTrie;}int index = key[depth] - 'a';rootTrie->child[index] = remove(rootTrie->child[index], key, depth + 1);if (isEmpty(rootTrie) && rootTrie->isEnd == false) {delete (rootTrie);rootTrie = NULL;}return rootTrie;}
int main(){
//Jai Shree Ram
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string keys[] = { "the", "a", "there", "answer", "any", "by", "bye", "their", "hero", "heroplane" };
int n = sizeof(keys) / sizeof(keys[0]);
for (int i = 0; i < n; i++)
insert(rootTrie, keys[i]);
search(rootTrie, "the") ? cout << "Yes\n" : cout << "No\n";
search(rootTrie, "these") ? cout << "Yes\n" : cout << "No\n";
remove(rootTrie, "heroplane");
search(rootTrie, "hero") ? cout << "Yes\n" : cout << "No\n";
return 0;
}

View File

@ -0,0 +1,44 @@
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 1e9;
#define inf2 2e18;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31);}
size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); }
};
struct TrieNode{ TrieNode* child[26]; bool isEnd;
TrieNode(){ isEnd = false; for(int i = 0; i<26; i++){ child[i] = NULL; } }
};
struct TrieNode* rootTrie;
void addTrie(string& s){ TrieNode* curr = rootTrie; for(int i = 0; i<s.length(); i++){ int n = s[i] - 'a';if(curr->child[n] == NULL){curr->child[n] = new TrieNode();} curr = curr->child[n]; } curr->isEnd = true; }
bool searchTrie(string& s){TrieNode* curr = rootTrie;for(int i = 0; i<s.length(); i++){int n = s[i] - 'a';if(!curr->child[n]) return false;curr = curr->child[n];}return curr->isEnd;}
bool startsWithTrie(string s) {int n = s.length();TrieNode* curr = rootTrie;for(int i =0 ; i<n; i++){int k = s[i] - 'a';if(curr->child[k] == NULL) return false;curr = curr->child[k];}return true;}
int main(){
//Jai Shree Ram
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string keys[] = {"the", "a", "there", "answer", "any", "by", "bye", "their" };
int n = sizeof(keys)/sizeof(keys[0]);
struct TrieNode *root = getNode();
for (int i = 0; i < n; i++) insert(root, keys[i]);
char output[][32] = {"Not present in trie", "Present in trie"};
cout<<"the"<<" --- "<<output[search(root, "the")]<<endl;
cout<<"these"<<" --- "<<output[search(root, "these")]<<endl;
cout<<"their"<<" --- "<<output[search(root, "their")]<<endl;
cout<<"thaw"<<" --- "<<output[search(root, "thaw")]<<endl;
return 0;
}

View File

@ -18,8 +18,10 @@
- [Dijkstras](graphs/Dijkstras.java) - [Dijkstras](graphs/Dijkstras.java)
- [Prims](graphs/Prims.java) - [Prims](graphs/Prims.java)
## Linked Lists ## Linked Lists
- [Circular Singly Linked List](linked-lists/circular-singly-linkedlist.java)
- [Circular](linked-lists/circular.java) - [Circular](linked-lists/circular.java)
- [Clone Linked List](linked-lists/clone-linkedlist.java) - [Clone Linked List](linked-lists/clone-linkedlist.java)
- [Doubly](linked-lists/doubly.java) - [Doubly](linked-lists/doubly.java)

View File

@ -0,0 +1,119 @@
class circularll {
Node head;
Node tail;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
//add() function add element to the rear of the linkedlist
public void add(int data){
Node newNode = new Node(data);
if(head==null){
head=tail=newNode;
}
else{
tail.next=newNode;
tail=tail.next;
}
tail.next=head;
}
//display() function to show elements of linkedlist
public void display(){
System.out.printf("\nThe Linkedlist is ");
Node temp=head;
do{
System.out.print(temp.data+" ");
temp=temp.next;
}while (temp!=head);
}
//search() function searches the element in the linkedlist
public void search(int target){
int flag=0;
Node temp=head;
do{
if(target==temp.data){
System.out.print("\nTarget is found");
flag=1;
break;
}
temp=temp.next;
}while (temp!=head);
if (flag==0)
System.out.print("\nTarget Not Found");
}
// addfront() function added a element to the front of the circular singly linkedlist
public void addfront(int data){
Node newNode = new Node(data);
newNode.next=head;
head=newNode;
tail.next=head;
}
//reverse() function is reversing the circular singly linkedlist
public void reverse(){
Node previous=tail;
Node current=head,nextnode = head;
do{
nextnode=current.next;
current.next=previous;
previous=current;
current=nextnode;
}while(current!=head);
tail=head;
head=previous;
tail.next=head;
}
public static void main(String[] args) {
System.out.println("LinkedList");
circularll ll = new circularll();
ll.add(5);
ll.add(8);
ll.add(7);
ll.add(1);
ll.add(2);
ll.display();
ll.addfront(9);
ll.display();
ll.search(2);
ll.search(4);
ll.reverse();
ll.display();
}
}
/*
OUTPUT:
LinkedList
The Linkedlist is 5 8 7 1 2
The Linkedlist is 9 5 8 7 1 2
Target is found
Target Not Found
The Linkedlist is 2 1 7 8 5 9
*/
// Here initial linkedlist was 9 5 8 7 1 2 and after using reverse function the linkedlist become 2 1 7 8 5 9

View File

@ -7,6 +7,7 @@
- [Missing Number](arrays/missing_number.py) - [Missing Number](arrays/missing_number.py)
- [Remove duplicate items](arrays/remove_duplicates_list.py) - [Remove duplicate items](arrays/remove_duplicates_list.py)
- [Dutch National Flag Algorithm](arrays/dutch_national_flag_algo.py) - [Dutch National Flag Algorithm](arrays/dutch_national_flag_algo.py)
- [Max Sub Array Sum](arrays/max_sub_array_sum.py)
## Linked Lists ## Linked Lists
- [Doubly](linked_lists/doubly.py) - [Doubly](linked_lists/doubly.py)

View File

@ -0,0 +1,32 @@
"""
Algorithm Name: Max Sum of Sub Array
Time Complexity: O(n)
Explanation: arr = [3, 2, -4, 9]
at the start of the algorithm
assign current sum (max_sum_curr) = max sum(max_sum) = arr[0]
(for) iterate from arr[1] to arr[n] and do
max_sum_curr = arr[i] if arr[i] > arr[i] + max_sum_curr
else
max_sum_curr = max_sum_curr + arr[i]
max_sum = max_sum if max_sum > max_sum_curr
else
max_sum = max_sum_curr
end
return max_sum
"""
def max_sub_arr_sum(arr):
arr_size = len(arr)
max_sum = arr[0]
max_sum_curr = arr[0]
for i in range(1, arr_size):
max_sum_curr = max(arr[i], max_sum_curr + arr[i])
max_sum = max(max_sum, max_sum_curr)
return max_sum
# print("Enter array of numbers (Ex: 1 2 3 4 for [1, 2, 3, 4])")
arr = [3, 2, -4, 9] # list(map(int, input().split()))
print("Maximum Sub Array Sum is", max_sub_arr_sum(arr))

View File

@ -1,11 +1,17 @@
# Algorithms # Algorithms
## Backtracking
- [N-Queens](./Backtracking/N-Queens.md)
## Lists ## Lists
- [Singly linked list](./Lists/singly-linked-list.md) - [Singly linked list](./Lists/singly-linked-list.md)
- [Doubly linked list](./Lists/doubly-linked-list.md) - [Doubly linked list](./Lists/doubly-linked-list.md)
## Sorting ## Searching
- [Binary Search](./Searching/Binary-Search.MD)
- [Linear Search](./Searching/Linear-Search.md)
## Sorting
- [Bubble Sort](./Sorting/Bubble-Sort.md) - [Bubble Sort](./Sorting/Bubble-Sort.md)
- [Merge Sort](./Sorting/Merge-Sort.md) - [Merge Sort](./Sorting/Merge-Sort.md)
- [Selection Sort](./Sorting/Selection-Sort.md) - [Selection Sort](./Sorting/Selection-Sort.md)
@ -13,16 +19,13 @@
- [Heap Sort](./Sorting/Heap-Sort.md) - [Heap Sort](./Sorting/Heap-Sort.md)
- [Quick Sort](./Sorting/Quick-Sort.md) - [Quick Sort](./Sorting/Quick-Sort.md)
- [Cycle Sort](./Sorting/Cycle-Sort.md) - [Cycle Sort](./Sorting/Cycle-Sort.md)
- [Radix Sort](./Sorting/Radix-Sort.md)
## Strings ## Strings
- [Palindrome](./Strings/Palindrome.md) - [Palindrome](./Strings/Palindrome.md)
## Searching ## Tree
- [Min Heap](./Tree/min-heap.md)
- [Binary Search](./Searching/Binary-Search.MD)
- [Linear Search](./Searching/Linear-Search.md)
## Others ## Others
[How to add new algorithm documentation?](./CONTRIBUTING.md) [How to add new algorithm documentation?](./CONTRIBUTING.md)