From db1fcd13424ffd0c05c6884fa20aa255c636a10b Mon Sep 17 00:00:00 2001 From: Rishabh <53911515+Rishabh672003@users.noreply.github.com> Date: Sat, 23 Dec 2023 23:37:53 +0530 Subject: [PATCH] website stuff --- .gitignore | 2 +- .../Binary-Search/Easy/01-binary-search.md | 123 ------ .../Easy/02-lower&upper-bound.md | 121 ------ .../Easy/03-search-insert-position.md | 76 ---- .../Easy/04-floor&ceil-in-array.md | 90 ---- .../Easy/05-first-and-last-ocurrence.md | 70 ---- .../Easy/06-number-of-occurrence.md | 73 ---- ...7-search-in-rotated-sorted-unique-array.md | 226 ---------- ...earch-in-rotated-sorted-duplicate-array.md | 113 ----- .../Easy/09-minimum-in-sorted-rotated.md | 36 -- .../Easy/10-single-in-sorted-rotated.md | 63 --- .../Easy/11-find-peak-in-array.md | 55 --- .../Medium/koko-eating-bananas.md | 116 ------ .../Searching-Algorithms/linear-search.md | 50 --- Algorithms/Sliding-Window/01-intro.md | 57 --- Algorithms/Sliding-Window/02-problem-1.md | 114 ----- Algorithms/Sliding-Window/03-problem-2.md | 99 ----- Algorithms/Sorting-Algorithms/bubble-sort.md | 49 --- .../Sorting-Algorithms/selection-sort.md | 78 ---- Algorithms/time-complexity.md | 100 ----- Data-Structures/Hash-Maps/01-maps-intro.md | 79 ---- Data-Structures/Hash-Maps/02-map-methods.md | 62 --- .../Hash-Maps/03-number-of-occurrences.md | 94 ----- .../Hash-Maps/04-max-occurrence.md | 58 --- .../Linear-Data-Structures/02-strings.md | 204 --------- .../Linear-Data-Structures/03-vectors.md | 109 ----- .../Linear-Data-Structures/04-stacks.md | 203 --------- .../Linear-Data-Structures/05-queues.md | 275 ------------ .../Linear-Data-Structures/Array/01-arrays.md | 392 ------------------ .../Array/02-second-largest.md | 88 ---- .../Linked-List/01-linked-list.md | 63 --- .../Linked-List/02-node-creation.md | 33 -- .../Linked-List/03-traversal.md | 27 -- .../Linked-List/04-insertion.md | 138 ------ .../Linked-List/reverseLinkedList.md | 50 --- .../Linked-List/temp.cpp | 88 ---- .../Linked-List/temp2.cpp | 25 -- Data-Structures/Trees/01-intro.md | 33 -- Data-Structures/Trees/02-basics.md | 39 -- Data-Structures/Trees/03-travsersals.md | 66 --- Data-Structures/Trees/04-in-order-recur.md | 26 -- Data-Structures/Trees/05-pre-order-recur.md | 26 -- Data-Structures/Trees/06-post-order-recur.md | 26 -- Data-Structures/Trees/07-level-order.md | 152 ------- .../Trees/08-in-order-iterative.md | 113 ----- .../Trees/09-pre-order-iterative.md | 55 --- .../Trees/10-post-order-twoStack.md | 65 --- .../Trees/11-post-order-oneStack.md | 49 --- .../Trees/problems/check-for-balanced-bt.cpp | 57 --- .../Trees/problems/count-leaves.cpp | 41 -- .../Trees/problems/depth-of-bt.cpp | 54 --- .../Trees/problems/diameter-of-bt.cpp | 54 --- .../Trees/problems/sum-of-left-leaves.cpp | 45 -- .../Trees/problems/symmetric-bt.cpp | 49 --- Data-Structures/stl-reference.md | 14 - JavaScript/01-intro.md | 96 ----- JavaScript/02-basics.md | 79 ---- JavaScript/03-operators.md | 36 -- JavaScript/04-variables.md | 156 ------- JavaScript/05-array-methods.md | 366 ---------------- JavaScript/Asynchronous JS/async-await.md | 82 ---- JavaScript/Asynchronous JS/callBack.md | 69 --- JavaScript/Asynchronous JS/multiHandlers.md | 25 -- JavaScript/Asynchronous JS/promiChain.md | 93 ----- JavaScript/Asynchronous JS/promise-1.md | 81 ---- JavaScript/Asynchronous JS/promise-2.md | 66 --- JavaScript/Asynchronous JS/sync-vs-async.md | 35 -- JavaScript/Asynchronous JS/then-catch.md | 54 --- OOP/OOP-intro.md | 52 --- OOP/abstraction.md | 10 - OOP/classes-objects-intro.md | 121 ------ OOP/encapsulation.md | 117 ------ OOP/inheritence.md | 126 ------ OOP/polymorphism.md | 110 ----- .../01-typescript-basics.md | 120 ------ .../Learn-What-Matters/02-the-tsconfig.md | 36 -- TypeScript/Learn-What-Matters/03-functions.md | 163 -------- TypeScript/Learn-What-Matters/04-arrays.md | 116 ------ .../Learn-What-Matters/05-custom-types.md | 201 --------- .../TypeScript-For-React/01-useState.md | 45 -- .../TypeScript-For-React/02-dataFromAPI.md | 94 ----- .../TypeScript-For-React/03-eventListners.md | 44 -- book.toml | 6 + {CPP => src}/01-intro.md | 0 {CPP => src}/02-c-vs-cpp.md | 0 src/02-intro.md | 1 + {CPP => src}/03-basics.md | 0 {CPP => src}/04-loops.md | 0 {CPP => src}/05-bitwise-operators.md | 0 {CPP => src}/06-operators.md | 0 {CPP => src}/07-functions.md | 0 {CPP => src}/08-lambda-function.md | 0 {CPP => src}/09-data-types.md | 0 {CPP => src}/10-static-typing.md | 0 {CPP => src}/11-dynamic-typing.md | 0 {CPP => src}/12-pointers-references.md | 0 {CPP => src}/13-memory-model.md | 0 {CPP => src}/14-raw-ptr.md | 0 {CPP => src}/15-memory-leakage.md | 0 {CPP => src}/16-unique-ptr.md | 0 {CPP => src}/17-shared-ptr.md | 0 {CPP => src}/18-structuring-codebase.md | 0 {CPP => src}/19-scope.md | 0 {CPP => src}/20-namespace.md | 0 {CPP => src}/20.1-dont-use-namesapce-std.md | 0 {CPP => src}/21-code-splitting.md | 0 {CPP => src}/22-forward-declaration.md | 0 {CPP => src}/23-structs-classes.md | 0 {CPP => src}/24-OOP.md | 0 {CPP => src}/25-OOP-example.md | 0 {CPP => src}/26-multiple-inheritance.md | 0 {CPP => src}/26.1-diamond-inheritance.md | 0 {CPP => src}/27-static-polymorphism.md | 0 {CPP => src}/28-dynamic-polymorphism.md | 0 {CPP => src}/28.1-virtual-methods.md | 0 {CPP => src}/28.2-virtual-tables.md | 0 {CPP => src}/29-exception-handling.md | 0 {CPP => src}/29.1-try-catch-throw.md | 0 {CPP => src}/30-exit-codes.md | 0 {CPP => src}/31-access-violations.md | 0 src/32-type-casting.md | 78 ++++ src/33-standard-template-library.md | 71 ++++ src/34-templates.md | 84 ++++ src/SUMMARY.md | 41 ++ 124 files changed, 282 insertions(+), 7255 deletions(-) delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/01-binary-search.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/02-lower&upper-bound.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/03-search-insert-position.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/04-floor&ceil-in-array.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/05-first-and-last-ocurrence.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/06-number-of-occurrence.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/07-search-in-rotated-sorted-unique-array.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/08-search-in-rotated-sorted-duplicate-array.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/09-minimum-in-sorted-rotated.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/10-single-in-sorted-rotated.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Easy/11-find-peak-in-array.md delete mode 100644 Algorithms/Searching-Algorithms/Binary-Search/Medium/koko-eating-bananas.md delete mode 100644 Algorithms/Searching-Algorithms/linear-search.md delete mode 100644 Algorithms/Sliding-Window/01-intro.md delete mode 100644 Algorithms/Sliding-Window/02-problem-1.md delete mode 100644 Algorithms/Sliding-Window/03-problem-2.md delete mode 100644 Algorithms/Sorting-Algorithms/bubble-sort.md delete mode 100644 Algorithms/Sorting-Algorithms/selection-sort.md delete mode 100644 Algorithms/time-complexity.md delete mode 100644 Data-Structures/Hash-Maps/01-maps-intro.md delete mode 100644 Data-Structures/Hash-Maps/02-map-methods.md delete mode 100644 Data-Structures/Hash-Maps/03-number-of-occurrences.md delete mode 100644 Data-Structures/Hash-Maps/04-max-occurrence.md delete mode 100644 Data-Structures/Linear-Data-Structures/02-strings.md delete mode 100644 Data-Structures/Linear-Data-Structures/03-vectors.md delete mode 100644 Data-Structures/Linear-Data-Structures/04-stacks.md delete mode 100644 Data-Structures/Linear-Data-Structures/05-queues.md delete mode 100644 Data-Structures/Linear-Data-Structures/Array/01-arrays.md delete mode 100644 Data-Structures/Linear-Data-Structures/Array/02-second-largest.md delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/01-linked-list.md delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/02-node-creation.md delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/03-traversal.md delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/04-insertion.md delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/reverseLinkedList.md delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/temp.cpp delete mode 100644 Data-Structures/Linear-Data-Structures/Linked-List/temp2.cpp delete mode 100644 Data-Structures/Trees/01-intro.md delete mode 100644 Data-Structures/Trees/02-basics.md delete mode 100644 Data-Structures/Trees/03-travsersals.md delete mode 100644 Data-Structures/Trees/04-in-order-recur.md delete mode 100644 Data-Structures/Trees/05-pre-order-recur.md delete mode 100644 Data-Structures/Trees/06-post-order-recur.md delete mode 100644 Data-Structures/Trees/07-level-order.md delete mode 100644 Data-Structures/Trees/08-in-order-iterative.md delete mode 100644 Data-Structures/Trees/09-pre-order-iterative.md delete mode 100644 Data-Structures/Trees/10-post-order-twoStack.md delete mode 100644 Data-Structures/Trees/11-post-order-oneStack.md delete mode 100644 Data-Structures/Trees/problems/check-for-balanced-bt.cpp delete mode 100644 Data-Structures/Trees/problems/count-leaves.cpp delete mode 100644 Data-Structures/Trees/problems/depth-of-bt.cpp delete mode 100644 Data-Structures/Trees/problems/diameter-of-bt.cpp delete mode 100644 Data-Structures/Trees/problems/sum-of-left-leaves.cpp delete mode 100644 Data-Structures/Trees/problems/symmetric-bt.cpp delete mode 100644 Data-Structures/stl-reference.md delete mode 100644 JavaScript/01-intro.md delete mode 100644 JavaScript/02-basics.md delete mode 100644 JavaScript/03-operators.md delete mode 100644 JavaScript/04-variables.md delete mode 100644 JavaScript/05-array-methods.md delete mode 100644 JavaScript/Asynchronous JS/async-await.md delete mode 100644 JavaScript/Asynchronous JS/callBack.md delete mode 100644 JavaScript/Asynchronous JS/multiHandlers.md delete mode 100644 JavaScript/Asynchronous JS/promiChain.md delete mode 100644 JavaScript/Asynchronous JS/promise-1.md delete mode 100644 JavaScript/Asynchronous JS/promise-2.md delete mode 100644 JavaScript/Asynchronous JS/sync-vs-async.md delete mode 100644 JavaScript/Asynchronous JS/then-catch.md delete mode 100644 OOP/OOP-intro.md delete mode 100644 OOP/abstraction.md delete mode 100644 OOP/classes-objects-intro.md delete mode 100644 OOP/encapsulation.md delete mode 100644 OOP/inheritence.md delete mode 100644 OOP/polymorphism.md delete mode 100644 TypeScript/Learn-What-Matters/01-typescript-basics.md delete mode 100644 TypeScript/Learn-What-Matters/02-the-tsconfig.md delete mode 100644 TypeScript/Learn-What-Matters/03-functions.md delete mode 100644 TypeScript/Learn-What-Matters/04-arrays.md delete mode 100644 TypeScript/Learn-What-Matters/05-custom-types.md delete mode 100644 TypeScript/TypeScript-For-React/01-useState.md delete mode 100644 TypeScript/TypeScript-For-React/02-dataFromAPI.md delete mode 100644 TypeScript/TypeScript-For-React/03-eventListners.md create mode 100644 book.toml rename {CPP => src}/01-intro.md (100%) rename {CPP => src}/02-c-vs-cpp.md (100%) create mode 100644 src/02-intro.md rename {CPP => src}/03-basics.md (100%) rename {CPP => src}/04-loops.md (100%) rename {CPP => src}/05-bitwise-operators.md (100%) rename {CPP => src}/06-operators.md (100%) rename {CPP => src}/07-functions.md (100%) rename {CPP => src}/08-lambda-function.md (100%) rename {CPP => src}/09-data-types.md (100%) rename {CPP => src}/10-static-typing.md (100%) rename {CPP => src}/11-dynamic-typing.md (100%) rename {CPP => src}/12-pointers-references.md (100%) rename {CPP => src}/13-memory-model.md (100%) rename {CPP => src}/14-raw-ptr.md (100%) rename {CPP => src}/15-memory-leakage.md (100%) rename {CPP => src}/16-unique-ptr.md (100%) rename {CPP => src}/17-shared-ptr.md (100%) rename {CPP => src}/18-structuring-codebase.md (100%) rename {CPP => src}/19-scope.md (100%) rename {CPP => src}/20-namespace.md (100%) rename {CPP => src}/20.1-dont-use-namesapce-std.md (100%) rename {CPP => src}/21-code-splitting.md (100%) rename {CPP => src}/22-forward-declaration.md (100%) rename {CPP => src}/23-structs-classes.md (100%) rename {CPP => src}/24-OOP.md (100%) rename {CPP => src}/25-OOP-example.md (100%) rename {CPP => src}/26-multiple-inheritance.md (100%) rename {CPP => src}/26.1-diamond-inheritance.md (100%) rename {CPP => src}/27-static-polymorphism.md (100%) rename {CPP => src}/28-dynamic-polymorphism.md (100%) rename {CPP => src}/28.1-virtual-methods.md (100%) rename {CPP => src}/28.2-virtual-tables.md (100%) rename {CPP => src}/29-exception-handling.md (100%) rename {CPP => src}/29.1-try-catch-throw.md (100%) rename {CPP => src}/30-exit-codes.md (100%) rename {CPP => src}/31-access-violations.md (100%) create mode 100644 src/32-type-casting.md create mode 100644 src/33-standard-template-library.md create mode 100644 src/34-templates.md create mode 100644 src/SUMMARY.md diff --git a/.gitignore b/.gitignore index b65db94..7585238 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -Example-Code/*.out +book diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/01-binary-search.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/01-binary-search.md deleted file mode 100644 index 6d3042d..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/01-binary-search.md +++ /dev/null @@ -1,123 +0,0 @@ -# Binary Search. - -_Search Element in a Linear **Sorted** Data Structure._ - -**Time Complexity:** - -1. Best Case: O(1) --> Element at middle of the array. -2. Average / Worst Case: O(log n) --> Element at 1st or last position. - -## Logic. - -1. Find Mid --> mid = start + (end - start) / 2. -2. Compare mid with target --> possible comparisons (mid == target) or (mid > target) or (mid < target). -3. If mid == target, return mid. -4. If mid != target, change path w.r.t (mid > target) or (mid < target) -5. If mid > target, start --> same, end --> mid - 1. -6. If mid < target, end --> same, start --> mid + 1. -7. Repeat. - -## Implementation 1 - Iterative Approach - -```cpp -#include -using namespace std; - -int binarySearch(int *arr, int size, int target) { - int start = 0; - int end = size - 1; - int mid = start + (end - start) / 2; - while (start <= end) - { - if (arr[mid] == target) - return mid; - if (arr[mid] > target) - end = mid - 1; - else - start = mid + 1; - mid = start + (end - start) / 2; - } - return -1; -} - -int main() { - int arr[5] = {1, 2, 3, 4, 5}; - int index = binarySearch(arr, 5, 3); - if (index == -1) - cout << "NOT FOUND!"; - else - cout << "Element found at Index " << index; - return 0; -} - -``` - ---- - -## Implementation 2 - Recursive Approach - -```cpp -#include -using namespace std; - -int binarySearch(vector&arr, int low, int high, int target) { - - // base case - if (low > high) return -1; - - // calculate mid - int mid = low + (high - low) / 2; - - // if found, return mid index - if (arr[mid] == target) return mid; - - // if target > arr[mid], call the binarySearch function with updated low index. - else if (target > arr[mid]) return binarySearch(arr, mid+1, high, target); - - // else when target < arr[mid], call the binarySearch function with updated high index. - return binarySearch(arr, low, mid-1, target); -} - -int search(vector&nums, int target){ - return binarySearch(nums, 0, nums.size() - 1, target); -} - -int main() { - int vectorarr = {1, 2, 3, 4, 5}; - int index = search(arr, 5, 3); - if (index == -1) - cout << "NOT FOUND!"; - else - cout << "Element found at Index " << index; - return 0; -} - -``` - -## Linear Search v/s Binary Search. - -In Linear search, for the worst case, if the size of array is 1000, then the function will perform 1000 comparisons. -In Binary Search, for worst case, for 1000 size array, the function will perform log2(1000) = 10 comparisons, -which is 100 times less than Linear Search. - -## How O(log n) ? - -Suppose a N sized array perform binary search, then the middle element will be at N/21 position where 1 represents 1st comparison. - -The next mid will be at N/22 Position where 2 represents 2nd comparison. - -Similarly at last comparison, N/2k , the mid = size of array i.e, 1. - -Therefore N/2k = 1 - -N = 2k - -Log2N = K - -Which means, at kth comparison, the size of array will be log2N - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/binary-search_972?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & [LeetCode](https://leetcode.com/problems/binary-search/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/02-lower&upper-bound.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/02-lower&upper-bound.md deleted file mode 100644 index e6e35d1..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/02-lower&upper-bound.md +++ /dev/null @@ -1,121 +0,0 @@ -## Find Lower and Upper bound in an array. - -### Lower Bound : - -If we have a sorted array `arr` and a target element `x` which is supposed to be found in that array, then a Lower bound is the **Smallest** `index` in that array such that, - -```cpp -arr[index] >= x; -``` - ---- - -**Example :** - -```cpp -int arr[6] = {1, 2, 4, 4, 5, 7}; -int x = 4; // element to be found in array -``` - -If we iterate over the array, we can find that 4 >= 4, 4 >= 4, 5 >= 4 and 7 >= 4. But the first occurence of 4 at index 2 satisfies the condition as it is `>=` the target element and it's index is the smallest of all. - -**Hence, The Lower bound of this array is 2.** - ---- - -### Upper Bound : - -If we have a sorted array `arr` and a target element `x` which is supposed to be found in that array, then an Upper bound is the **Smallest** `index` in that array such that, - -```cpp -arr[index] > x; // note the sign here -``` - ---- - -**Example :** - -```cpp -int arr[6] = {1, 2, 4, 4, 5, 7}; -int x = 4; // element to be found in array -``` - -If we iterate over the array, we can find that 5 > 4 and 7 > 4. But the value 5 at index 4 satisfies the condition as it is `>` the target element and it's index is the smallest of all. - -**Hence, The upper bound of this array is 4.** - ---- - -**Note :** There could be an edge case where no such target element exists or which satisfies `arr[index] >= target` or `arr[index] > target`, then we will return the nth element of the array because, then it would the hypothetical lower or upper bound for that array. - -**Example :** - -```cpp -int arr[6] = {1, 2, 4, 4, 5, 7}; -int x = 7; -/* -this x value would have upper bound == 6, -as no element is > than 7 -*/ -``` - ---- - -**Implementation :** - -```cpp -#include -using namespace std; - -int lowerBound(vector &arr, int n, int x){ - int low = 0, high = n - 1; - int ans = n; - while (low <= high){ - int mid = low + (high - low) / 2; - // maybe answer - if (arr[mid] >= x){ - ans = mid; - // look for more small index in left - high = mid - 1; - } else { - low = mid + 1; // look for right - } - } - return ans; -} - -int upperBound(vector &arr, int n, int x){ - int low = 0, high = n - 1; - int ans = n; - while (low <= high){ - int mid = low + (high - low) / 2; - // maybe answer - if (arr[mid] > x){ - ans = mid; - // look for more small index in left - high = mid - 1; - } else { - low = mid + 1; // look for right - } - } - return ans; -} - -int main(){ - int n; cin >> n; - int arr[n]; - for (int i = 0; i < n; i++>){ - cin >> arr[i]; - } - int x; cin >> x; - cout << "Lower Bound : " << lowerBound(arr, n, x); - cout << "Upper Bound : " << upperBound(arr, n, x); - return 0; -} -``` - ---- - -**Solve it on :** - -[Coding Ninjas - Lower Bound](https://www.codingninjas.com/studio/problems/lower-bound_8165382?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & [Upper Bound](https://www.codingninjas.com/studio/problems/implement-upper-bound_8165383?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/03-search-insert-position.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/03-search-insert-position.md deleted file mode 100644 index 1723458..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/03-search-insert-position.md +++ /dev/null @@ -1,76 +0,0 @@ -## Search Insert Position - -You're given a sorted array `arr` of distinct values and a target value `m`. Search for the index of the target value in array. - ---- - -**Note :** - -- If the value is present in the array, return its index. - -- If the value is absent, determine the index where it would be inserted in the array while **maintaining the sorted order.** - -- Consider 0-based indexing only. - ---- - -**Example :** - -``` -int arr[5] = {1, 2, 3, 5, 7}; -m = 6; - -Output : 3 - -Explanation : In the given array, the target 6 is not available so we can insert m = 6 at index 3 to maintain sorted order. -``` - ---- - -**Implementation :** - -```cpp -#include -using namespace std; - -int searchInsert(vector& arr, int m) { - int n = arr.size(); - int low = 0, high = n - 1; - int ans = n; - while (low <= high) { - int mid = low + (high - low) / 2; - if (arr[mid] >= m) { - ans = mid; - high = mid - 1; - } else { - low = mid + 1; - } - } - return ans; -} - -int main() { - vector arr = {1, 3, 5, 6, 8, 9}; - int m = 7; - cout << searchInsert(arr, m) << endl; - return 0; -} -``` - -``` -Output : 4 - -Explanation : 7 isn't present in the array so 4 will be the index where 7 would be inserted so as to maintain sorted order. -``` - ---- - -**Refer :** -[Lower Bound](./02-lower&upper-bound.md), [Binary Search](./01-binary-search.md). - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/algorithm-to-find-best-insert-position-in-sorted-array_839813?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/04-floor&ceil-in-array.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/04-floor&ceil-in-array.md deleted file mode 100644 index b85e848..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/04-floor&ceil-in-array.md +++ /dev/null @@ -1,90 +0,0 @@ -## Floor and Ceil in array. - -**Floor : _Largest_ element in array which is <= x.** - -**Ceil : _Smallest_ element in array which is >= x.** - ---- - -**Example :** - -``` -int arr[5] = {10, 20, 30, 40, 50}; -int x = 25 - -here, floor --> 20 and ceil --> 30 - -Explanation : -floor : 10 <= 25, 20 <= 25 but 20 > 10, so 20. -ceil : 30 >= 25, 40 >= 25, 50 >= 25 but 40 > 30 < 50, so 30. -``` - -**Note :** If the element exists in the array then the **element itself** is floor and ceil. - ---- - -**Implementation :** - -```cpp -int findFloor(vector& arr, int x){ - int n = arr.size(); - int low = 0, high = n - 1; - int ans = -1; - while (low <= high){ - int mid = low + (high - low) / 2; - if (arr[mid] <= x){ - ans = arr[mid]; // maybe an answer - low = mid + 1; - // eleminate the left search space as we want to find the 'largest' element. - } else { - high = mid - 1; - } - } - return ans; -} - -int findCeil(vector& arr, int x){ - int n = arr.size(); - int low = 0, high = n - 1; - int ans = -1; - while (low <= high){ - int mid = low + (high - low) / 2; - if (arr[mid] >= x){ - ans = arr[mid]; // maybe an answer - high = mid - 1; - // eleminate the right search space as we want to find the 'smallest' element. - } else { - low = mid + 1; - } - } - return ans; -} - -int main() { - vector arr = {1, 3, 5, 6, 8, 9}; - int x = 7; - int floor = findFloor(arr, x); - int ceil = findCeil(arr, x); - cout << "The floor of " << x << " is " << floor << endl; - cout << "The ceil of " << x << " is " << ceil << endl; - return 0; -} - -``` - -``` -output : -The floor of 7 is 6 -The ceil of 7 is 7 -``` - ---- - -**Refer :** -[Lower Bound](./02-lower&upper-bound.md), [Binary Search](./01-binary-search.md). - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/ceiling-in-a-sorted-array_1825401?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/05-first-and-last-ocurrence.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/05-first-and-last-ocurrence.md deleted file mode 100644 index 9ae99c6..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/05-first-and-last-ocurrence.md +++ /dev/null @@ -1,70 +0,0 @@ -## First and Last occurrence of an element. - -### First occurrence --> Lower Bound. - -### Last occurrence --> Upper bound - 1. - ---- - -**Implementation :** - -```cpp -int lowerBound(vector &arr, int n, int x){ - int low = 0, high = n - 1; - int ans = n; - while (low <= high){ - int mid = low + (high - low) / 2; - if (arr[mid] >= x){ - ans = mid; - high = mid - 1; - } else { - low = mid + 1; - } - } - return ans; -} - -int upperBound(vector &arr, int n, int x){ - int low = 0, high = n - 1; - int ans = n; - while (low <= high){ - int mid = low + (high - low) / 2; - // maybe answer - if (arr[mid] > x){ - ans = mid; - // look for more small index in left - high = mid - 1; - } else { - low = mid + 1; // look for right - } - } - return ans; -} - -pair firstAndLastPosition(vector& arr, int n, int k) -{ - int lb = lowerBound(arr, n, k); - if (lb == n || arr[lb] != k) return {-1, -1}; - return {lb, upperBound(arr, n, k) - 1}; -} - -int main() { - vector arr = {1, 3, 5, 5, 5, 5, 7, 8, 9}; - int k = 5; - pair result = firstAndLastPosition(arr, arr.size(), k); - cout << "The first and last position of " << k << " in the array are " << result.first << " and " << result.second << endl; - return 0; -} -``` - -``` -Output : -The first and last position of 5 in the array are 2 and 5 -``` - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/first-and-last-position-of-an-element-in-sorted-array_1082549?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/06-number-of-occurrence.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/06-number-of-occurrence.md deleted file mode 100644 index bbfcc25..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/06-number-of-occurrence.md +++ /dev/null @@ -1,73 +0,0 @@ -## Number of Occurrence of element in an array. - -### Number of occurrence = last occurrence - first occurrence + 1 - ---- - -**Implementation :** - -```cpp -#include -using namespace std; - -int lowerBound(vector& arr, int n, int x) { - int low = 0, high = n - 1; - int ans = n; - while (low <= high) { - int mid = low + (high - low) / 2; - if (arr[mid] >= x) { - ans = mid; - high = mid - 1; - } else { - low = mid + 1; - } - } - return ans; -} - -int upperBound(vector& arr, int n, int x) { - int low = 0, high = n - 1; - int ans = n; - while (low <= high) { - int mid = low + (high - low) / 2; - if (arr[mid] > x) { - ans = mid; - high = mid - 1; - } else { - low = mid + 1; - } - } - return ans; -} - -pair firstAndLastPosition(vector& arr, int n, int k) { - int lb = lowerBound(arr, n, k); - if (lb == n || arr[lb] != k) return {-1, -1}; - return {lb, upperBound(arr, n, k) - 1}; -} - -int count(vector& arr, int n, int x) { - pair ans = firstAndLastPosition(arr, n, x); - if (ans.first == -1) return 0; - return ans.second - ans.first + 1; -} - -int main() { - vector arr = {1, 3, 5, 5, 5, 5, 7, 8, 9}; - int x = 5; - int count = count(arr, arr.size(), x); - cout << "The number of occurrences of " << x << " in the array is " << count << endl; - return 0; -} -``` - -``` -Output : -The number of occurrences of 5 in the array is 4 -``` - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/occurrence-of-x-in-a-sorted-array_630456?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/07-search-in-rotated-sorted-unique-array.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/07-search-in-rotated-sorted-unique-array.md deleted file mode 100644 index 8d093de..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/07-search-in-rotated-sorted-unique-array.md +++ /dev/null @@ -1,226 +0,0 @@ -## Search in Rotated Sorted Array of Unique Elements. - -**Problem statement :** You're given an array of **unique** elements which is rotated and sorted about a pivot, search for an element in that array. - ---- - -This problem could be solved using a **linear search** with a time complexity of **O(N)**, but to make it more efficient, we'll use **Binary Search** to solve it efficiently in **O(log N)**. - ---- - -```cpp -int sorted_rotated_array[9] = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - -// the above array is rotated about 2nd index. -``` - ---- - -To find an element in above array, we couldn't directly proceed with generic binary search. - -Because, let's say you've to search for 9 in the array. The first thing we do is to calculate the mid and compare it with target value. - -Here mid is 2 and when we compare it with target 9 to eleminate some search space, we found that 2 < 9 but 9 in this array despite being in right search space, is now in the left search space. - -So if we procced with normal binary search then we'll eleminate the incorrect half of the array and hence, could have never found the target. - ---- - -### Steps to solve this problem : - -To solve this type of problem, we'll always try to first find out the sorted half of the array because as you can observe in `{7, 8, 9, 1, 2, 3, 4, 5, 6}`, the right half from the mid is sorted `{2, 3, 4, 5, 6}` and the left half `{7, 8, 9, 2}` is not sorted. - -**Step 1 : Check for the sorted half :** - -If `arr[low] > arr[mid]`, then it means that our left half is not sorted and we can't apply a Binary Search over there. In our case `(7 > 2)` so we'll consider the other sorted half. - -**Step 2 : Check for the target in our sorted half :** - -Suppose our **target value is 1.** - -If the target value is present in our right (sorted) half, then it'll always be in the range `arr[mid] <= target <= arr[high]`. - -In our right sorted half, the condition `2 <= 1 <= 6` fails and hence we'll eleminate the right half and now look for 1 in the left half. - -Thereby high goes to `mid - 1` and our search space now is the left half. - -Again, we'll look for the sorted half by following the condition `arr[low] > arr[mid]` and then we'll again check for the target in the sorted half. If not present, eleminate that half and again repeat the same steps untill we get `arr[mid] == target`. - ---- - -### Step by Step Explanation : - -Consider the Array : - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ ^ ^ - low mid high - -target = 1 -``` - -**Check for the sorted half :** - -``` -Here, arr[mid] != target and arr[low] > arr[mid]; -Hence left half is not sorted. -And ultimately, the right half is sorted. -``` - -**Check for element in the right sorted half :** - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ ^ ^ - low mid high - -if (arr[mid] <= target && target <= arr[high]); -that is, if (2 <= 1 && 1 <= 6) which is false, -Means, 1 is not in our right half. -Hence, the right half is now eleminated. -``` - -``` -thereby, high = mid - 1; -``` - -And now our required array becomes, - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ ^ ^ - low mid high -``` - -**Again Check for the sorted half :** - -``` -Here, arr[mid] != target but arr[low] <= arr[mid]; -Hence, They are sorted -``` - -**Check for element in the left sorted half :** - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ ^ ^ - low mid high - -if (arr[low] <= target && target <= arr[mid]); -that is, if (7 <= 1 && 1 <= 8) which is false, -Means, 1 is not in our left half. -Hence, the left half is now eleminated. -``` - -``` -thereby, low = mid + 1; -``` - -And now our required array becomes, - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ ^ - low high - ^ - mid -``` - -**Again Check for the sorted half :** - -``` -Here, arr[mid] != target but arr[low] <= arr[mid]; -that is 9 <= 9, they are sorted. -``` - -**Check for element in the left sorted half :** - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ ^ - low high - ^ - mid - -if (arr[low] <= target && target <= arr[mid]); -that is, if (9 <= 1 && 1 <= 9) which is false, -Means, 1 is not in our left half. -Hence, the left half is now eleminated. -``` - -``` -thereby, low = mid + 1; -``` - -And now our required array becomes, - -``` -index -> 0 1 2 3 4 5 6 7 9 -int arr = {7, 8, 9, 1, 2, 3, 4, 5, 6}; - ^ - low - ^ - mid - ^ - high -``` - -``` -Here, arr[mid] == target and arr[low] <= arr[mid] and (arr[low] <= target && target <= arr[mid]); -That is (1 <= 1 && 1 <= 1) - -Hence we found our element! -``` - ---- - -### Implementation : - -```cpp -int search(vector& arr, int n, int k) -{ - int low = 0, high = n - 1; - while (low <= high){ - int mid = low + (high - low) / 2; - - // base condition - if (arr[mid] == k) return mid; - - // check if left half is sorted - if (arr[low] <= arr[mid]){ - // Check for element in the left sorted half - if (arr[low] <= k && k <= arr[mid]){ - // if it is present, eleminate right search space - high = mid - 1; - } else { - // if not present, eleminate left search space - low = mid + 1; - } - } - else { // if right half is sorted - // Check for element in the right sorted half - if(arr[mid] <= k && k <= arr[high]){ - // if it is present, eleminate left search space - low = mid + 1; - } else { - // if not present, eleminate right search space - high = mid - 1; - } - } - - } - return -1; -} -``` - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/search-in-rotated-sorted-array_1082554?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](https://leetcode.com/problems/search-in-rotated-sorted-array/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/08-search-in-rotated-sorted-duplicate-array.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/08-search-in-rotated-sorted-duplicate-array.md deleted file mode 100644 index e9550e7..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/08-search-in-rotated-sorted-duplicate-array.md +++ /dev/null @@ -1,113 +0,0 @@ -## Search in Rotated Sorted Array of Duplicate Elements. - -**NOTE : A function Searching for an element in Rotated Sorted Array of Duplicate Elements cannot return it's index but returns a boolean value if the target is present in element or not.** - ---- - -In [previous problem](./07-search-in-rotated-sorted-unique-array.md), when we searched the element in a rotated array of unique elements, if followed the steps : - -- Compare mid with target. -- Check for the sorted half. -- Check for the element in the sorted half. - -This steps would probably work with array of duplicate elements in very few cases, for example, if we have an array - -```cpp -int arr[9] = {5, 6, 1, 2, 3, 3, 4, 4, 4}; -int target = 4; -``` - -Everything works fine, we check for the sorted part by comparing `mid` with `low` and we see that the left half is not sorted so we trim that part and then we check for the target in right half and we found some duplicates of target so we returned `true` and everthing seems fine. - ---- - -### But we are not considering an edge case ! - -```cpp -int arr[6] = {3, 1, 3, 3, 3, 3}; -int target = 1; -``` - -Here we can't even compare the `mid`, `low` and `high` in order to find the sorted part as `low == mid == high`. But finding the sorted part is a crucial step to move forward! So how we'll procced further ?? - ---- - -**Well, to tackle this problem, we an first check if the mid is not equal to target and if it's not then we can trim down the search space until we find duplicates on low, mid and high.** - -Here's what I mean : - -``` -Initial array: - -index --> 0 1 2 3 4 5 -int arr[6] = {3, 1, 3, 3, 3, 3} - ^ ^ ^ - low mid high -``` - -``` -Array after trimming corner duplicates if mid != target : - -index --> 0 1 2 3 4 5 -int arr[6] = {3, 1, 3, 3, 3, 3} - ^ ^ ^ - low mid high -``` - -Once we came to a situation where `low != mid` or `mid != high`. - ---- - -**How to trim the search space :** - -```cpp -if (arr[low] == arr[mid] && arr[mid] == arr[high]){ - low++; high--; - continue; -} -``` - ---- - -### Implementation : - -```cpp -bool searchInARotatedSortedArrayII(vector&arr, int target) { - int n = arr.size(); - int low = 0; int high = n - 1; - while (low <= high){ - int mid = low + (high - low) / 2; - if (arr[mid] == target) return true; - - // if corner elements are duplicates of mid element - if (arr[low] == arr[mid] && arr[mid] == arr[high]){ - low++; high--; - continue; - } - - // normal search-rotate-sort algorithm - if (arr[low] <= arr[mid]){ - if (arr[low] <= target && target <= arr[mid]){ - high = mid - 1; - } else { - low = mid + 1; - } - } - else { - if (arr[mid] <= target && target <= arr[high]){ - low = mid + 1; - } else { - high = mid - 1; - } - } - } - return false; -} -``` - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/search-in-a-rotated-sorted-array-ii_7449547?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/09-minimum-in-sorted-rotated.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/09-minimum-in-sorted-rotated.md deleted file mode 100644 index abc6e51..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/09-minimum-in-sorted-rotated.md +++ /dev/null @@ -1,36 +0,0 @@ -## Find Minimum in Rotated Sorted Array - -Given the sorted rotated array **arr** of **unique** elements, return the **minimum** element of this array. -You must write an algorithm that runs in **O(log n)** time. - -```cpp -int findMin(vector& arr) -{ - int low = 0, high = arr.size() - 1; - int ans = INT_MAX; - while (low <= high) { - int mid = low + (high - low) / 2; - - if (arr[low] <= arr[high]) { - ans = min(ans, arr[low]); - break; - } - - if (arr[low] <= arr[mid]){ - ans = min(ans, arr[low]); - low = mid + 1; - } else { - high = mid - 1; - ans = min(ans, arr[mid]); - } - } - return ans; -} -``` - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/rotated-array_1093219?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/10-single-in-sorted-rotated.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/10-single-in-sorted-rotated.md deleted file mode 100644 index 41bf5c6..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/10-single-in-sorted-rotated.md +++ /dev/null @@ -1,63 +0,0 @@ -## Single Element in a Sorted Array - -**Problem Statement :** -You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. - -Return the single element that appears only once. -Your solution must run in **O(log n)** time and **O(1)** space. - ---- - -**Example :** - -``` -Input: arr[9] = [1,1,2,3,3,4,4,8,8]; -Output: 2 -``` - ---- - -### Implementation : - -```cpp -class Solution { -public: - int singleNonDuplicate(vector& arr) { - int n = arr.size(); - - if (n == 1) return arr[0]; // if only 1 element in array - - // trimming down array size to avoid extra comparisons. - if (arr[0] != arr[1]) return arr[0]; - if (arr[n-1] != arr[n-2]) return arr[n-1]; - int low = 1, high = n - 2; - - while (low <= high){ - int mid = low + (high - low) / 2; - - // search for mid to be a single - if (arr[mid] != arr[mid - 1] && arr[mid] != arr[mid + 1]) return arr[mid]; - - /* if one of th half is sorted, our answer is in the opposite half. if we are on left half and it is sorted, eleminate it */ - if ((mid % 2 == 1 && arr[mid] == arr[mid - 1]) - || (mid % 2 == 0 && arr[mid] == arr[mid + 1])) { - low = mid + 1; - } - - // else right half is sorted, eleminate it. - else { - high = mid - 1; - } - - } - return -1; - } -}; -``` - ---- - -**Solve it on :** - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/unique-element-in-sorted-array_1112654?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](https://leetcode.com/problems/single-element-in-a-sorted-array/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Easy/11-find-peak-in-array.md b/Algorithms/Searching-Algorithms/Binary-Search/Easy/11-find-peak-in-array.md deleted file mode 100644 index cbe2cde..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Easy/11-find-peak-in-array.md +++ /dev/null @@ -1,55 +0,0 @@ -## Find Peak Element - -**Problem Statement :** -A peak element is an element that is **strictly** greater than its neighbors. - -Given an integer array nums, find a peak element, and return its index. _If the array contains multiple peaks, return the index to any of the peaks._ - -You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be **strictly** greater than a neighbor that is outside the array. - -You must write an algorithm that runs in **O(log n)** time. - ---- - -**Example :** - -``` -Input: nums = [1,2,3,1] -Output: 2 -Explanation: 3 is a peak element and your function should return the index number 2. -``` - ---- - -### Implementation : - -```cpp -int findPeakElement(vector &arr) { - int n = arr.size(); - - // trimming search space by checking corners - if (n == 0) return 0; - if (arr[0] > arr[1]) return 0; - if (arr[n - 1] > arr[n - 2]) return n - 1; - int low = 1, high = n - 2; - - while (low <= high) { - int mid = low + (high - low) / 2; - - // if my mid is a peak - if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) return mid; - - // if mid is on an increasing curve - else if (arr[mid] > arr[mid - 1]) low = mid + 1; - - // if mid is on an deccreasing curve - else high = mid - 1; - } - return -1; -} -``` - ---- - -[Coding Ninjas](https://www.codingninjas.com/studio/problems/find-peak-element_1081482?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf) & -[LeetCode](https://leetcode.com/problems/single-element-in-a-sorted-array/). diff --git a/Algorithms/Searching-Algorithms/Binary-Search/Medium/koko-eating-bananas.md b/Algorithms/Searching-Algorithms/Binary-Search/Medium/koko-eating-bananas.md deleted file mode 100644 index 9afe03d..0000000 --- a/Algorithms/Searching-Algorithms/Binary-Search/Medium/koko-eating-bananas.md +++ /dev/null @@ -1,116 +0,0 @@ -## KOKO Eating Bananas - -**Problem Statement:** A monkey is given `n` piles of bananas, whereas the `ith` pile has `a[i]` bananas. An integer `h` is also given, which denotes the time (in hours) for all the bananas to be eaten. - -Each hour, the monkey chooses a non-empty pile of bananas and eats `k` bananas. If the pile contains less than `k` bananas, then the monkey consumes all the bananas and won’t eat any more bananas in that hour. - -Find the minimum number of bananas `k` to eat per hour so that the monkey can eat all the bananas within `h` hours. - ---- - -### Examples - -Example 1: -Input Format: N = 4, a[] = {7, 15, 6, 3}, h = 8 -Result: 5 -Explanation: If Koko eats 5 bananas/hr, he will take 2, 3, 2, and 1 hour to eat the piles accordingly. So, he will take 8 hours to complete all the piles. - ---- - -Example 2: -Input Format: N = 5, a[] = {25, 12, 8, 14, 19}, h = 5 -Result: 25 -Explanation: If Koko eats 25 bananas/hr, he will take 1, 1, 1, 1, and 1 hour to eat the piles accordingly. So, he will take 5 hours to complete all the piles. - ---- - -Before moving on to the solution, let’s understand how Koko will eat the bananas. Assume, the given array is {3, 6, 7, 11} and the given time i.e. h is 8. - -First of all, Koko cannot eat bananas from different piles. He should complete the pile he has chosen and then he can go for another pile. -Now, Koko decides to eat 2 bananas/hour. So, in order to complete the first he will take -3 / 2 = 2 hours. Though mathematically, he should take 1.5 hrs but it is clearly stated in the question that after completing a pile Koko will not consume more bananas in that hour. So, for the first pile, Koko will eat 2 bananas in the first hour and then he will consume 1 banana in another hour. - -From here we can conclude that we have to take ceil of (3/2). Similarly, we will calculate the times for other piles. - - 1st pile: ceil(3/2) = 2 hrs - 2nd pile: ceil(6/2) = 3 hrs - 3rd pile: ceil(7/2) = 4 hrs - 4th pile: ceil(11/2) = 6 hrs - -Koko will take 15 hrs in total to consume all the bananas from all the piles. - ---- - -**Observation**: Upon observation, it becomes evident that the maximum number of bananas (represented by 'k') that Koko can consume in an hour is obtained from the pile that contains the largest quantity of bananas. Therefore, the maximum value of 'k' corresponds to the maximum element present in the given array. - -So, our answer i.e. the minimum value of ‘k’ lies between 1 and the maximum element in the array i.e. max(a[]). - ---- - -### Solution : - -```cpp -#include -using namespace std; - -long long calculateTotalHours(vector &v, long long hourly) { - long long totalH = 0; - int n = v.size(); - for (int i = 0; i < n; i++) { - totalH += (v[i] + hourly - 1) / hourly; - } - return totalH; -} - -long long minimumRateToEatBananas(vector &v, long long h) { - long long low = 1, high = INT_MAX; - - while (low < high) { - long long mid = low + (high - low) / 2; - long long totalH = calculateTotalHours(v, mid); - - if (totalH <= h) { - high = mid; - } else { - low = mid + 1; - } - } - return low; -} -``` - ---- - -### Explanation : - -1. `calculateTotalHours` : - This function calculates the total hours required to eat all the bananas at a given hourly rate. It uses integer division and rounds up to the nearest integer using `(v[i] + hourly - 1) / hourly`. - -2. `minimumRateToEatBananas` : - This function performs a **binary search** to find the minimum hourly rate required to eat all the bananas within h hours. It initializes a `low` rate as 1 and a `high` rate as a large integer. - - The binary search continues until low is less than high, and it updates the `mid` rate within this range. - - It then calculates the total hours required at the mid rate using the calculateTotalHours function. If the total hours are less than or equal to h, it updates high to mid, effectively searching in the lower half of the range; otherwise, it updates low to mid + 1, searching in the upper half. - ---- - -The expression `(v[i] + hourly - 1) / hourly` with an example: - -Suppose we have the following values: - - v[i] (the number of bananas to eat) = 12 - hourly (the hourly rate at which we can eat) = 5 - -Using the expression `(v[i] + hourly - 1) / hourly`: - - (12 + 5 - 1) / 5 - (16) / 5 - 3.2 - -Now, let's break it down: - - 12 + 5 - 1 equals 16. This step ensures that we add hourly - 1 to the numerator, which is necessary to ensure rounding up. - 16 / 5 equals 3.2. This is the result of dividing the numerator (16) by the denominator (5). - -In this example, the result of `(v[i] + hourly - 1) / hourly` is 3.2. Since we want to round up to the nearest integer (**because you can't eat a fraction of a banana**), this value would be considered as 4 hours required to eat 12 bananas at a rate of 5 bananas per hour. diff --git a/Algorithms/Searching-Algorithms/linear-search.md b/Algorithms/Searching-Algorithms/linear-search.md deleted file mode 100644 index 2bf8488..0000000 --- a/Algorithms/Searching-Algorithms/linear-search.md +++ /dev/null @@ -1,50 +0,0 @@ -# Linear Search - -_Searching Elements in Contigious Linear Data Structure._ - -**Time Complexity:** - -1. Best Case: O(1) --> Element found at 1st comparison. -2. Average / Worst Case: O(n) --> for n comparisons. (where n is the size of array) - -# Implementation - -```cpp -#include -using namespace std; - -int linearSearch(int arr[], int n, int x) -{ - // loop through each element in the array - for (int i = 0; i < n; i++) - { - // if the current element matches the search value, return the index - if (arr[i] == x) - { - return i; - } - } - // if the search value is not found in the array, return -1 - return -1; -} - -int main() -{ - int arr[] = {10, 20, 30, 40, 50}; - int n = sizeof(arr) / sizeof(arr[0]); - int x = 30; - - int index = linearSearch(arr, n, x); - if (index == -1) - { - cout << "Element not found" << endl; - } - else - { - cout << "Element found at index " << index << endl; - } - - return 0; -} - -``` diff --git a/Algorithms/Sliding-Window/01-intro.md b/Algorithms/Sliding-Window/01-intro.md deleted file mode 100644 index 28858a7..0000000 --- a/Algorithms/Sliding-Window/01-intro.md +++ /dev/null @@ -1,57 +0,0 @@ -## Introduction to Sliding Window Algorithm. - -- The sliding window algorithm is a technique for solving problems that involve a sequence of elements, such as an **array** or a **string**. - -- The sliding window can be termed as a **sub-array** or a **sub-string** which moves over the sequence, and some operation is performed on the elements within the window. - -- The algorithm works by maintaining a window of fixed or variable size over the sequence. - ---- - -## Why we need this algorithm ? - -Suppose you've a problem where your are provided an integer array, - -```cpp -int arr[7] = {2, 3, 5, 2, 9, 7, 1}; -``` - -and an integer let's say '3' which denotes the size of subarray. Find the maximum sum of subarrays. - -**A subarray is a subset of an array. But it must be continuous in nature.** - -``` -The array 2 3 5 2 9 7 1 can have the following size 3 subarrays with their sum : - -2 3 5 sum = 10 -3 5 2 sum = 10 -5 2 9 sum = 16 -2 9 7 sum = 18 --> Maximum sum -9 7 1 sum = 17 -``` - -To solve this problem, we might think about the Brute Force Approach, where we consider 2 pointers `i` and `j`, we use 2 nested `for` loops where `i` iterates from 0 to size and `j` iterates from `i` to `j < i + 3` and stores the sum for each sub-array and at the end returns the max of all individual sums. - -But then we will be performing a **repetitive task** of adding 2 same numbers for each iteration which we've **already performed** in previous iteration. - -**Here's what I mean :** - -``` -2 + 3 + 5 -3 + 5 + 2 we repeat 3 + 5 -5 + 2 + 9 we repeat 5 + 2 -2 + 9 + 7 we repeat 2 + 9 -9 + 7 + 1 we repeat 9 + 7 -``` - -Whenever you find such repetitions in any program, there's a need of **Optimization**. - -To overcome this repetitions, what we can do is to remove the previous value, once it gets added up and then add the upcoming value and so on. - -This is something what a Sliding Window does. Whenever it moves ahead it leaves behind the previous value and includes the upcoming value. - -**See Below Example :** - -![sliding-window](https://github.com/Rishabh672003/Programming-Notes/assets/53911515/7ebe8306-58c5-4b9b-9f35-ca6941612780) - ---- diff --git a/Algorithms/Sliding-Window/02-problem-1.md b/Algorithms/Sliding-Window/02-problem-1.md deleted file mode 100644 index a9a4d0d..0000000 --- a/Algorithms/Sliding-Window/02-problem-1.md +++ /dev/null @@ -1,114 +0,0 @@ -## Maximum sum of subarray with size k - -**Flow** : - -1. Problem Statement - Input - Output -2. Identification -3. Abstract -4. Actual Code - ---- - -**Problem Statement :** -Given an array `arr` of size `n`, Find the maximum sum sub-array with size k. - ---- - -**Input :** - -```cpp -int n = 7; -int arr[n] = {2, 5, 1, 8, 2, 9, 1}; -k = 3 // window size. -``` - ---- - -**Output :** - -Return an integer which is maximum sum among all the sub-arrays. - ---- - -**Identificaion :** - -We are given with an **array/string**, we're asked for a **subarray/substring** and either we have a window size [**fixed size window**] or a condition for window size [**variable size window**]. - ---- - -**Abstract :** - -1. **How do we code the window ?** - - To design a window, we need something to represent it's **start** and something to represent it's **end**. - - Let's denote it's start with a pointer `i` and it's end by another pointer `j`. - - Then the size of window `k` can be given as `k = j - i + 1` - -2. **How to begin ?** - - Initialize two pointers, `i` & `j` [start and end] with 0. `i = 0` and `j = 0`. Why 0? because initially start and end will be at same position. - - Then we'll check if our window size `j-i+1` is less than `k`, if it is, then we'll increase it's size by incrementing `j` until it reaches `k`. - - We increase the size because, the only useful window size to us is of size k where we need to perform our calculation. - - If the size is less than k, we'll increase our `j` pointer and we'll check if the size reaches `k`. - -3. **How we'll get the answer ?** - - Once we reach the condition `j-i+1 == k`, we'll then perform our calculation and we'll get our very first answer. - - At this moment we don't want to loose our window size, we'll maintain the window size by incrementing `i` and `j` simultaneously. And this is how our window will move / slide. - -4. **Conclusion :** - - We'll initialise 2 pointers `i = 0` and `j = 0`, `i` denotes start, `j` denotes end, we'll increase the window size by moving the `j` pointer until we hit the required size `k = j-i+1`, once we hit the requires size, we'll perform our calculation and maintain the size by incrementing `i` as `i++` and `j` as `j++`. - ---- - -**Actual Code :** - -```cpp -#include -using namespace std; - -class Solution { - public: - long maximumSumSubarray(int k, vector& arr, int n) { - int i = 0, j = 0; - long long sum = 0; - long long maxi = INT_MIN; - while (j < n) { - sum += arr[j]; - if (j - i + 1 == k) { - maxi = max(maxi, sum); - sum -= arr[i]; - i++; - } - j++; - } - return maxi; - } -}; - -int main() { - int t; - cin >> t; - while (t--) { - int N, K; - cin >> N >> K; - ; - vector Arr; - for (int i = 0; i < N; ++i) { - int x; - cin >> x; - Arr.push_back(x); - } - Solution ob; - cout << ob.maximumSumSubarray(K, Arr, N) << endl; - } - return 0; -} -``` diff --git a/Algorithms/Sliding-Window/03-problem-2.md b/Algorithms/Sliding-Window/03-problem-2.md deleted file mode 100644 index f53b6ac..0000000 --- a/Algorithms/Sliding-Window/03-problem-2.md +++ /dev/null @@ -1,99 +0,0 @@ -## First Negative Number in every window of size k - -**Problem Statement :** - -You're given an array `arr` of size `n`, your task is to find the first negative integer in every window of size `k.` - ---- - -**We'll use the concept of sliding window to solve this problem.** - -```cpp -#include -using namespace std; -vectorprintFirstNegative(int arr[], int n, int k){ - vector ans; - queue list; - int i = 0, j = 0; - while(j < n){ - if(arr[j] < 0){ - list.push(arr[j]); - } if(j - i + 1 < k){ - j++; - } else if (j - i + 1 == k){ - if(list.size() == 0){ - ans.push_back(0); - } else { - ans.push_back(list.front()); - if (arr[i] == list.front()){ - list.pop(); - } - } - i++; j++; - } - } - return ans; -} -int main(){ - int t, i; - cin >> t; - while (t--) { - int n; - cin >> n; - int arr[n]; - for (i = 0; i < n; i++) { - cin >> arr[i]; - } - int k; - cin >> k; - - vector ans = printFirstNegative(arr, n, k); - for (auto it : ans) cout << it << " "; - cout << endl; - } -} -``` - ---- - -**Explanation :** - -The code first initializes two variables: i and j. The variable i is used to track the index of the current element in the array, and the variable j is used to track the index of the next element to be added to the window. - -The code then iterates over the array. On each iteration, the following steps are performed: - -1. If the current element is negative, then it is added to the queue. - -2. If the size of the window is equal to k, then the following steps are performed: - - If the queue is empty, then the output vector is appended with 0. - - Otherwise, the output vector is appended with the first element in the queue. - - The first element in the queue is removed. - - The index i is incremented by 1. - -3. The index j is incremented by 1. - ---- - -**Example :** - -THe output for an input [-8, 2, 3, -6, 10] and window size 2 is [-8, 0, -6, -6]. - -The first window is [-8, 2]. The first negative integer in this window is -8, so it is appended to the output vector. - -The second window is [2, 3]. There are no negative integers in this window, so 0 is appended to the output vector. - -The third window is [3, -6]. The first negative integer in this window is -6, so it is appended to the output vector. - -The fourth window is [-6, 10]. The first negative integer in this window is -6, so it is appended to the output vector. - ---- - -**Analysis :** - -The output of the code is the vector of the first negative integers in the sliding windows of size `k` in the array `arr`. - -The time complexity of the code is **O(N)**, where N is the number of elements in the array. This is because the code iterates over the array once. The space complexity of the code is **O(k)**, where k is the size of the window. This is because the queue can store up to k elements. diff --git a/Algorithms/Sorting-Algorithms/bubble-sort.md b/Algorithms/Sorting-Algorithms/bubble-sort.md deleted file mode 100644 index a9c5535..0000000 --- a/Algorithms/Sorting-Algorithms/bubble-sort.md +++ /dev/null @@ -1,49 +0,0 @@ -# Bubble Sort - -**Bubble sort is a simple sorting algorithm that repeatedly steps through a list of elements to be sorted, compares each pair of adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.** - -### Working - -Here is an example of how bubble sort works on a list of numbers: - -1. Compare the first two elements. If the first element is greater than the second element, swap them. -2. Move to the next pair of elements (second and third) and repeat step 1. -3. Continue to compare and swap adjacent elements until the end of the list is reached. -4. Repeat steps 1-3 until no more swaps are needed. - -### Implementation in C++ - -```cpp -#include -using namespace std; - -void bubbleSort(int arr[], int n) { - int i, j; - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) { - if (arr[j] > arr[j + 1]) { - swap(arr[j], arr[j + 1]); - } - } - } -} - -int main() { - int arr[] = {64, 25, 12, 22, 11}; - int n = sizeof(arr) / sizeof(arr[0]); - bubbleSort(arr, n); - cout << "Sorted array: "; - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - return 0; -} - -``` - -we define a function called bubbleSort that takes an array of integers and the size of the array as its arguments. The function then uses nested loops to compare adjacent elements in the array and swap them if they are in the wrong order. This process is repeated until the entire array is sorted. - -### Time and Space Complexity of Bubble Sort - -The time complexity of bubble sort is O(n^2), where n is the number of elements in the array. This means that the time taken by the algorithm to sort an array grows quadratically with the size of the input data. Specifically, in the worst case scenario where the array is already sorted in reverse order, the algorithm will take n\*(n-1)/2 comparisons and swaps to sort the array. In the average case, it will take about the same number of comparisons and swaps. - -The space complexity of bubble sort is O(1), which means that the amount of memory required by the algorithm remains constant regardless of the size of the input data. This is because bubble sort only requires a few variables to keep track of the current state of the algorithm, such as the indices of the elements being compared, and a temporary variable used for swapping elements. diff --git a/Algorithms/Sorting-Algorithms/selection-sort.md b/Algorithms/Sorting-Algorithms/selection-sort.md deleted file mode 100644 index 4b6d4ec..0000000 --- a/Algorithms/Sorting-Algorithms/selection-sort.md +++ /dev/null @@ -1,78 +0,0 @@ -
- -# Selection Sort - -
- -### Definition - -**Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from an unsorted list and placing it at the beginning of the list. The algorithm maintains two sub-lists: a sorted sub-list that is built up from left to right at the front of the list, and an unsorted sub-list that contains the remaining elements to be sorted.** - -### Working - -1. Set the first element of the list as the minimum value. -2. Compare the minimum value to the second element of the list. If the second element is smaller than the minimum value, set it as the new minimum value. -3. Repeat step 2 for every element in the list, until the end of the list is reached. -4. Swap the minimum value with the first element of the list. -5. Repeat steps 1-4 for the remaining unsorted sub-list. - -### Implementation in C++ - -```cpp - -#include -using namespace std; - -void selectionSort(int arr[], int n) { - int i, j, min_idx; - - for (i = 0; i < n - 1; i++) { - min_idx = i; - for (j = i + 1; j < n; j++) - if (arr[j] < arr[min_idx]) - min_idx = j; - - swap(arr[min_idx], arr[i]); - } -} - -int main() { - int arr[] = {8, 3, 2, 7, 4, 6, 5, 1}; - int n = sizeof(arr) / sizeof(arr[0]); - selectionSort(arr, n); - cout << "Sorted array: \n"; - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - cout << endl; - return 0; -} - -``` - -**How will the above code will actually work** - -After each step the algorithm finds the least element of the unsorted sub-list and places it at the beginning of the sorted sub-list. - -
- -| unsorted list | sorted list | -| ---------------------- | ---------------------- | -| 8, 3, 2, 7, 4, 6, 5, 1 | | -| 1, 3, 2, 7, 4, 6, 5, 8 | 1 | -| 1, 2, 3, 7, 4, 6, 5, 8 | 1, 2 | -| 1, 2, 3, 7, 4, 6, 5, 8 | 1, 2, 3 | -| 1, 2, 3, 4, 7, 6, 5, 8 | 1, 2, 3, 4 | -| 1, 2, 3, 4, 5, 6, 7, 8 | 1, 2, 3, 4, 5 | -| 1, 2, 3, 4, 5, 6, 7, 8 | 1, 2, 3, 4, 5, 6 | -| 1, 2, 3, 4, 5, 6, 7, 8 | 1, 2, 3, 4, 5, 6, 7 | -| 1, 2, 3, 4, 5, 6, 7, 8 | 1, 2, 3, 4, 5, 6, 7, 8 | - -
- -### Time and Space Complexity - -The time complexity of selection sort is O(n^2), where n is the number of elements in the list. This means that the running time of the algorithm grows quadratically with the number of elements in the list. - -In terms of space complexity, selection sort requires only a constant amount of extra space, since it operates directly on the input list without creating any additional data structures. Therefore, the space complexity of selection sort is O(1). - -Although selection sort is not the most efficient sorting algorithm, its simplicity and low space requirements make it useful for small lists or as a building block in more complex algorithms. diff --git a/Algorithms/time-complexity.md b/Algorithms/time-complexity.md deleted file mode 100644 index fcab57a..0000000 --- a/Algorithms/time-complexity.md +++ /dev/null @@ -1,100 +0,0 @@ -# Time Complexity with the big O notation - -Time complexity refers to the amount of time it takes for an algorithm to execute as a function of the size of its input. -In other words, it is a measure of the amount of time it takes an algorithm to solve a problem as the size of the problem increases. - -The time complexity of an algorithm is generally expressed in big O notation. -It provides an upper bound on the growth rate of the algorithm's running time. - -For example, if an algorithm has a time complexity of O(n), it means that the algorithm's running time increases linearly with the size of its input, -where n represents the size of the input. If the algorithm has a time complexity of O(n^2), -it means that the algorithm's running time increases quadratically with the size of its input. - -A time complexity of O(n^2) may still run faster than an algorithm with a time complexity of O(n) for small inputs, -but as the input size increases, the O(n^2) algorithm will eventually become slower. - -Some common time complexities: - -``` -O(1) (constant time), -O(log n) (logarithmic time), -O(n) (linear time), -O(n log n) (quasilinear time), -O(n^2) (quadratic time), and -O(2^n) (exponential time). - -Increase in Time Complexity --> -O(1) < O(log n) < 0(n) < O(n log n) < O(n^2) < O(2^n) < O(n!) -``` - -Time Complexity for various functions: - -1. If-Else: - -The time complexity of an if-else statement in C++ is O(1), or constant time, - -For example, consider the following if-else statement: - -```cpp -if (n > 0) { - /* the amount of time it takes to evaluate the condition - and execute the corresponding block of code does not depend on the size of the input.*/ -} else {} -``` - -2. For Loop: - -The time complexity of a for loop depends on the number of iterations it performs. -In general, a for loop with a fixed number of iterations has a time complexity of O(1) because the number of iterations is constant -and does not depend on the size of the input. - -For example, consider the following for loop in C++ that iterates 10 times: - -```cpp -for (int i = 0; i < 10; i++) { - // Since the number of iterations is fixed at 10, the time complexity of this for loop is O(1). -} -``` - -However, if the number of iterations in the for loop depends on the size of the input, -then the time complexity will depend on the input size. - -For example, consider the following for loop that iterates n times: - -```cpp -for (int i = 0; i < n; i++) { - /* In this case, the time complexity of the for loop is O(n) - because the number of iterations depends on the size of the input, which is represented by the variable n.*/ -} -``` - -##### Other algorithms - -``` -3. Array Access: O(1) Accessing an element in an array takes constant time since the index can be used to directly access the element. -4. Bubble Sort: O(n^2) -5. Insertion Sort: O(n^2) -6. Selection Sort: O(n^2) -7. Merge Sort: O(n log n) -8. Quick Sort: O(n log n) (average case) -9. Linear Search: O(n) -10. Binary Search: O(log n) (for a sorted array) -11. Length: O(1) -12. Concatenation: O(m+n) (where m and n are the lengths of the strings being concatenated) -13. Comparison: O(min(m,n)) (where m and n are the lengths of the strings being compared) -``` - ---- - -## ![Time-complexity](https://user-images.githubusercontent.com/53911515/227717627-0e7671ac-1dc7-4863-8832-6fed71ef3e23.png) - -These time complexities are for worst-case scenarios and may vary depending on the specific implementation of the function and the input data. - -TLE (Time Limit Exceeded): It is a common error that occurs when the execution time of a program exceeds the time limit set by the compiler. - -Tips to avoid TLE: - -1. Avoid nested loops. -2. Use efficient data structures. -3. Avoid recursion. -4. Understand the time limit. diff --git a/Data-Structures/Hash-Maps/01-maps-intro.md b/Data-Structures/Hash-Maps/01-maps-intro.md deleted file mode 100644 index 3054841..0000000 --- a/Data-Structures/Hash-Maps/01-maps-intro.md +++ /dev/null @@ -1,79 +0,0 @@ -## What is a Map ? - -A map data structure, also known as an associative array or dictionary, is a fundamental concept in computer science. - -It's used to store and manage a collection of **key-value pairs**, where each key is a unique identifier and each value is associated with that key. - -This allows for efficient and fast retrieval of values based on their corresponding keys. - -## Why Map ? - -The map data structure is particularly useful when you want to: - -1. **Retrieve Data Efficiently:** With a map, you can quickly look up a value using its associated key, making searching for specific information a lot faster compared to searching through an entire list. - -2. **Maintain Relationships:** Maps are great for maintaining relationships between different pieces of data. For instance, you can use a map to associate a person's name with their contact information. - -3. **Count Occurrences:** Maps are excellent for counting the occurrences of elements in a collection. For example, you could count the frequency of each word in a text. - -4. **Implementing Algorithms:** Many algorithms and problem-solving techniques involve maps to store intermediate results or to track progress efficiently. - -5. **Implementing Hash Tables:** Under the hood, a common way to implement maps is using hash tables, which are fundamental in computer science. - -## Initialization - -In C++, the map data structure is called a `std::map.` - -It's part of the C++ Standard Template Library (STL) and provides a way to store key-value pairs in a sorted order based on the keys. - -The keys in a `std::map` are unique, which means that each key can only appear once in the map. - -```cpp -#include // include standard map library -``` - ---- - -```cpp -// declaring a map in STL -std::mapname_of_map; -``` - ---- - -```cpp -// example : -std::mapmp; -``` - ---- - -```cpp -// Adding a key-value pair in a map - -#include -using namespace std; - -int main(){ - - map scores; - - // adding value to a key :- - // here, "Amit" is the key and 99 is the value. - scores["Amit"] = 99; - - cout << "Amit's Score: " << scores["Amit"] << endl; - - return 0; -} - -// output: 99 - -/* -Note that scores["Amit"] = 99; -is similar to what we do to initialise -an array element by arr[index] = some_value; -In case of a map, the index value can be of any data type. -In above example the key was a string, hence it was quoted inside a "...". -*/ -``` diff --git a/Data-Structures/Hash-Maps/02-map-methods.md b/Data-Structures/Hash-Maps/02-map-methods.md deleted file mode 100644 index 79ed9d9..0000000 --- a/Data-Structures/Hash-Maps/02-map-methods.md +++ /dev/null @@ -1,62 +0,0 @@ -## STL Map Methods - -1. **Insertion:** - - `mapName[key] = value` - Inserts a key-value pair into the map. - - `insert({key, value})` - Inserts a key-value pair into the map. - -2. Access: - - `mapName[key]` - Accesses the value associated with the given key. - - `at(key)` - Accesses the value associated with the given key (throws an exception if the key is not present). - -3. **Search:** - - `find(key)` - Searches for a key in the map and returns an iterator pointing to it. - - `count(key)` - Returns the number of occurrences of a key (0 or 1 in a map). - -4. **Deletion:** - - `erase(key)` - Removes the element with the given key from the map. - - `clear()` - Removes all elements from the map. - -5. **Size and Empty Check:** - - `size()` - Returns the number of elements in the map. - - `empty()` - Checks if the map is empty. - -6. **Iterators:** - - `begin()` - Returns an iterator pointing to the first element. - - `end()` - Returns an iterator pointing just beyond the last element. - You can use iterators to traverse through the map's elements. - -7. **Range-based Loop:** - - You can use a range-based loop to iterate through the map's elements easily. - -8. **Value Modification:** - - You can modify the value associated with a key directly using the key as an index. - -9. **Bounds:** - - `lower_bound(key)` - Returns an iterator to the first element with a key not less than the given key. - - `upper_bound(key)` - Returns an iterator to the first element with a key greater than the given key. - -10. **Key Comparison:** - - `key_comp()` - Returns a function that compares keys. - - `value_comp()` - Returns a function that compares values. - -11. **Swapping:** - - `swap(map2)` - Swaps the contents of two maps. diff --git a/Data-Structures/Hash-Maps/03-number-of-occurrences.md b/Data-Structures/Hash-Maps/03-number-of-occurrences.md deleted file mode 100644 index 582c44f..0000000 --- a/Data-Structures/Hash-Maps/03-number-of-occurrences.md +++ /dev/null @@ -1,94 +0,0 @@ -## Find Number of Occurrence : Integers - -```cpp -#include -using namespace std; -int main() { - int n; cin >> n; - int arr[n]; - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - - // precompute - int hash[n] = {0}; - for(int i = 0; i < n; i++){ - // go to the index of hash array and do a +1 - hash[arr[i]]++; - } - - //fetch - int num; cin >> num; - - cout << hash[num] << endl; - - return 0; -} -``` - -``` -output : -5 --> size of array -1 1 2 2 3 --> array elements -2 --> target element -2 --> number of it's occurrence -``` - ---- - -### A short explanation : - -- We create an array `arr` of size `n`, and take input of the elements. - -- The Precomputation is done by creating an hash array with size `n`. - -- **Example** : if `arr[i] = 1`, then `hash[1]` will be incremented by 1 and so on. - ---- - -## Find Number of Occurrence : Characters (LowerCase) - -```cpp -#include -using namespace std; -int main(){ - string s; cin >> s; - - // precompute - int hash[26] = {0}; - for (int i = 0; i < s.size(); i++){ - hash[s[i] - 'a']++; - } - - // fetch - char c; cin >> c; - - cout << hash[c - 'a'] << endl; - - return 0; -} -``` - ---- - -### A short explanation : - -- We create an string `s`, and take it's input. - -- The Precomputation begins by creating an hash array with size 26. (index 0 to 25) - -- Then we keep incrementing the count of every `s[i] - 'a'` in hash array. - -- As we know that `s[i]` is a character and **ASCII** value of a is 97, hence we subtract the current character with 'a' to get an integer **ASCII** value equivalent to it's positon in hash array. - -- **Example** : if s`[i] = 'c'`, then `'c' - 'a' = 99 - 97 = 2`, which then refers it's index (position) in hash array. (0 based indexing). - -- While printing output, `hash[c - 'a']` refers to the index value which comes after subtracting character `c - 'a'`. - -- **Example** : If `c = 'd'`, then `hash['d' - 'a'] == hash[100 - 97] == hash[3]`, which is the place where count of `'d'` is stored. - ---- - -### Tags : - -`#hashing` `#find-occurrence` diff --git a/Data-Structures/Hash-Maps/04-max-occurrence.md b/Data-Structures/Hash-Maps/04-max-occurrence.md deleted file mode 100644 index 59f4237..0000000 --- a/Data-Structures/Hash-Maps/04-max-occurrence.md +++ /dev/null @@ -1,58 +0,0 @@ -## Find the maximum Occurring number. - -```cpp -#include -using namespace std; - -int main() { - int n; cin >> n; - int arr[n]; - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - - // create an unordered_map to store the frequencies of the elements - unordered_map mp; - for(int i = 0; i < n; i++){ - mp[arr[i]]++; - } - - // find the maximum value in the map - int max_val = -1; - int max_key = -1; - - for(auto it = mp.begin(); it != mp.end(); it++){ - if(it->second > max_val){ - max_val = it->second; - max_key = it->first; - } - } - - // print the maximum occurring number - cout << max_key << " -> " << max_val << endl; - - return 0; -} -``` - -``` -Output: - -5 --> size of array -1 1 1 2 3 --> array elements -1 -> 3 --> most occurred value -> how many times it occurred. -``` - ---- - -### Explanation : - -- In this code, the mp `unordered_map` is used to store the frequencies of the elements in the `arr` array. - -- The `max_val` variable is used to store the maximum value in the map and the `max_key` variable is used to store the key corresponding to the maximum value. - -- The for loop iterates over the `mp` map and finds the maximum value. - -- `it->first` is the key, `it->second` is the value of that particular iterator value. - -- The maximum occurring number and it's occurrence is then printed. diff --git a/Data-Structures/Linear-Data-Structures/02-strings.md b/Data-Structures/Linear-Data-Structures/02-strings.md deleted file mode 100644 index 513dfb2..0000000 --- a/Data-Structures/Linear-Data-Structures/02-strings.md +++ /dev/null @@ -1,204 +0,0 @@ -# Strings - -In C++, a string is a sequence of characters stored in a contiguous block of -memory. The standard library provides a string class that encapsulates the -management of these sequences of characters. - -- ### To use Strings you need to import the string class from the - -```cpp -#include -``` - -- ### Initialization and declaration: - -```cpp - -#include -using std::string; - -string str; // declares an empty string -string str1 = "Hello"; // declares a string initialized with "Hello" -string str2("World"); // declares a string initialized with "World" -string str3 = str1 + " " + str2; // concatenates two strings -// A string ends with a null character '\0' in memory, which shows that the -// string ends here. -``` - -- ### To input and output strings - -```cpp - -cout << str1 << endl; // prints the string to the console -cin >> str; // reads a string from input. 'cin' stops consideering an input as - // string whenever it gets a space " ". -getline(cin, str); // reads a line of text (string) from input and Overcome 'cin'. -``` - -- ### Length of a String. - -```cpp -string str = "Hello, world!"; -int length = str.length(); // or str.size(); -cout << "Length of string: " << length << endl; -``` - -- ### Reverse a String. - -```cpp -string myString = "Hello, world!"; -reverse(myString.begin(), myString.end()); -cout << "Reversed string: " << myString << endl; - -// Or By Character Array Method. -void reverseString(vector& s) { - int st = 0; - int e = s.size() - 1; - while (st < e) { - swap(s[st++], s[e--]); - } -} -``` - -- ### Rotate A String. - -```cpp -string myString = "Hello, world!"; -rotate(myString.begin(), myString.begin() + 7, myString.end()); -cout << "Rotated string: " << myString << endl; - -/* Explanation: - -This code will output: Rotated string: world!Hello, - -The rotate() function takes three arguments: -The first one is the beginning of the range to be rotated, -The second one is the new beginning of the range after the rotation, and -The third one is the end of the range to be rotated. -In this case, we are rotating the string by 7 positions to the right, -so we pass myString.begin() + 7 as the second argument to rotate(). -This means that the characters from index 0 to index 6 will be moved to the end -of the string, while the characters from index 7 to the end of the string will -be moved to the beginning of the string. - -*/ -``` - -- ### String manipulation - -```cpp - -str.append(" World"); // appends " World" to the string -str.insert(0, "Hello "); // inserts "Hello " at the beginning of the string -str.replace(0, 5, "Hi"); // replaces the first 5 characters with "Hi" -str.erase(0, 3); // erases the first 3 characters of the string -``` - -- ### String Case Change. - -```cpp - -string str; -cout << "Enter String: "; -cin >> str; - -// Convert each character to lowercase -for (char& c : str) { - c = tolower(c); // For uppercase, use toupper(c); -} - -cout << str << endl; // prints lower case output. - -/* How Case Conversion works: - -1. Uppercase --> Lowercase -('CHARACTER' - 'A') + 'a'. - -2. Lowercase --> Uppercase -('character' - 'a') + 'A'. - -eg: [B] -We know that A --> 1, B --> 2. -then, B - A --> 2 - 1 = 1. -now, This 1 + 'a' --> 1 + 1 = 2 --> 'b' - -3. Character --> Number (integer) -suppose, char = '1'. -then, 'ch' - '0' = number -i.e; '1' - '0' = 1. -*/ -``` - -- ### Check Palindrome [For a Single Word]. - -```cpp -bool isPalindrome(string s) { - int left = 0, right = s.length() - 1; - while (left < right) { - if (s[left] != s[right]) { - return false; - } - left++; - right--; - } - - return true; -} -``` - -- ### Check Palindrome [for a sentence including spaces & special characters] - -```cpp -/* -A phrase is a palindrome if, after converting all uppercase letters into -lowercase letters and removing all non-alphanumeric characters, it reads the -same forward and backward. Alphanumeric characters include letters and numbers. - -Given a string s, return true if it is a palindrome, or false otherwise. - -Example: -Input: s = "A man, a plan, a canal: Panama" -Output: true -Explanation: After removing all the spaces and special characters, -"amanaplanacanalpanama" is a palindrome. -*/ - -#include -using namespace std; - -bool isAlphanumeric(char ch) { - return isalpha(ch) || isdigit(ch); // checks alphabet and digits, return - // true if alphabet or digit -} - -bool isPalindrome(string s) { - // Remove non-alphanumeric characters and convert to lowercase - string cleanStr; - for (char ch : s) { - if (isAlphanumeric(ch)) { - cleanStr += tolower(ch); - } - } - - // Check if the cleaned string is a palindrome - int left = 0, right = cleanStr.length() - 1; - while (left < right) { - if (cleanStr[left] != cleanStr[right]) { - return false; - } - left++; - right--; - } - - return true; -} - -int main() { - string str; - cout << "Enter Something: "; - cin >> str; - cout << "Is Palindrome: " - << isPalindrome(str); // Returns 1 or 0, if palindrome or not. - return 0; -} -``` diff --git a/Data-Structures/Linear-Data-Structures/03-vectors.md b/Data-Structures/Linear-Data-Structures/03-vectors.md deleted file mode 100644 index 02c5ebb..0000000 --- a/Data-Structures/Linear-Data-Structures/03-vectors.md +++ /dev/null @@ -1,109 +0,0 @@ -# STL vector in C++ - -In C++, a vector is a dynamic array that can resize itself during runtime. It is defined in the header file. - -```cpp -#include -``` - -Here's how to initialize a vector: - -```cpp -vector v; -``` - -Initialize Vector with size. - -```cpp -vector v1(5); // Vector with size 5. By Default all elements are assigned as 0. -vector v2(5, 1) // Vector with size 5, and all elements are assigned as 1. -``` - -To insert and remove values from the vector: - -```cpp -vector.push_back(1); // Insert Values from behind. -vector.pop_back(); // Removes an element from end. -``` - -You can also access elements in the vector using the square bracket notation, just like with arrays: - -```cpp -cout << vector[1]; -``` - -Adding elements in vector with `for` loop. - -```cpp -vector a(5); -for (int i : a) // for i belongs to vector a. -{ - cin >> i; -} -``` - -You can output all the elements of the vector using the `for` loop: - -```cpp -for (auto i = 0; i < vector.size(); i++) { - cout << vector[i] << " "; -} -/* -The keyword auto is used to declare a variable i without specifying its type -explicitly. Instead, the type of i is automatically deduced by the compiler -based on the type of the container. -*/ -``` - -```cpp -vector b(a); // Copying vector a to another vector b. -``` - -Vector in a function. - -```cpp -returnType functionName(vector& vectorName, int size) { returnValue; } -``` - -Useful vector functions: - -```cpp -vector.size(); // gives you the size of the vector -vector.capacity(); // gives you the capacity of the vector i.e; the memory - // allocated to it. -vector.empty(); // empties the vector -vector.resize(n); // resizes the vector to n elements -vector.shrink_to_fit(); // releases unused memory and set the capacity to match - // the current size. -vector.reserve(n); // reserves the capacity of the vector to n elements -vector.swap(v2); // swaps the contents of the vector v and v2 -vector.clear(); // clears the vector -vector.front(); // returns the first element of the vector -vector.back(); // returns the last element of the vector -vector.data(); // returns a pointer to the vector's elements -vector.data() + i; // returns a pointer to the i'th element of the vector -vector.begin(); // returns a pointer to the first element of the vector -vector.end(); // gives you a pointer to the end of the vector -back_inserter(vector); // returns an iterator to the last element -sort(vector.begin(), - vector.end()); // sorts the vector in ascending order comes from STL -sort(vector.begin(), vector.end(), - greater()); // sorts the vector in descending order comes from STL -``` - -These are some functions in the algorithm library in c++ very useful for manipulating vectors: - -```cpp - -#include // you need this to use the algorithm library - -reverse(vector.begin(), vector.end()); // reverses the vector -auto it = find(vector.begin(), vector.end(), 1); // finds the element 1 in the vector -auto it = min_element(vector.begin(), vector.end()); // finds the minimum element in the vector -auto it = max_element(vector.begin(), vector.end()); // finds the maximum element in the vector -sum(vector.begin(), vector.end()); // returns the sum of all elements in the vector -swap(vector[0], vector[1]); // swaps the first two elements of the vector -unique(vector.begin(), vector.end()); // removes all the duplicates from the vect -binary_search(vector.begin(), vector.end(), 1); // returns true if 1 is in the vector, false otherwise -erase(vector.begin(), vector.end()); // erases all the elements from the) -``` diff --git a/Data-Structures/Linear-Data-Structures/04-stacks.md b/Data-Structures/Linear-Data-Structures/04-stacks.md deleted file mode 100644 index c1213a2..0000000 --- a/Data-Structures/Linear-Data-Structures/04-stacks.md +++ /dev/null @@ -1,203 +0,0 @@ -# Stacks - -### Basic definition - -A stack is a linear data structure that follows the principle of Last In First -Out (LIFO). This means the last element inserted inside the stack is removed -first. A real-life example of a stack is a pile of plates stacked on top of -another. If you want the plate at the bottom, you must first remove all the -plates on top. - -![STACK](https://cdn.programiz.com/sites/tutorial2program/files/stack.png) - -### Working of stack - -A stack uses a pointer called TOP to keep track of the top element in the stack. -When initializing the stack, its value is set to -1 so that we can check if the -stack is empty by comparing TOP == -1. On pushing an element, we increase the -value of TOP and place the new element in the position pointed to by TOP. On -popping an element, we return the element pointed to by TOP and reduce its value. - -![Working of Stack](https://cdn.programiz.com/sites/tutorial2program/files/stack-operations.png) - -### Advantages and uses of Stacks - -Stacks are very powerful despite their simplicity. They are used to reverse a -word, in compilers to calculate the value of expressions, and in browsers to -manage the history of URLs visited. Each time you visit a new page, it is added -on top of the stack. When you press the back button, the current URL is removed -from the stack, and the previous URL is accessed. For the array-based -implementation of a stack, the push and pop operations take constant time, i.e. -O(1) - -## Implementations - -### Implementation in C++ - -```cpp -#include -#define MAX_SIZE 100 - -// Function to push an element into the stack -void push(int stack[], int& top, int value) { - if (top == MAX_SIZE - 1) { - std::cout << "Stack Overflow!\n"; - } else { - top++; - stack[top] = value; - std::cout << "Element " << value << " pushed successfully!\n"; - } -} - -// Function to pop an element from the stack -void pop(int stack[], int& top) { - if (top == -1) { - std::cout << "Stack Underflow!\n"; - } else { - int value = stack[top]; - top--; - std::cout << "Element " << value << " popped successfully!\n"; - } -} - -// Function to get the top element of the stack -int top(int stack[], int top) { - if (top == -1) { - std::cout << "Stack is empty!\n"; - return -1; // assuming -1 represents an empty stack - } else { - return stack[top]; - } -} - -// Function to check if the stack is empty -bool isEmpty(int top) { return top == -1; } - -// Function to check if the stack is full -bool isFull(int top) { return top == MAX_SIZE - 1; } - -int main() { - int stack[MAX_SIZE]; - int topIndex = -1; - - push(stack, topIndex, 5); // pushing element 5 - push(stack, topIndex, 10); // pushing element 10 - push(stack, topIndex, 15); // pushing element 15 - - std::cout << "Top element of the stack: " << top(stack, topIndex) << "\n"; - - pop(stack, topIndex); // popping an element - - std::cout << "Top element of the stack: " << top(stack, topIndex) << "\n"; - - return 0; -} -``` - -### Implementation in Java - -```java -import java.util.EmptyStackException; - -public class CombinedStack { - private int[] stackArray; - private int top; - private int maxSize; - - public CombinedStack(int maxSize) { - this.maxSize = maxSize; - stackArray = new int[maxSize]; - top = -1; - } - - public void push(int value) { - if (top == maxSize - 1) { - throw new StackOverflowError("Stack is full"); - } - top++; - stackArray[top] = value; - } - - public int pop() { - if (isEmpty()) { - throw new EmptyStackException(); - } - int value = stackArray[top]; - top--; - return value; - } - - public int peek() { - if (isEmpty()) { - throw new EmptyStackException(); - } - return stackArray[top]; - } - - public boolean isEmpty() { - return top == -1; - } - - public boolean isFull() { - return top == maxSize - 1; - } - - public static void main(String[] args) { - CombinedStack stack = new CombinedStack(5); - stack.push(10); - stack.push(20); - stack.push(30); - - System.out.println("Top element: " + stack.peek()); - - int poppedElement = stack.pop(); - System.out.println("Popped element: " + poppedElement); - - System.out.println("Is stack empty? " + stack.isEmpty()); - System.out.println("Is stack full? " + stack.isFull()); - } -} -``` - -### Implementation in python - -```py -class Stack: - def __init__(self): - self.stack = [] - - def push(self, item): - self.stack.append(item) - - def pop(self): - if not self.is_empty(): - return self.stack.pop() - else: - raise Exception("Stack is empty") - - def peek(self): - if not self.is_empty(): - return self.stack[-1] - else: - raise Exception("Stack is empty") - - def is_empty(self): - return len(self.stack) == 0 - - def size(self): - return len(self.stack) - - -stack = Stack() -stack.push(10) -stack.push(20) -stack.push(30) - -print("Top element:", stack.peek()) - -popped_element = stack.pop() -print("Popped element:", popped_element) - -print("Is stack empty?", stack.is_empty()) -print("Stack size:", stack.size()) -``` diff --git a/Data-Structures/Linear-Data-Structures/05-queues.md b/Data-Structures/Linear-Data-Structures/05-queues.md deleted file mode 100644 index 8f8dc10..0000000 --- a/Data-Structures/Linear-Data-Structures/05-queues.md +++ /dev/null @@ -1,275 +0,0 @@ -# Queues - -### Basic Definition - -A queue is a linear data structure that allows operations to be performed in a -First In First Out (FIFO) order. This means that the element that is first -inserted into the queue is the first one to be removed. It can be visualized -as a line of people waiting for a service, where the person who arrives first -gets served first. - -Adding items to the queue is known as **enqueue**, and removing items from the queue is known as **dequeue**. - -### Why use Queues? - -Queues are often used in scenarios where data doesn't need to be processed -immediately but in a FIFO order. For example, in disk scheduling, asynchronous -data transfer, semaphores, print spooling, or input device buffers. - -### Working of Queues - -In a queue, all additions are made at one end (known as the rear), and all -deletions are made at the other end (known as the front). - -When implemented using an array, the queue uses two variables, 'front' and -'rear'. The 'front' variable points to the index where the first element is -stored, while the 'rear' variable points to the index where the last element is -stored. - -## Implementations - -### Implementation in C++ - -```cpp -#include -#define SIZE 5 - -int items[SIZE]; -int front = -1; -int rear = -1; - -bool isFull() { - if (front == 0 && rear == SIZE - 1) { - return true; - } - return false; -} - -bool isEmpty() { - if (front == -1) { - return true; - } - return false; -} - -void enqueue(int element) { - if (isFull()) { - std::cout << "Queue is full\n"; - } else { - if (front == -1) - front = 0; - rear++; - items[rear] = element; - std::cout << "Inserted " << element << "\n"; - } -} - -int dequeue() { - int element; - if (isEmpty()) { - std::cout << "Queue is empty\n"; - return (-1); - } else { - element = items[front]; - if (front >= rear) { - front = -1; - rear = -1; - } /* Q has only one element, so we reset the - queue after dequeuing it. */ - else { - front++; - } - std::cout << "Deleted -> " << element << "\n"; - - return (element); - } -} - -void display() { - /* Function to display status of Circular Queue */ - int i; - if (isEmpty()) { - std::cout << "Empty Queue" << std::endl; - } else { - std::cout << "Front -> " << front; - std::cout << "Items -> "; - for (i = front; i <= rear; i++) - std::cout << items[i] << " "; - std::cout << " Rear -> " << rear << std::endl; - } -} - -int main() { - // Dequeuing an empty queue - dequeue(); - - enqueue(1); - enqueue(2); - enqueue(3); - enqueue(4); - enqueue(5); - - // This fails to enqueue because the queue is full - enqueue(6); - - display(); - dequeue(); - - // Fails to dequeue because queue is empty - dequeue(); - - return 0; -} -``` - -### Implementation in Java - -```java -public class Queue { - int SIZE = 5; - int items[] = new int[SIZE]; - int front, rear; - - Queue() { - front = -1; - rear = -1; - } - - // check if the queue is full - boolean isFull() { - if (front == 0 && rear == SIZE - 1) { - return true; - } - return false; - } - - // check if the queue is empty - boolean isEmpty() { - if (front == -1) - return true; - else - return false; - } - - // insert elements to the queue - void enqueue(int element) { - if (isFull()) { - System.out.println("Queue is full"); - } - else { - if (front == -1) { - // mark front denote first element of queue - front = 0; - } - rear++; - // insert element at the rear - items[rear] = element; - System.out.println("Insert " + element); - } - } - - // delete element from the queue - int dequeue() { - int element; - if (isEmpty()) { - System.out.println("Queue is empty"); - return (-1); - } else { - element = items[front]; - if (front >= rear) { - front = -1; - rear = -1; - } else { - front++; - } - System.out.println(element + " Deleted"); - return (element); - } - } - - void display() { - if (isEmpty()) { - System.out.println("Empty Queue"); - } else { - System.out.println("Front index: " + front); - System.out.println("Rear index: " + rear); - System.out.println("Items in the queue: "); - for (int i = front; i <= rear; i++) { - System.out.print(items[i] + " "); - } - } - } - - public static void main(String[] args) { - Queue q = new Queue(); - - // deQueue is not possible on empty queue - q.dequeue(); - - // enQueue 5 elements - q.enqueue(1); - q.enqueue(2); - q.enqueue(3); - q.enqueue(4); - q.enqueue(5); - - // 6th element can't be added to queue because queue is full - q.enqueue(6); - - q.display(); - - // deQueue removes element entered first - q.dequeue(); - - q.display(); - } -} -``` - -### Implementation in python - -```py -class Queue: - def __init__(self): - self.queue = [] - - # Add an element - def enqueue(self, item): - self.queue.append(item) - - # Remove an element - def dequeue(self): - if len(self.queue) < 1: - return None - return self.queue.pop(0) - - # Display the queue - def display(self): - print(self.queue) -``` - -### Real-life examples of queues (because our sir loves those) - -1. Ticket lines: Queues are often used to manage ticket lines, such as at a - movie theater or a sporting event. The first person in line gets the first - ticket, and so on. - -2. Print spoolers: Print spoolers use queues to manage print jobs. When a user - sends a print job to a printer, it is placed in the print queue. The print - jobs are then processed in the order in which they were received. - -3. Message queues: Message queues are used to send and receive messages between - different processes. Messages are placed in a queue, and then they are - processed by the processes in the order in which they were received. - -4. Traffic lights: Traffic lights use queues to control the flow of traffic. - Cars are placed in a queue, and then they are allowed to pass through the - intersection one at a time. - -5. Operating systems: Operating systems often use queues to manage resources, - such as CPU time and memory. Processes are placed in a queue, and then they - are allocated resources in the order in which they were received. - -6. Web servers: Web servers often use queues to manage requests from web - browsers. Requests are placed in a queue, and then they are processed by the - web server in the order in which they were received. diff --git a/Data-Structures/Linear-Data-Structures/Array/01-arrays.md b/Data-Structures/Linear-Data-Structures/Array/01-arrays.md deleted file mode 100644 index d209d6c..0000000 --- a/Data-Structures/Linear-Data-Structures/Array/01-arrays.md +++ /dev/null @@ -1,392 +0,0 @@ -# Arrays - -### Basic definition - -In C++, an array is a collection of elements of the same type that are stored sequentially in memory. Each element in an array can be accessed using an index value, which starts at 0 for the first element and increments by 1 for each subsequent element. - -### Initializing an array - -First you define the type of each element in the array, and then you initialize the array with its name and number of elements in the array - -```cpp -int arr[5]; // defines an array of 5 integers -string arr[5]; // defines an array of 5 strings -``` - -OR - -```cpp -int arr[5] = {1,2,3,4,5} -string arr[5] = {"a","b","c","d","e"} - -``` - -You access the elements of an array using the index value, which starts at 0 for the first element and increments by 1 for each subsequent - -```cpp -int x = arr[0]; // access the first element of the array -int y = arr[1]; // access the second element of the array -int z = arr[2]; // access the third element of the - -``` - -##### Note that in C++, arrays do not perform bounds checking, so it is possible to access elements outside the bounds of the array. This can lead to undefined behavior, so it's important to be careful when working with arrays to ensure that you stay within the bounds of the array. - -### Size of Array - -```cpp -int arr[2] = {2,7}; -int arrSize = sizeof(arr)/sizeof(int); // That is 8 / 4 = 2. -cout<<" Size of array is " << arrSize < - using namespace std; - - bool isPresent(int *arr, int size, int key) - { - - for (int i = 0; i < size; i++) - { - if (arr[i] == key) - { - return 1; - } - } - return 0; - } - - int main() - { - int arr[7] = {3, 4, 5, 67, -9, 1, 0}; - int key; - cout << "Enter Number to be found: "; - cin >> key; - bool found = isPresent(arr, 7, key); - - if (found) - cout << "Present!" << endl; - else - cout << "Not Found!" << endl; - - return 0; - } - - ``` - -- 2. Binary search. - - ```cpp - #include - using namespace std; - - int binarySearch(int arr[], int size, int key) { - - int start = 0; - int end = size-1; - - int mid = start + (end-start)/2; - - while(start <= end) { - - if(arr[mid] == key) { - return mid; - } - - //go to right wala part - if(key > arr[mid]) { - start = mid + 1; - } - else{ //key < arr[mid] - end = mid - 1; - } - - mid = start + (end-start)/2; - } - - return -1; - } - - - int main() { - - int even[6] = {2,4,6,8,12,18}; - int odd[5] = {3, 8, 11, 14, 16}; - - int evenIndex = binarySearch(even, 6, 6); - - cout << " Index of 6 is " << evenIndex << endl; - - int oddIndex = binarySearch(odd, 5, 14); - - cout << " Index of 14 is " << oddIndex << endl; - - - return 0; - } - - int findPeak(int arr[], int n) { - - int s =0, e = n-1; - int mid = s + (e-s)/2; - - while(s - using namespace std; - - void revArray(int arr[], int size) - { - int start = 0; - int end = size - 1; - - while (start <= end) - { - swap(arr[start], arr[end]); - start++; - end--; - } - } - - void printArr(int arr[], int size) - { - for (int i = 0; i < size; i++) - { - cout << arr[i] << " "; - } - } - - int main() - { - int even[6] = {1, 2, 3, 4, 5, 6}; - int odd[5] = {1, 2, 3, 4, 5}; - revArray(even, 6); - revArray(odd, 5); - - printArr(even, 6); - cout << endl; - printArr(odd, 5); - - return 0; - } - ``` - -- 4. Find Duplicate Element. - - ```cpp - #include - using namespace std; - - int findUnique(int a[], int size) - { - sort(a, a + size); // Time Complexity O(nLogn) - - int duplicate = a[0]; - - for (int i = 1; i < size; i++) - { - if (a[i] == a[i - 1]) - { - duplicate = a[i]; - break; - } - } - - return duplicate; - } - - int main() - { - int a[7] = {1, 2, 3, 4, 5, 6, 6}; - int size = sizeof(a) / sizeof(a[0]); - - int duplicate = findUnique(a, size); - - cout << "The Duplicate element in the array is: " << duplicate << endl; - - return 0; - } - ``` - -- 5. Sort 0 1 - - ```cpp - // 0 0 1 1 2 2... - - #include - using namespace std; - - void printArray(int *arr) - { - for (int i = 0; i < 10; i++) - { - cout << arr[i] << " "; - } - cout << endl; - } - - void swap1(int *arr) - { - int left = 0, right = 9; // right == size - 1 - while (left < right) // start from arr[i] till arr[n-1] - { - // shift all 0's to left and 1's to right - while (arr[left] == 0 && left < right) - left++; // If Left Already 0 then update index. - - while (arr[right] == 1 && left < right) - right--; // If right Already 1 then update index. - - if (left < right) - swap(arr[left], arr[right]); - left++; - right--; - } - printArray(arr); - } - - int main() - { - int arr[10] = {1, 1, 0, 0, 1, 0, 0, 1, 1, 1}; - // METHOD 1: Sort --> O(nLogn) - sort(arr, arr + 7); - printArray(arr); - - // METHOD 2: Swap --> O(n) - swap1(arr); - - return 0; - } - ``` - -- 6. Array Min/Max - - ```cpp - #include - using namespace std; - - int getMin(int num[], int n) { - - int mini = INT_MAX; - - for(int i = 0; i max){ - // max = num[i]; - // } - } - - //returning max value - return maxi; - } - - int main() { - - int size; - cin >> size; - - int num[100]; - - //taking input in array - for(int i = 0; i> num[i]; - } - - cout << " Maximum value is " << getMax(num, size) << endl; - cout << " Minimum value is " << getMin(num, size) << endl; - - return 0; - } - ``` - -- 7. Swap Alternate. - - ```cpp - #include - using namespace std; - - void printArray(int arr[], int n) { - - for(int i = 0; i Traverse from n - 2 --> if (a[i] != largest) ==> secondLargest == a[i] - - Time Complexity : O(N Log N) + N ==> [Sort + Traversal] - -Code : - -```cpp -int secondLargest(vector &arr, int n){ - int secondLargest = -1; - sort(arr.begin(), arr.end()); // O(N Log N) - for (int i = n - 2; i >= 0; i++) { // O(N) - if (arr[i] != largest) { - secondLargest = arr[i]; - } - } - return secondLargest; -} -``` - -2. Better : Traverse for Largest --> set SecondLargest = -1 --> Traverse again --> if (arr[i] > SecondLargest and arr[i] != largest) ==> secondLargest == a[i] - - Time Complexity : O(2N) ==> [Two Traversals] - -Code : - -```cpp -int secondLargest(vector &arr, int n){ - int largest = arr[0]; - int secondLargest = -1; - for (int i = 0; i < n; i++){ // O(N) - if (arr[i] > largest){ - largest = arr[i]; - } - } - for (int i = 0; i < n; i++){ // O(N) - if (arr[i] > secondLargest && arr[i] != largest){ - secondLargest = arr[i]; - } - } - return secondLargest; -} -``` - -3. Optimal : set FirstElement to Largest, set SecondLargest = -1 --> Traverse from 0 to n --> if found an a[i] > Largest ==> SecondLargest == Largest and Largest == arr[i] --> else if found an a[i] < largest but a[i] > SecondLargest ==> SecondLargest == a[i] - - Time Complexity : O(N) ==> [Single Traversal] - -Code : - -```cpp -int secondLargest(vector &arr, int n){ - int largest = arr[0]; - int secondLargest = -1; - for (int i = 0; i < n; i++){ // O(N) - if (arr[i] > largest){ - secondLargest = largest; - largest = arr[i]; - } else if (arr[i] < largest && arr[i] > secondLargest){ - secondLargest = arr[i]; - } - } - return secondLargest; -} -``` - ---- - -### Bonus : Find Second Smallest - -```cpp -int secondLargest(vector &arr, int n){ - int smallest = arr[0]; - int secondSmallest = INT_MAX; - for (int i = 0; i < n; i++){ - if (arr[i] < smallest){ - secondSmallest = smallest; - smallest = arr[i]; - } else if (arr[i] != smallest && arr[i] < secondSmallest){ - secondSmallest = arr[i]; - } - } - return secondSmallest; -} -``` diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/01-linked-list.md b/Data-Structures/Linear-Data-Structures/Linked-List/01-linked-list.md deleted file mode 100644 index 4ea192b..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/01-linked-list.md +++ /dev/null @@ -1,63 +0,0 @@ -# Linked Lists. - - - -**Table of content :** - -- [Why do we need Linked list ?](#why-do-we-need-linked-list) -- [What is a Linked List ?](#what-is-a-linked-list) -- [Structure of a Linked List](#structure-of-a-linked-list) -- [Linked List Terminologies](#linked-list-terminologies) -- [A depiction of a Linked list in heap memory](#a-depiction-of-a-linked-list-in-heap-memory) - - ---- - -### Why do we need Linked list ? - -We need a data structure which is dynamic in nature, means it should not have a fixed size. The size could be changed during the run-time. - -An **array** with size 10 will be allocated a fixed 10 sized in memory and hence it cannot span or contract during the run-time. - -A **vector** can span double to its size if extra elements are meant to be added, but it ultimately wastes the remaining allocated memory. - -Hence we need an optimal data structure which can grow or shrink on run time with no memory waste. - ---- - -### What is a Linked List ? - -A Linked list is a **Linear** but **Non-contiguous** Data Structure. Unlike arrays, hey are **Dynamic** in nature. - -Linked list elements are randomly placed in the heap memory and hence **cannot be indexed**. - ---- - -### Structure of a Linked List - -**If Linked list elements are non-contiguous, then how do they form a linear collection?** - -This is only possible because, in a Linked list, each member element is linked to the other with a reference to its memory location, means each linked list element stores its **data** and also a pointer to point the **memory address** of its next element. - -**But there's no Primitive or Collective data type which can hold two things at a time!** - -So we need to create a **Self Defined data type (a struct or a class)**, which can hold two values, the data (of any type) and a pointer to point a memory address at the same time. - -Let's call this self defined data type a **NODE**. Now each node will have two halves, the first half will store data, the other half will store a pointer. A single node may look like a capsule with two halves: - -``` - [ Data | Pointer* ] -``` - ---- - -### Linked List Terminologies - -1. **Head node** : The first node of Linked list is the head node and acts as a starting point for most of the operations. -2. **Tail node** : The last node of Linked list which points to the NULL Pointer 0x0. - ---- - -### A depiction of a Linked list in heap memory : - -![Linked-List-1](https://github.com/amitsuthar69/assets/blob/main/linked-lists/linked-list-1.png?raw=true) diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/02-node-creation.md b/Data-Structures/Linear-Data-Structures/Linked-List/02-node-creation.md deleted file mode 100644 index 567530e..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/02-node-creation.md +++ /dev/null @@ -1,33 +0,0 @@ -## Creating a Node in Linked List - -The self defined data type to create a node could be a struct or a class. - -### C++ Implementation : - -```cpp -#include -using namespace std; - -class Node { - public: - // node members - int data; // data - Node* next; // pointer - - // constructor - Node(int val) { - data = val; - next = nullptr; - } -}; - -int main() { - vector arr = {2, 3, 4, 6, 3}; - const Node* n1 = new Node(arr[1]); // creating a new node - cout << n1->data << endl; // print 3 - cout << n1->next << endl; // prints Null address - return 0; -} -``` - -The line `Node *n1 = new Node(arr[1]);` of code is allocating memory for a new object of the class named `Node` on the heap and assigning the address of the object to a pointer variable named `next`. diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/03-traversal.md b/Data-Structures/Linear-Data-Structures/Linked-List/03-traversal.md deleted file mode 100644 index ad4de88..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/03-traversal.md +++ /dev/null @@ -1,27 +0,0 @@ -## Traversing in a Linked List - -### Algorithm : - -1. Create a temporary node (temp) which points to head node. -2. Unless the temp points to a NULL node, do the following things repeatedly : - - print current temp node's data. - - move the temp node ahead by assigning the temp node to its next node. - -```cpp -class Solution { - public: - void display(Node* head) { - Node* temp = head; - while (temp != NULL) { - std::cout << temp->data << " "; - temp = temp->next; - } - } -}; -``` - ---- - -### Depiction of traversal - -![linked-list-1](https://github.com/Rishabh672003/Programming-Notes/assets/53911515/98f79c73-5949-4bd7-8001-7201c0f46e44) diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/04-insertion.md b/Data-Structures/Linear-Data-Structures/Linked-List/04-insertion.md deleted file mode 100644 index 6975914..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/04-insertion.md +++ /dev/null @@ -1,138 +0,0 @@ -## Insertion in a Linked List. - -### 1. Insertion at head - -- Create a new node and assign the data to it. -- Set the `next` pointer of the new node to the current head of the list. -- Update the head of the list to the new node. - ---- - -### 2. **Insertion at tail** - -- Create a new node and assign the data to it. -- Set the `next` pointer of the current tail node to the new node. -- Update the tail of the list to the new node. - ---- - -### 3. **Insertion at any position** - -- If the position is 1, insert at the head. -- If the position is greater than the length of the list, insert at the tail. -- Otherwise, traverse the list to the desired position. -- Create a new node and assign the data to it. -- Set the `next` pointer of the new node to the node currently at the desired position. -- Update the `next` pointer of the node before the desired position to the new node. - ---- - -### Implementation : - -```cpp -#include - -using std::cout, std::cin, std::endl, std::string; - -class Node { - public: - int data; - Node* next; - - explicit Node(int data) { - this->data = data; - this->next = NULL; - } - virtual ~Node() { - if (this->next != NULL) { - delete next; - this->next = NULL; - } - } -}; - -void insertAtHead(Node*& head, int data) { - Node* temp = new Node(data); - temp->next = head; - head = temp; -} - -void insertAtTail(Node*& tail, int data) { - Node* temp = new Node(data); - tail->next = temp; - tail = temp; -} - -void insertAtPosition(Node*& head, Node*& tail, int pos, int data) { - Node* temp = head; - int cnt = 1; - - // if inserting at first pos - if (pos == 1) { - insertAtHead(head, data); - return; - } - - // if inserting at last pos - if (temp->next == NULL) { - insertAtTail(tail, data); - return; - } - - while (cnt < pos - 1) { - temp = temp->next; - cnt++; - } - - Node* nodeToInsert = new Node(data); - nodeToInsert->next = temp->next; - temp->next = nodeToInsert; -} - -void printLinkedList(Node*& head) { - Node* temp = head; - while (temp != NULL) { - cout << temp->data << " "; - temp = temp->next; - } - cout << endl; -} - -int main() { - Node* node1 = new Node(10); - - // create head and tail pointer. - Node* head = node1; - Node* tail = node1; - - cout << "Initial List : "; - printLinkedList(head); - - insertAtHead(head, 12); - - cout << "List after insertion at head : "; - printLinkedList(head); - - insertAtTail(tail, 13); - - cout << "List after insertion at tail : "; - printLinkedList(head); - - insertAtPosition(head, tail, 3, 14); - - cout << "List after insertion at 3rd position : "; - printLinkedList(head); - return 0; -} -``` - -**Output** : - -``` -Initial List : 10 -List after insertion at head : 12 10 -List after insertion at tail : 12 10 13 -List after insertion at 3rd position : 12 10 14 13 -``` - ---- diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/reverseLinkedList.md b/Data-Structures/Linear-Data-Structures/Linked-List/reverseLinkedList.md deleted file mode 100644 index 8bd0ffa..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/reverseLinkedList.md +++ /dev/null @@ -1,50 +0,0 @@ -## Reverse a Linked List - -### Approach : - -1. Initialize prev to nullptr and current to the head of the original linked list. -2. Enter a while loop that terminates when current is nullptr. -3. Inside the while loop, do the following: - - Store the next node in the original linked list in next. - - Update the next pointer of the current node to point to the previous node. - - Update the prev pointer to point to the current node. - - Update the current pointer to point to the next node. -4. Return prev, which is now the head of the reversed linked list. - ---- - -### Imlementation : - -```cpp -#include - -using std::cout, std::cin, std::endl; - -template class LinkedListNode { -public: - T data; - LinkedListNode *next; - LinkedListNode(T data) { - this->data = data; - this->next = NULL; - } -}; - -// Solution :- -LinkedListNode *reverseLinkedList(LinkedListNode *head) { - - LinkedListNode *prev = nullptr; - LinkedListNode *current = head; - LinkedListNode *next = nullptr; - - while (current != nullptr) { - next = current->next; - current->next = prev; - prev = current; - current = next; - } - return prev; -} - -int main() { return 0; } -``` diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/temp.cpp b/Data-Structures/Linear-Data-Structures/Linked-List/temp.cpp deleted file mode 100644 index ea5c261..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/temp.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include - -using std::cout, std::endl; - -class Node { - public: - int data; - Node* next; - - Node(int data) { - this->data = data; - this->next = NULL; - } -}; - -void insertAtHead(Node*& head, int data) { - Node* temp = new Node(data); - temp->next = head; - head = temp; -} - -void insertAtTail(Node*& tail, int data) { - Node* temp = new Node(data); - tail->next = temp; - tail = temp; -} - -void insertAtPosition(Node*& head, Node*& tail, int pos, int data) { - Node* temp = head; - int cnt = 1; - - // if inserting at first pos - if (pos == 1) { - insertAtHead(head, data); - return; - } - - // if inserting at last pos - if (temp->next == NULL) { - insertAtTail(tail, data); - return; - } - - while (cnt < pos - 1) { - temp = temp->next; - cnt++; - } - - Node* nodeToInsert = new Node(data); - nodeToInsert->next = temp->next; - temp->next = nodeToInsert; -} - -void printLinkedList(Node*& head) { - Node* temp = head; - while (temp != NULL) { - cout << temp->data << " "; - temp = temp->next; - } - cout << endl; -} - -int main() { - Node* node1 = new Node(10); - - // create head and tail pointer. - Node* head = node1; - Node* tail = node1; - - cout << "Initial List : "; - printLinkedList(head); - - insertAtHead(head, 12); - - cout << "List after insertion at head : "; - printLinkedList(head); - - insertAtTail(tail, 13); - - cout << "List after insertion at tail : "; - printLinkedList(head); - - insertAtPosition(head, tail, 3, 14); - - cout << "List after insertion at 3rd position : "; - printLinkedList(head); - return 0; -} diff --git a/Data-Structures/Linear-Data-Structures/Linked-List/temp2.cpp b/Data-Structures/Linear-Data-Structures/Linked-List/temp2.cpp deleted file mode 100644 index b323f61..0000000 --- a/Data-Structures/Linear-Data-Structures/Linked-List/temp2.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include -#include - -using std::cout, std::endl, std::vector; - -class Node { - public: - // node members - int data; // data - Node* next; // pointer - - // constructor - Node(int data1) { - data = data1; - next = nullptr; - } -}; - -int main() { - vector arr = {2, 3, 4, 6, 3}; - const Node* n1 = new Node(arr[1]); - cout << n1->data << endl; - cout << n1->next << endl; - return 0; -} diff --git a/Data-Structures/Trees/01-intro.md b/Data-Structures/Trees/01-intro.md deleted file mode 100644 index 2cc7686..0000000 --- a/Data-Structures/Trees/01-intro.md +++ /dev/null @@ -1,33 +0,0 @@ -## Tress - A hierarchical Data Structure - -Trees are hierarchical data structures consisting of nodes. - -A tree consists of root node, parent nodes, children nodes, leaf-nodes, sub-tree and ancestors. - -``` - 1 <-- root node - / \ - 2 3 <-- Child node - / \ / \ - 4 5 6 7 - / / \ - 8 9 10 <-- Leaf node -``` - ---- - -### Binary Search Tree - -A Binary tree is a type of tree where each parent node consists of at **max 2** child nodes. - -**Types of Binary tree :** - -1. **Fully Binary tree :** Every node will either have 0 or 2 children nodes. - -2. **Complete Binary Tree :** All levels of tree should be completely filled. If not completely filled, then the last level should have all nodes as left as possible. - -3. **Perfect Binary Tree :** All leaf nodes are at same level. - -4. **Balnced Binary Tree :** The tree can at max have a height of **Log2(n)**, where n is number of nodes. For every node, height(left sub-tree) - height(right sub-tree) <= 1. - -5. **Degenerate Tree :** When every node only have a single child or parent node. This type resembles to a Linked List. diff --git a/Data-Structures/Trees/02-basics.md b/Data-Structures/Trees/02-basics.md deleted file mode 100644 index 07dc610..0000000 --- a/Data-Structures/Trees/02-basics.md +++ /dev/null @@ -1,39 +0,0 @@ -## Representation of a Tree in C++ - -``` - 1 <-- data - left pointer --> / \ <-- right pointer - 2 3 - / \ - 4 NULL -``` - ---- - -### Implementation : - -```cpp -struct Node { - int data; - struct Node* left; - struct Node* right; - // constructor - Node(int value) { - data = value; - left = right = NULL; // initially pointing to null - } -} - -// Tree Creation -int main() { - // calling constructor and passing root's value. - struct Node* root = new Node(1); - - root->left = new Node(2); - root->right = new Node(3); - - root->left->left = new Node(4); - - return 0; -} -``` diff --git a/Data-Structures/Trees/03-travsersals.md b/Data-Structures/Trees/03-travsersals.md deleted file mode 100644 index b2147d1..0000000 --- a/Data-Structures/Trees/03-travsersals.md +++ /dev/null @@ -1,66 +0,0 @@ -## Traversing in a Tree - -There are two ways to traverse in a Binary search tree : - -1. **Depth-First-Search [DFS] :** - In this method, the tree is traversed through it's entire height / length. - - There are 3 types of DFS :- - -a. _In-order Traversal_ (left-**root**-right) : Start form the root, if there exists a left, go left, if no further left, print left, go back, print the root and now look for right, if right exists, apply the same logic. - -``` - 1 - / \ - 2 3 - / \ / \ - 4 5 6 7 - / / \ - 8 9 10 -``` - -In above BST, if we apply In-order traversal, we get : - -``` -4 2 8 5 1 6 3 9 7 10 -``` - ---- - -b. _Pre-Order-Traversal_ (**root**-left-right) : Start from the root, print root, if left exists, go left & print left, if no further left, go back, check for right, if right exists, apply the same logic. - -In above BST, if we apply Pre-order traversal, we get : - -``` -1 2 4 5 8 3 6 7 9 10 -``` - ---- - -c. _Post-Order-Traversal_ (left-right-**root**) : Start from the root, if left exists, go to left, print left, if no further left, go back, check if right exists, if exists print right, go back and print root. - -In above BST, if we apply Pre-order traversal, we get : - -``` -4 5 8 2 6 7 9 10 7 3 1 -``` - ---- - -2. **Breadth-first-Search [BFS] :** In this method, we traverse the tree level by level, through it's entire breadth. - -``` - --> 1 - / \ - --> 2 3 - / \ / \ - --> 4 5 6 7 - / / \ - --> 8 9 10 -``` - -**BFS in Above Tree :** - -``` -1 2 3 4 5 6 7 8 9 10 -``` diff --git a/Data-Structures/Trees/04-in-order-recur.md b/Data-Structures/Trees/04-in-order-recur.md deleted file mode 100644 index c27f044..0000000 --- a/Data-Structures/Trees/04-in-order-recur.md +++ /dev/null @@ -1,26 +0,0 @@ -## In-Order-Traversal ~ Recursive approach C++ Implementation - -``` - 1 - / \ - 2 3 - / \ / \ - 4 5 6 7 - / / \ - 8 9 10 -``` - -### Implementation : - -```cpp -void inorder(int node) { - if (node == NULL) { // base case - return; - } - inorder(node->left); // recursion - cout << node->data << endl; - inorder(node->right); // recursion -} -``` - -pattern : left --> print --> right diff --git a/Data-Structures/Trees/05-pre-order-recur.md b/Data-Structures/Trees/05-pre-order-recur.md deleted file mode 100644 index de296ed..0000000 --- a/Data-Structures/Trees/05-pre-order-recur.md +++ /dev/null @@ -1,26 +0,0 @@ -## Pre-Order-Traversal ~ Recursive approach C++ Implementation - -``` - 1 - / \ - 2 3 - / \ / \ - 4 5 6 7 - / / \ - 8 9 10 -``` - -### Implementation : - -```cpp -void preorder(int node) { - if (node == NULL) { // base case - return; - } - cout << node->data << endl; - preorder(node->left); // recursion - preorder(node->right); // recursion -} -``` - -pattern : print --> left --> right diff --git a/Data-Structures/Trees/06-post-order-recur.md b/Data-Structures/Trees/06-post-order-recur.md deleted file mode 100644 index 0bac0e2..0000000 --- a/Data-Structures/Trees/06-post-order-recur.md +++ /dev/null @@ -1,26 +0,0 @@ -## Post-Order-Traversal ~ Recursive approach C++ Implementation - -``` - 1 - / \ - 2 3 - / \ / \ - 4 5 6 7 - / / \ - 8 9 10 -``` - -### Implementation : - -```cpp -void postorder(int node) { - if (node == NULL) { // base case - return; - } - postorder(node->left); // recursion - postorder(node->right); // recursion - cout << node->data << endl; -} -``` - -pattern : left --> right --> print diff --git a/Data-Structures/Trees/07-level-order.md b/Data-Structures/Trees/07-level-order.md deleted file mode 100644 index 508b7de..0000000 --- a/Data-Structures/Trees/07-level-order.md +++ /dev/null @@ -1,152 +0,0 @@ -## Level Order Traversal [BFS] C++ Implementation - -==> We'll need two data sructures, A queue and a vector of vectors. - ---> The Queue will hold the roots of tree. - ---> vector will hold the levels - -Step 1 : Push the root node of the tree to the queue. - -Step 2: Check if there exists any left or right branch for that node. - -Step 3: If there exists any left or right, push them to queue. - -Step 4: Once performed Step 2 & 3 for a node, push that node into the vector. - -Step 5 : Now iterate over the next queue elements and take them out, and repeat from Step 2. Check for their left and right, push their left / right to the queue and finally push the previous queue elements into the vector - ---- - -Example : - -``` - --> 1 - / \ - --> 2 3 - / \ / \ - --> 4 5 6 7 -``` - -Step 1 : - -The queue becomes : - -``` -1 -``` - -Step 2, Step 3 : Root node 1 has child nodes 2 and 3 as it's left and right, so push them to the queue. - -The queue becomes : - -``` -1 2 3 -``` - -Step 4 : - -Push Root node 1 into the vector. - -The vector becomes : - -``` -1 -``` - -Step 5 : - -Once we've performed these operations for Node 1, take child node 2 and 3 out of the queue and check if they have any left / right child nodes. - -2 and 3 have 4 5 6 7 as their child nodes, push them to the queue. - -The queue becomes : - -``` -1 2 3 4 5 6 7 -``` - -Now Push the child nodes 2 & 3 into the vector. - -The vector becomes : - -``` -1, 2 3 -``` - -Once we've performed these operations for Child nodes 2 & 3, take child node 4, 5, 6 and 7 out of the queue and check if they have any left / right child nodes. - -4 5 6 7 doesn't have any child nodes to push into the queue, so push them to the vector - -The vector becomes : - -``` -1, 2 3, 4 5 6 7 -``` - -**So the Level order traversal prints `1 2 3 4 5 6 7`** - ---- - -![Visualization](https://github.com/Rishabh672003/Programming-Notes/assets/53911515/596d45d5-7510-4b23-946b-215811a55ab0) - ---- - -### Approach : - -- Declare a vector of vectors (ans). -- if root == NULL, return ans. -- declare a queue, push the root into it. -- while the queue is not empty, -- calculate it's size to traverse. -- declare a vector to store levels (levels). -- traverse the current nodes inside the queue. -- declare a node and initialize it to q.front(). -- pop the node out of the queue and check if it's left and right exists. -- If exists, push them to queue -- push the node's value into the (level) vector. -- push the (level) vector to (ans) vector. - ---- - -### Implementation : - -```cpp -/* Defination for binary tree : -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x): val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), -right(right) {} -} -*/ - -class Solution { - public: - vector> levelOrder(TreeNode* root) { - vector> ans; // vector of vector - if (root == NULL) - return ans; - queue q; // queue - q.push(root); - while (!q.empty()) { - int size = q.size(); - vector level; - for (int i = 0; i < size; i++) { - TreeNode* node = q.front(); - q.pop(); - if (node->left != NULL) - q.push(node->left); - if (node->right != NULL) - q.push(node->right); - level.push_back(node->value); - } - ans.push_back(level); - } - return ans; - } -}; -``` diff --git a/Data-Structures/Trees/08-in-order-iterative.md b/Data-Structures/Trees/08-in-order-iterative.md deleted file mode 100644 index 6abab3a..0000000 --- a/Data-Structures/Trees/08-in-order-iterative.md +++ /dev/null @@ -1,113 +0,0 @@ -## In order traversal ~ Iterative Approach - ---> In this approach, we'll need an auxillary stack space and the stack will hold the upcoming nodes. - -**Approach :** - -1. Take the node, if it's not NULL, push it into the stack. -2. If there exists a left, take it and push it to the stack. -3. If encounter a NULL, no need to move left any further. -4. Pop out the first element form the stack and print it. -5. As per the logic (left-root-right), we'll check for the right of current node. -6. If right is not NULL, check for further left. -7. If right is NULL, pop out the next element from the stack. -8. Once the stack gets empty, the iteration gets over. - ---- - -**Example :** - -``` - 1 - / \ - 2 3 - / \ - 4 5 - / \ - 6 7 -``` - -1. Take node 1 and push it into stack. - -Stack becomes : - -``` -1 -``` - -2. Node 2 is left of the node 1, push it into the stack. Node 4 is left of the node 2, so push it too. - -Stack becomes : - -``` -4 -2 -1 -``` - -3. Now, node 4 has a NULL left node, so pop out the node 4 from the stack. - -Stack becomes : - -``` -2 -1 -``` - -4. Also node 4 has a NULL right node, so pop out the node 2 from the stack. - -Stack becomes : - -``` -1 -``` - -5. Now go to the right of node 2 and check for the left node, if exists, push it into the stack, if doesn't exist pop out the latest node from the stack. - ---- - -![pre-order-itr](https://github.com/Rishabh672003/Programming-Notes/assets/53911515/81e7bd40-4e9e-4023-b399-b832d04aab2f) - ---- - -### Implementation : - -```cpp -/* Defination for binary tree : -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x): val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), -right(right) {} -} -*/ - -class Solution { - public: - vector inorderTraversal(TreeNode* root) { - - stack st; // declare a stack - vector ans; // declare an answer vector - - TreeNode* node = root; // take the root node - - while (true) { - if (node != NULL) { // if not null - st.push(node); // push into the stack - node = node->left; // go to left - } else { - if (st.empty() == true) - break; - node = st.top(); // if null, - st.pop(); // pop the node out - ans.push_back(node->val); // push it to ans vector - node = node->right; // now check for right - } - } - return ans; - } -}; -``` diff --git a/Data-Structures/Trees/09-pre-order-iterative.md b/Data-Structures/Trees/09-pre-order-iterative.md deleted file mode 100644 index fe629c5..0000000 --- a/Data-Structures/Trees/09-pre-order-iterative.md +++ /dev/null @@ -1,55 +0,0 @@ -## Pre Order traversal ~ Iterative Approach - -**Approach :** - -1. Take the root and push it into the stack. -2. Start the Stack iteration, pop the top most element out and push it to the answer vector, then check if it has any left or right. -3. If left or right not NULL, first push right then left into the stack. -4. The stack iteration continues, pop the top most (left) element out and push it to the answer vector, then check if it has any left or right. -5. Continue the iteration untill the stak gets empty. - -![pre-order-itr](https://github.com/Rishabh672003/Programming-Notes/assets/53911515/eb403e15-29ca-410a-913b-b9f79822c59a) - -### Implementation : - -```cpp -/* Defination for binary tree : -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x): val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), -right(right) {} -} -*/ - -class Solution { - public: - vector preorder(TreeNode* root) { - - vectro ans; - if (root == NULL) - return ans; - - stack st; - st.push(root); - - while (!st.empty()) { - - root = st.top(); - st.pop(); - ans.push_back(root->val); - - if (root->right != NULL) { - st.push(root->right); - } - if (root->left != NULL) { - st.push(root->left); - } - } - return ans; - } -}; -``` diff --git a/Data-Structures/Trees/10-post-order-twoStack.md b/Data-Structures/Trees/10-post-order-twoStack.md deleted file mode 100644 index d30b55a..0000000 --- a/Data-Structures/Trees/10-post-order-twoStack.md +++ /dev/null @@ -1,65 +0,0 @@ -## Post Order Traversal ~ Two stack iteration - -**Approach :** - -1. Declare Two empty stacks. Push root of the tree into st1. - -2. Start the st1 iteration, pop the top most element into st2. - -3. Now if the top element of st2 has a left or right, push them into st1. - -4. The iteration continues, pop the top most element into st2, check if it has left or right, push the left / right into st1. - -5. The iteration stops when st1 gets empty. - -6. When st1 gets empty, pop out all the element from st2 into answer vector. - -### Implementation - -```cpp -/* Definition for binary tree : -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x): val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), -right(right) {} -} -*/ - -class Solution { - public: - vector postOrderTwoStack(TreeNode* root) { - - vector ans; - if (root == NULL) - return and; - - stack st1, st2; - st1.push(root); - - while (!st1.empty()) { - - root = st1.top(); - st1.pop(); - st2.push(root); - - if (root->left != NULL) { - st1.push(root->left); - } - if (root->right != NULL) { - st1.push(root->right); - } - } - - while (!st2.empty()) { - ans.push_back(st2.top()->val); - st2.pop(); - } - - return ans; - } -} -``` diff --git a/Data-Structures/Trees/11-post-order-oneStack.md b/Data-Structures/Trees/11-post-order-oneStack.md deleted file mode 100644 index b26c651..0000000 --- a/Data-Structures/Trees/11-post-order-oneStack.md +++ /dev/null @@ -1,49 +0,0 @@ -## Post Order Traversal ~ One Stack Iteration - -```cpp -/* Defination for binary tree : -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x): val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), -right(right) {} -} -*/ - -class Solution { - public: - vector postOrderOneStack(TreeNode* root) { - vector ans; - if (root == NULL) - return ans; - - TreeNode* curr = root; - TreeNode* temp = NULL; - stack st; - - while (curr != NULL || !st.empty()) { - if (curr != NULL) { - st.push(curr); - curr = curr->left; - } else { - temp = st.top()->right; - if (temp == NULL) { - temp = st.top(); - st.pop(); - ans.push_back(temp); - while (!st.empty()&& temp = st.top()->right) { - temp = st.top(); - st.pop(); - ans.push_back(temp); - } - } else { - curr = temp; - } - } - } - } -} -``` diff --git a/Data-Structures/Trees/problems/check-for-balanced-bt.cpp b/Data-Structures/Trees/problems/check-for-balanced-bt.cpp deleted file mode 100644 index b8d9dbd..0000000 --- a/Data-Structures/Trees/problems/check-for-balanced-bt.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include -using namespace std; - -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode() : val(0), left(nullptr), right(nullptr) {} - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - TreeNode(int x, TreeNode *left, TreeNode *right) - : val(x), left(left), right(right) {} -}; - -class Solution { -public: - // a function to check if tree is balanced or not on basis of it's height. - bool isBalanced(TreeNode *root) { return dfsHeight(root) != -1; } - - /* a function to calculate height of tree, if this function returns -1, - the tree is not balanced. The tree will always be balanced if this function - returns some non-negative height */ - - int dfsHeight(TreeNode *root) { - if (root == NULL) - return 0; - - int lh = dfsHeight(root->left); - if (lh == -1) - return -1; - - int rh = dfsHeight(root->right); - if (rh == -1) - return -1; - - // for a balanced BT, height(left sub-tree) - height(right sub-tree) <= 1 - if (abs(lh - rh) > 1) - return -1; - - return max(lh, rh) + 1; - } -}; - -int main() { - Solution solution; - - TreeNode *balancedTree = new TreeNode(1); - balancedTree->left = new TreeNode(2); - balancedTree->right = new TreeNode(3); - balancedTree->left->left = new TreeNode(4); - balancedTree->left->right = new TreeNode(5); - balancedTree->right->left = new TreeNode(6); - balancedTree->right->right = new TreeNode(7); - - bool isBalancedResult = solution.isBalanced(balancedTree); - cout << "tree balanced? " << (isBalancedResult ? "Yes" : "No") << endl; - return 0; -} diff --git a/Data-Structures/Trees/problems/count-leaves.cpp b/Data-Structures/Trees/problems/count-leaves.cpp deleted file mode 100644 index 11db24c..0000000 --- a/Data-Structures/Trees/problems/count-leaves.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include -using namespace std; - -struct TreeNode { - int val; - TreeNode* left; - TreeNode* right; - explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} -}; - -class Solution { - public: - int countLeaves(TreeNode* root) { - - if (root == NULL) - return 0; - if (root->left == NULL && root->right == NULL) - return 1; - - int leftLeaves = countLeaves(root->left); - int rightLeaves = countLeaves(root->right); - - return leftLeaves + rightLeaves; - } -}; - -int main() { - // Create a sample binary tree - TreeNode* root = new TreeNode(3); - root->left = new TreeNode(9); - root->right = new TreeNode(20); - root->right->left = new TreeNode(15); - root->right->right = new TreeNode(7); - - Solution solution; - - int result = solution.countLeaves(root); - cout << "Sum of left leaves: " << result << std::endl; - - return 0; -} diff --git a/Data-Structures/Trees/problems/depth-of-bt.cpp b/Data-Structures/Trees/problems/depth-of-bt.cpp deleted file mode 100644 index 7922044..0000000 --- a/Data-Structures/Trees/problems/depth-of-bt.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include -#include -using namespace std; - -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} -}; - -class Solution { -public: - int maxDepth(TreeNode *root) { - if (root == NULL) - return 0; - int lh = maxDepth(root->left); - int rh = maxDepth(root->right); - return 1 + max(lh, rh); // formula - } - int minDepth(TreeNode *root) { - if (root == NULL) - return 0; - - // if the tree is a skew tree - if (root->left == NULL && root->right != NULL) { - return minDepth(root->right) + 1; - } else if (root->left != NULL && root->right == NULL) { - return minDepth(root->left) + 1; - } - - // if a normal binary tree - int lh = minDepth(root->left); - int rh = minDepth(root->right); - return 1 + min(lh, rh); // formula - } -}; - -int main() { - TreeNode *root = new TreeNode(3); - root->left = new TreeNode(9); - root->right = new TreeNode(20); - root->right->left = new TreeNode(15); - root->right->right = new TreeNode(7); - - Solution solution; - - int maxDepth = solution.maxDepth(root); - int minDepth = solution.maxDepth(root); - std::cout << "Max Depth of tree : " << maxDepth << std::endl; - std::cout << "Min Depth of tree : " << minDepth << std::endl; - - return 0; -} diff --git a/Data-Structures/Trees/problems/diameter-of-bt.cpp b/Data-Structures/Trees/problems/diameter-of-bt.cpp deleted file mode 100644 index 4ff6df5..0000000 --- a/Data-Structures/Trees/problems/diameter-of-bt.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include -using namespace std; - -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} -}; - -/* -The diameter of a binary tree is the length of the longest path between any two -nodes in a tree. This path may or may not pass through the root. -The length of a path between two nodes is represented by the number of edges -between them. -*/ - -class Solution { -public: - int diameter = 0; - int diameterOfBinaryTree(TreeNode *root) { - height(root); - return diameter; - } - int height(TreeNode *node) { - if (!node) - return 0; - int lh = height(node->left); - int rh = height(node->right); - diameter = max(diameter, lh + rh); - return 1 + max(lh, rh); - } -}; - -int main() { - TreeNode *root = new TreeNode(3); - root->left = new TreeNode(9); - root->right = new TreeNode(20); - root->right->left = new TreeNode(15); - root->right->right = new TreeNode(7); - - Solution solution; - - int result = solution.diameterOfBinaryTree(root); - - cout << "Diameter of the binary tree: " << result << endl; - - delete root->left; - delete root->right->left; - delete root->right->right; - delete root; - - return 0; -} diff --git a/Data-Structures/Trees/problems/sum-of-left-leaves.cpp b/Data-Structures/Trees/problems/sum-of-left-leaves.cpp deleted file mode 100644 index 50c8c52..0000000 --- a/Data-Structures/Trees/problems/sum-of-left-leaves.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include -using namespace std; - -struct TreeNode { - int val; - TreeNode* left; - TreeNode* right; - explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} -}; - -class Solution { - public: - int sumOfLeftLeaves(TreeNode* root) { - if (root == NULL) - return 0; - - int sum = 0; - - // checking if the root has a left leaf - if (root->left != NULL && root->left->left == NULL && - root->left->right == NULL) { - sum += root->left->val; - } - - sum += sumOfLeftLeaves(root->left); - sum += sumOfLeftLeaves(root->right); - - return sum; - } -}; - -int main() { - TreeNode* root = new TreeNode(3); - root->left = new TreeNode(9); - root->right = new TreeNode(20); - root->right->left = new TreeNode(15); - root->right->right = new TreeNode(7); - - Solution solution; - - int result = solution.sumOfLeftLeaves(root); - std::cout << "Sum of left leaves: " << result << std::endl; - - return 0; -} diff --git a/Data-Structures/Trees/problems/symmetric-bt.cpp b/Data-Structures/Trees/problems/symmetric-bt.cpp deleted file mode 100644 index b800b9e..0000000 --- a/Data-Structures/Trees/problems/symmetric-bt.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include -using namespace std; - -struct TreeNode { - int val; - TreeNode *left; - TreeNode *right; - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} -}; - -/* -A symmetric binary tree is a binary tree where the left and right subtrees of -the root node are mirror images of each other. -*/ - -class Solution { -public: - bool isSymmetric(TreeNode *root) { - return root == NULL || helper(root->left, root->right); - } - bool helper(TreeNode *left, TreeNode *right) { - if (left == NULL || right == NULL) - return left == right; - if (left->val != right->val) - return false; - return helper(left->left, right->right) && helper(left->right, right->left); - } -}; - -int main() { - TreeNode *root = new TreeNode(1); - root->left = new TreeNode(2); - root->right = new TreeNode(2); - root->left->left = new TreeNode(3); - root->left->right = new TreeNode(4); - root->right->left = new TreeNode(4); - root->right->right = new TreeNode(3); - - Solution solution; - bool isSymmetric = solution.isSymmetric(root); - - if (isSymmetric) { - cout << "The tree is symmetric." << endl; - } else { - cout << "The tree is not symmetric." << endl; - } - - return 0; -} \ No newline at end of file diff --git a/Data-Structures/stl-reference.md b/Data-Structures/stl-reference.md deleted file mode 100644 index 8d7a701..0000000 --- a/Data-Structures/stl-reference.md +++ /dev/null @@ -1,14 +0,0 @@ -
- -# STL Quick Reference - -
- -![C++ STL Quick Reference (2)-1](https://user-images.githubusercontent.com/53911515/229293159-04ddf328-3bb5-4508-bfe1-7cff06d8a22b.jpg) -![C++ STL Quick Reference (2)-2](https://user-images.githubusercontent.com/53911515/229293161-f0618394-ec65-450f-b02c-97f318737dd4.jpg) -![C++ STL Quick Reference (2)-3](https://user-images.githubusercontent.com/53911515/229293162-db8f8a94-eb7b-4f4c-8c1b-3fe36a6d3239.jpg) -![C++ STL Quick Reference (2)-4](https://user-images.githubusercontent.com/53911515/229293164-4173335e-8083-4c13-8fd7-82111916244e.jpg) -![C++ STL Quick Reference (2)-5](https://user-images.githubusercontent.com/53911515/229293167-b347df15-77eb-4745-bbc6-47732416e8b8.jpg) -![C++ STL Quick Reference (2)-6](https://user-images.githubusercontent.com/53911515/229293168-b0fddfd3-9058-409c-bf78-cd1bc2c550bf.jpg) -![C++ STL Quick Reference (2)-7](https://user-images.githubusercontent.com/53911515/229293169-f090fc7e-a309-4407-a186-289434428433.jpg) -![C++ STL Quick Reference (2)-8](https://user-images.githubusercontent.com/53911515/229293172-383b17ed-4042-49f0-87fc-ee0f4b195056.jpg) diff --git a/JavaScript/01-intro.md b/JavaScript/01-intro.md deleted file mode 100644 index 62a40bf..0000000 --- a/JavaScript/01-intro.md +++ /dev/null @@ -1,96 +0,0 @@ -# Introduction : - -JavaScript does not use datatypes as opposed to c , c++ , Java. It has three initialisation techniques namely - -- let - -- var - -- const - -Semicolon " ; " is not essential to put at the end of every line but it is a good practice if you do so - ---- - -# Arrays - -```js -let arr = [1, 2, 3, 4]; - -//This creates an array of length 3, as the indexing starts from 0 , even though you can see four elements inside the array -``` - -## Adding elements in the front: - -```js -let arr = [1, 2, 3, 4]; -arr.unshift(-1, 0); - -//You can also use - -arr.concat(arr(-1, 0)); - -/*these techniques will add two elements in the beginning of the array -output: -[-1 , 0 , 1 , 2 , 3 , 4] */ -``` - ---- - -# Functions : - -### Different ways to declare a function: - -```js -function fn(){ } -//OR -const fn = function(){ } -//OR -const fn => { } -``` - -Here "fn" is the function name - ---- - -# **forEach** : - -- Creates a function for each element of an array -- It does not return a value - -```js -arr.forEach(function fn(arr) { - console.log(arr + 2); -}); -``` - -This will display each element of the array after adding 2 to them - ---- - -# **Map** : - -- This creates a new array consisting the functions of each element of other array - -```js -let arr1 = arr.map((item) => { - return item + 2; -}); -``` - -The values of array "arr" will increase by 2 and get returned to new array "arr1" - ---- - -# **Filter** : - -- It follows the boolean concept -- It creates a new array and puts only those values which fulfill the criteria mentioned by you - -```js -let f1 = arr.filter((arr) => { - return arr > 2; -}); - -// This will print only those numbers present in array "arr" which are greater than 2 -``` diff --git a/JavaScript/02-basics.md b/JavaScript/02-basics.md deleted file mode 100644 index ba7b723..0000000 --- a/JavaScript/02-basics.md +++ /dev/null @@ -1,79 +0,0 @@ -# JavaScript - Basics - -- JavaScript is used to program behaviour of pages. -- JavaScript Can Change HTML Content. -- JavaScript Can Change HTML Attribute Values. -- JavaScript Can Change HTML styles. -- JavaScript Can Hide HTML Elements. - ---- - -# Where to add JavaScript - -1. In -// Script tag can be added in - - tag or in - - tag. - - -``` - -2. In External .js File [ Without Script Tag ]. - -Exernal javascipt file is prefferd over all. - -- Easy to maintain and read -- Cached files can speed up page load. - ---- - -#