├── .gitignore
├── April 1st
└── April_1st.js
├── April 2nd
└── April_2nd.js
├── April 4th
└── April_4th.js
├── April 8th
└── arrays_objects.js
├── April-5th
├── April_5th.js
└── problem_solving_questions.pdf
├── April_11th
├── 2D-Array-Part-2.pdf
└── april_11th.js
├── April_13th
└── april_13th.js
├── April_14th
└── april_14th.js
├── April_20th
└── april_20th.js
├── April_21st
├── Recursion Problem Solving.pdf
└── april_21st.js
├── April_22nd
├── Recursion April 2022.pdf
└── april_22nd.js
├── April_29th
├── Asymptotic Analysis.pdf
└── april_29th.js
├── April_30th
├── Asymptotic analysis Part II.pdf
└── april_30th.js
├── April_9th
├── 2D-Arrays_Problem_Solving_Part_1.pdf
└── April_9th.js
├── July_13th
├── package.json
├── sum.js
└── tests
│ ├── sum.test.js
│ └── unit.test.js
├── June_1st
└── june_1st.js
├── June_20th
├── Object Relational Impedence Mismatch.pdf
├── package.json
├── using_mysql.js
└── using_sequelize.js
├── March 12th
├── BED -9th March-Lesson plan.pdf
├── BED-CO5 -11th March Deck.pptx.pdf
├── BED-CO5 -11th March- Lesson plan.pdf
├── USER APP.png
└── What is map and reduce.png
├── March 16th
├── BED-16th March- Deck.pdf
├── BED-16th March-Lesson Plan.pdf
├── Javascript_Class_Live_Examples
│ ├── .DS_Store
│ ├── index.html
│ ├── script.js
│ └── style.css
├── console_in_js.png
├── function fruitProcessor(apples, oranges).png
├── function_input_output.png
├── script.js
├── subtraction.png
└── uncalled_function.png
├── March 19th
└── code-examples
│ ├── conditional_statements.js
│ ├── index.html
│ ├── iterations.js
│ ├── operators.js
│ ├── operators_conditionals.js
│ └── style.css
├── March 20th - Doubt Session
├── Objects.js
├── arrays.js
├── functions.js
└── script.js
├── March 21st
├── class-examples
│ ├── functions.js
│ ├── index.html
│ └── style.css
└── march_21st.js
├── March 23rd
└── March_23rd.js
├── March 27th
└── March_27th.js
├── March 28th
├── BED-28th March-deck.pdf
└── March_28th.js
├── March 2nd
├── BED CO5-2nd Mar-Lesson Plan.pdf
├── BED-CO5-2nd March -Deck.pdf
├── What is Software Engineering.pdf
├── device_drivers.png
├── my_linkedin_profile.png
├── operating_system.png
├── software.png
├── software_engineering_jobs_US.png
├── software_engineering_jobs_india.png
├── system_softwares.png
├── types_of_system_software.png
└── web application architecture.png
├── March 30th
├── Bed-30th March-Deck.pdf
└── March_30th.js
├── March 4th
├── Notes for 4th March.pdf
├── chrome-javascript-features.png
├── node-javascript-features.png
├── test_project
│ ├── .vscode
│ │ └── settings.json
│ ├── index.html
│ ├── script.js
│ └── style.css
└── visualization of chrome and node.png
├── March 5th
├── $ Cassandra.png
├── Instructor Table.png
├── No Objection Certificate.pdf
├── Student Table.png
├── What is a database?.pdf
├── Who uses MongoDB.png
├── Who uses Oracle.png
├── Who uses PostgreSQL.png
├── document_store.jpeg
├── import mongoose from mongoose;.png
├── schemaless_database.png
├── uses MySQL.png
└── yrOuTxVLhpb3sdFHw4ihsaoNZuRrC8n-EcnH1rIxl3DivtwAgSxJJlCcnMIQNTzM2BmwHhHsD71EnB90Y95RpROw19DoEZc-6_Qfdvy79bScdnEe9AMFkLzspvNO.png
├── March 7th
├── 7th March Class.pdf
├── BED -7th March- Lesson Plan.pdf
├── BED -7th March- Pre-read.pdf
├── BED -7th March-Deckpptx.pdf
├── blocking.js
├── contents.json
├── hello_world_node.js
├── html-css-javascript-functions.png
├── html-css-javascript.png
├── html-css-js-as-parts-of-speech.png
├── node.js-definition.png
├── node.js
│ ├── blocking.js
│ ├── hello_node.txt
│ └── non_blocking.js
├── non-blocking.js
└── what-is-javascript.png
├── March 9th
├── When I wrote this code,.jpg
├── dynamic_typing_js.png
├── explain_undefined.png
├── javascript
│ ├── FunctionalProgrammingExamples.js
│ ├── index.html
│ ├── script.js
│ └── style.css
├── number_string_boolean.png
├── object_or_primitive_data_type.png
├── other_four_primitive_data_types.png
└── same_variable_different_data_type.png
├── May_23rd
├── app.js
├── async.txt
├── book.js
├── may_23rd.js
├── package-lock.json
└── package.json
├── May_25th
├── may_25th.js
└── tictactoe.js
├── May_27th
├── class_note.txt
├── countdown_timer_app
│ ├── index.html
│ ├── src
│ │ └── script.js
│ └── style.css
└── may_27th.js
├── May_2nd
└── may_2nd.js
├── May_30th
├── async_callback.js
├── class_note.txt
└── promises.js
├── May_4th
└── may_4th.js
├── May_6th
└── may_6th.js
├── May_7th
└── may_7th.js
├── May_9th
└── may_9th.js
├── Module - 3
├── AdvancedPS
│ ├── AggressiveCows.js
│ ├── Arrays
│ │ ├── BestTimeToBuySellStock.js
│ │ ├── ContainerWithMostWater.js
│ │ ├── FindMinimumInRotatedSortedArray.js
│ │ └── MaximumSubarraySum.js
│ ├── BookAllocation.js
│ ├── CountingSort.js
│ ├── FSD3-AdvancedPS
│ │ ├── ContainerWithMostWater.js
│ │ ├── FindTargetInRotatedSortedArray.js
│ │ ├── FindUniqueElement.js
│ │ ├── LCAInBST.js
│ │ ├── MaxDepthOfBinaryTree.js
│ │ ├── MaximizeProfitFromStock.js
│ │ ├── MaximumHeightPyramind.js
│ │ ├── MaximumSumSubarray.js
│ │ ├── SortArrayWithEquation.js
│ │ ├── SortNearlySortedArray.js
│ │ └── ThreeSum.js
│ ├── FindDuplicateInArray.js
│ ├── FindPairsThatSumToTarget.js
│ ├── FirstAndLastOccurenceOfANumberInArray.js
│ ├── HashMaps
│ │ ├── ContinuousSubarraySumToTarget.js
│ │ ├── HashTable.js
│ │ ├── Hashing.txt
│ │ ├── LongNonRepeatingSubstring.js
│ │ ├── SubarrayWithExactlyKDistinctIntegers.js
│ │ └── TestHashTable.js
│ ├── Heap
│ │ ├── LargestAreaHistogram.js
│ │ ├── MaxHeap.js
│ │ ├── MedianInAStreamOfIntegers.js
│ │ ├── MergeKSortedArrays.js
│ │ ├── PriorityQueue.js
│ │ ├── RearrangeStrings.js
│ │ ├── SortByFrequency.js
│ │ └── TestHeap.js
│ ├── IsBadVersion.js
│ ├── July25th-ArraysAndObjects.js
│ ├── July27th-ArraysAndObjects.js
│ ├── LinkedLists
│ │ ├── AddToLinkedLists.js
│ │ ├── Caches.txt
│ │ ├── CycleDetection-II.js
│ │ ├── CycleDetection.js
│ │ ├── IntersectionOfTwoLists.js
│ │ ├── LRUCache.js
│ │ ├── LinkedList.js
│ │ ├── MergeKSortedLists.js
│ │ ├── MergeTwoSortedLists.js
│ │ ├── MiddleOfALinkedList.js
│ │ ├── ReorderList.js
│ │ ├── ReverseList.js
│ │ ├── ReverseNodesInKGroups.js
│ │ ├── SortTriplets.js
│ │ ├── SortedLinkedListToBST.js
│ │ ├── SwapNodesInKPair.js
│ │ ├── SwapPairs.js
│ │ └── increment_operator_using_ll.js
│ ├── LongestIncreasingSubsequence-BS.js
│ ├── LongestIncreasingSubsequence-DP.js
│ ├── MedianOfTwoSortedArrays.js
│ ├── MeetingRooms-II.js
│ ├── MinimumCapacityToShipInDDays.js
│ ├── MinimumSizeSubarraySum.js
│ ├── MissingNumberInSortedArray.js
│ ├── NQueens.js
│ ├── PainterPartition.js
│ ├── Queues
│ │ ├── CircularTour.js
│ │ ├── Deque.js
│ │ ├── FirstNonRepeatingCharacter.js
│ │ ├── LemonadeChange.js
│ │ ├── Node.js
│ │ ├── OperationsOnDeque.js
│ │ ├── OperationsOnQueue.js
│ │ ├── PossibleToProvideChange.js
│ │ ├── PrintNumbersInBinaryFormat.js
│ │ ├── Queue.js
│ │ ├── QueueUsingStack.js
│ │ ├── ReverseFirstKElementsInQueue.js
│ │ └── SlidingWindowMaximum.js
│ ├── RadixSort.js
│ ├── RatInAMaze.js
│ ├── RelativeSortArray.js
│ ├── RevisionBinarySearch.js
│ ├── Sorting
│ │ ├── MaximumAbsoluteDifference.js
│ │ └── SortUsingStack.js
│ ├── SplitArrayLargestSum.js
│ ├── SquarefulArray.js
│ ├── Stacks
│ │ ├── AsteroidCollision.js
│ │ ├── InfixToPostfix.js
│ │ ├── MatchBrackets.js
│ │ ├── MaximumOfMinimumOfAllWindowSizes.js
│ │ ├── MinimumDeletionsToBalanceString.js
│ │ ├── NextGreaterElement-II.js
│ │ ├── NextGreaterElement.js
│ │ ├── RecursivelyReverseStack.js
│ │ ├── RemoveAllAdjacentDuplicates.js
│ │ ├── RemoveKDigits.js
│ │ ├── Stack.txt
│ │ ├── SumOfSubarrayMinimums.js
│ │ ├── ValidParenthesis.js
│ │ └── stack.js
│ ├── ThreeSum.js
│ ├── Trees
│ │ └── Binary
│ │ │ ├── AverageOfLevels.js
│ │ │ ├── BinaryTree.js
│ │ │ ├── ConstructTreeFromPreAndInorder.js
│ │ │ ├── DistanceOfNodeFromRoot.js
│ │ │ ├── FindLeavesGivenPreorderTraversalOfBST.js
│ │ │ ├── FindRootToNodePath.js
│ │ │ ├── LevelOrderTraversal.js
│ │ │ ├── LowestCommonAncestor.js
│ │ │ ├── Node.js
│ │ │ ├── NodesAtKDistance.js
│ │ │ ├── RightViewOfABinaryTree.js
│ │ │ └── TreeTraversals.js
│ ├── TwoSum.js
│ └── binary_search_simple.js
└── FE-7-AdvancedPS
│ ├── Heap
│ ├── KthSmallestElement.js
│ ├── MaxHeap.js
│ ├── MedianInAStreamOfIntegers.js
│ ├── MergeKSortedArrays.js
│ ├── PriorityQueue.js
│ ├── RearrangeString.js
│ ├── SortArrayByFrequency.js
│ ├── TaskScheduler.js
│ └── TestMaxHeap.js
│ ├── Queue
│ ├── FirstNegativeInWindow.js
│ ├── GasStation.js
│ ├── LemonadeChange.js
│ ├── Queue.js
│ └── ValidateStackSequence.js
│ ├── Stack
│ ├── LargestRectangleHistogram.js
│ ├── MinimumDeletions.js
│ ├── RemoveKdigits.js
│ └── TrappingRainWater.js
│ └── TryCatch
│ └── Exception.js
├── PasswordHashing
├── hash-password.js
└── package.json
├── index.html
└── jwt-demo
├── package.json
└── server.js
/.gitignore:
--------------------------------------------------------------------------------
1 | *node_modules/
2 |
--------------------------------------------------------------------------------
/April-5th/problem_solving_questions.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April-5th/problem_solving_questions.pdf
--------------------------------------------------------------------------------
/April_11th/2D-Array-Part-2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April_11th/2D-Array-Part-2.pdf
--------------------------------------------------------------------------------
/April_21st/Recursion Problem Solving.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April_21st/Recursion Problem Solving.pdf
--------------------------------------------------------------------------------
/April_22nd/Recursion April 2022.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April_22nd/Recursion April 2022.pdf
--------------------------------------------------------------------------------
/April_29th/Asymptotic Analysis.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April_29th/Asymptotic Analysis.pdf
--------------------------------------------------------------------------------
/April_29th/april_29th.js:
--------------------------------------------------------------------------------
1 | function foo(n) {
2 | let a = 0;
3 | if(n == 0) {
4 | a = 2;
5 | } else {
6 | a = 2 * foo(n-1);
7 | }
8 | bar(a);
9 | return a;
10 | }
11 |
12 | function bar(m) {
13 | for(let i = m; i > 1; i /= 2);
14 | }
--------------------------------------------------------------------------------
/April_30th/Asymptotic analysis Part II.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April_30th/Asymptotic analysis Part II.pdf
--------------------------------------------------------------------------------
/April_30th/april_30th.js:
--------------------------------------------------------------------------------
1 | /*
2 | [48]
3 | [20, 28]
4 | [8, 12, 16]
5 | [3, 5, 7, 9]
6 | [1, 2, 3, 4, 5]
7 | */
8 |
9 | function arrSum(arr) {
10 | if(arr.length === 0) {
11 | return;
12 | }
13 | const newArr = [];
14 | for(let i = 0; i < arr.length - 1; i++) {
15 | newArr[i] = arr[i] + arr[i+1];
16 | }
17 | arrSum(newArr);
18 | console.log(arr);
19 | }
20 |
21 | /*
22 | In Recursion basically there are kinds.
23 | 1. the larger values are dependent on the following recursions. eg: fibonacci.
24 | 2. the subseequent recursions are dependent on the previous recursion.
25 | */
--------------------------------------------------------------------------------
/April_9th/2D-Arrays_Problem_Solving_Part_1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/April_9th/2D-Arrays_Problem_Solving_Part_1.pdf
--------------------------------------------------------------------------------
/July_13th/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "july_13th",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "jest"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "devDependencies": {
13 | "jest": "^28.1.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/July_13th/sum.js:
--------------------------------------------------------------------------------
1 | exports.sum = (a, b) => {
2 | return a + b;
3 | }
--------------------------------------------------------------------------------
/July_13th/tests/sum.test.js:
--------------------------------------------------------------------------------
1 | const { expect } = require("expect")
2 | const { sum } = require("../sum")
3 |
4 | test('testing sum', () => {
5 | var result = sum(2, 3);
6 | expect(result).toBe(5);
7 | })
--------------------------------------------------------------------------------
/July_13th/tests/unit.test.js:
--------------------------------------------------------------------------------
1 | const { expect } = require("expect");
2 |
3 | test('Testing an object', () => {
4 | const data = {
5 | name: 'hello',
6 | phone: '9999999999'
7 | }
8 | expect(data).toEqual({name: 'hello', phone: '9999999999'});
9 | })
10 |
11 | test('null', () => {
12 | const n = undefined;
13 | // expect(n).toBeNull();
14 | // expect(n).toBeDefined();
15 | expect(n).toBeUndefined();
16 | // expect(n).toBeTruthy();
17 | expect(n).toBeFalsy();
18 | })
19 |
20 | test('aaaaab has aab', () => {
21 | expect('aaaaab').toMatch(/aaab/);
22 | })
23 |
24 | const shoppingList = [
25 | 'diapers',
26 | 'kleenex',
27 | 'trash bags',
28 | 'paper towels',
29 | 'milk',
30 | ];
31 |
32 | test('arrays and iterables', () => {
33 | expect(shoppingList).toContain('milk')
34 | expect(shoppingList).not.toContain('paper');
35 | })
36 |
37 |
38 | function throwError() {
39 | throw new Error('Failed in processing request');
40 | }
41 |
42 | test('exceptions', () => {
43 | expect(() => throwError()).toThrow(Error);
44 | })
45 |
46 |
47 | const asyncAdd = (a, b) => {
48 | return new Promise((resolve, reject) => {
49 | setTimeout(() => {
50 | if(a < 0 || b < 0) {
51 | reject('numbers must be positive');
52 | }
53 | resolve(a + b);
54 | }, 2000)
55 | })
56 | }
57 |
58 | test('asynchronous function', (done) => {
59 | setTimeout(() => {
60 | expect(1).toBe(1)
61 | done();
62 | }, 2000);
63 | })
64 |
65 | test('promised based with return', () => {
66 | return asyncAdd(4, 5).then(sum => {
67 | expect(sum).toBe(9);
68 | });
69 | })
70 |
71 | test('promise based with async/await', async () => {
72 | const sum = await asyncAdd(4, 5);
73 | expect(sum).toBe(9);
74 | });
75 |
76 | test('promise based with done', (done) => {
77 | asyncAdd(4, 5).then(sum => {
78 | expect(sum).toBe(9);
79 | done();
80 | })
81 | })
--------------------------------------------------------------------------------
/June_20th/Object Relational Impedence Mismatch.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/June_20th/Object Relational Impedence Mismatch.pdf
--------------------------------------------------------------------------------
/June_20th/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "june_20th",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "learning_sequelize.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "mysql2": "^2.3.3",
14 | "sequelize": "^6.21.0"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/June_20th/using_mysql.js:
--------------------------------------------------------------------------------
1 | const mysql = require('mysql2');
2 | const connection = mysql.createConnection({
3 | host: "127.0.0.1",
4 | user: "root",
5 | password: '',
6 | database: 'ecom_db'
7 | });
8 |
9 | connection.connect();
--------------------------------------------------------------------------------
/June_20th/using_sequelize.js:
--------------------------------------------------------------------------------
1 | /*
2 | https://sequelize.org/docs/v6/getting-started/ - let you set up a mysql server and validate
3 | CRUD operations.
4 | https://sequelize.org/docs/v6/core-concepts/model-basics/ - read through this module if possible.
5 |
6 | */
7 |
8 | const Sequelize = require('sequelize')
9 | const connection = new Sequelize(
10 | 'ecom_db',
11 | 'root',
12 | '',
13 | {
14 | host: "127.0.0.1",
15 | dialect: "mysql",
16 | pool: {
17 | max: 5,
18 | min: 1,
19 | acquire: 5000,
20 | idle: 10000
21 | }
22 |
23 | /*
24 | -------------------------------------
25 | | Conn1 | Conn2 | Conn3 | Conn4 |
26 | -------------------------------------
27 | */
28 | //tcp ports : souce_ip source_port dest_ip dest_port
29 | }
30 | );
31 |
32 | async function validateConnection() {
33 | try {
34 | await connection.authenticate();
35 | console.log('Connection has been established successfully!');
36 | } catch(error) {
37 | console.error('Unable to connect to database:', error);
38 | }
39 | }
40 |
41 | validateConnection();
--------------------------------------------------------------------------------
/March 12th/BED-CO5 -11th March Deck.pptx.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 12th/BED-CO5 -11th March Deck.pptx.pdf
--------------------------------------------------------------------------------
/March 12th/BED-CO5 -11th March- Lesson plan.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 12th/BED-CO5 -11th March- Lesson plan.pdf
--------------------------------------------------------------------------------
/March 12th/USER APP.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 12th/USER APP.png
--------------------------------------------------------------------------------
/March 12th/What is map and reduce.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 12th/What is map and reduce.png
--------------------------------------------------------------------------------
/March 16th/BED-16th March- Deck.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/BED-16th March- Deck.pdf
--------------------------------------------------------------------------------
/March 16th/BED-16th March-Lesson Plan.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/BED-16th March-Lesson Plan.pdf
--------------------------------------------------------------------------------
/March 16th/Javascript_Class_Live_Examples/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/Javascript_Class_Live_Examples/.DS_Store
--------------------------------------------------------------------------------
/March 16th/Javascript_Class_Live_Examples/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Backend-Cohort-Class
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/March 16th/Javascript_Class_Live_Examples/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | display: flex;
3 | justify-content: center;
4 | align-items: center;
5 | height: 100vh;
6 | margin: 0;
7 | background: rgb(77, 154, 77);
8 | font-family: 'Open Sans', sans-serif;
9 | font-size: 120%;
10 | }
11 |
12 | h1.header {
13 | color: aliceblue;
14 | }
--------------------------------------------------------------------------------
/March 16th/console_in_js.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/console_in_js.png
--------------------------------------------------------------------------------
/March 16th/function fruitProcessor(apples, oranges).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/function fruitProcessor(apples, oranges).png
--------------------------------------------------------------------------------
/March 16th/function_input_output.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/function_input_output.png
--------------------------------------------------------------------------------
/March 16th/subtraction.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/subtraction.png
--------------------------------------------------------------------------------
/March 16th/uncalled_function.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 16th/uncalled_function.png
--------------------------------------------------------------------------------
/March 19th/code-examples/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Backend-Cohort-Class
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/March 19th/code-examples/iterations.js:
--------------------------------------------------------------------------------
1 | console.log(`13 * 1 = ${13 * 1}`)
2 | console.log(`13 * 2 = ${13 * 2}`)
3 | console.log(`13 * 3 = ${13 * 3}`)
4 | console.log(`13 * 4 = ${13 * 4}`)
5 | console.log(`13 * 5 = ${13 * 5}`)
6 | console.log(`13 * 6 = ${13 * 6}`)
7 | console.log(`13 * 7 = ${13 * 7}`)
8 | console.log(`13 * 8 = ${13 * 8}`)
9 | console.log(`13 * 9 = ${13 * 9}`)
10 | console.log(`13 * 10 = ${13 * 10}`)
11 |
12 | for(let rep = 1; rep <= 10; rep = rep + 1) {
13 | console.log(`13 * ${rep} = ${13*rep}`);
14 | }
15 |
16 | let rep = 1;
17 | while(rep <= 10 ) {
18 | console.log(`13 * ${rep} = ${13*rep}`);
19 | rep += 1;
20 | }
21 |
22 | //-----while dice roll is not 6-------
23 |
24 | let dice = Math.trunc(Math.random() * 6) + 1;
25 | console.log(`You rolled a ${dice}`)
26 | while (dice !== 6) {
27 | console.log(`You rolled a ${dice}`)
28 | dice = Math.trunc(Math.random() * 6) + 1;
29 | }
--------------------------------------------------------------------------------
/March 19th/code-examples/operators.js:
--------------------------------------------------------------------------------
1 | //0, '', undefined, null, NaN
2 | console.log(Boolean(0))
3 | console.log(Boolean('0'))
4 | console.log(Boolean(Number('0')))
5 | console.log(Boolean(''))
6 | console.log(Number('Abhigyan'))
7 | console.log(typeof Infinity)
8 |
9 | let age = 32;
10 | console.log(age);
11 | age = 33;
12 | console.log(age);
13 |
14 | let children;
15 | children = 33;
16 | console.log(children);
17 |
18 | // -------- CONST -----------
19 |
20 | // const birthYear = '1990'
21 |
22 | const yearOfManufacture = undefined;
23 |
24 | // console.log(birthYear + " " + yearOfManufacture)
25 |
26 | let assigningConstToLet = yearOfManufacture;
27 | assigningConstToLet = 1992;
28 |
29 | var job = 'programmer'
30 | console.log(job)
31 | job = 'teacher'
32 | console.log(job)
33 |
34 | var undefinedVar;
35 | undefinedVar = 10;
36 |
37 |
38 | lastName = 'De'
39 | console.log(lastName)
40 |
41 | //-----------STRING LITERAL---------
42 | const firstName = 'Nayanava'
43 | const birthYear = '1990'
44 | const currentYear = '2022'
45 | const myJob = 'Software Engineer'
46 | // Hi I'm Nayanava, a 32 year old Software Engineer
47 | const aboutMe = "Hi I'm " + firstName + " a " +
48 | (currentYear - birthYear) + " year old " + myJob + "!";
49 |
50 | const aboutMeInStringAndTemplateLiterals =
51 | `Hi I'm ${firstName} a ${currentYear - birthYear} year old ${myJob}!`
52 | console.log(aboutMe)
53 | console.log(aboutMeInStringAndTemplateLiterals)
54 |
--------------------------------------------------------------------------------
/March 19th/code-examples/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | display: flex;
3 | justify-content: center;
4 | align-items: center;
5 | height: 100vh;
6 | margin: 0;
7 | background: rgb(77, 154, 77);
8 | font-family: 'Open Sans', sans-serif;
9 | font-size: 120%;
10 | }
11 |
12 | h1.header {
13 | color: aliceblue;
14 | }
--------------------------------------------------------------------------------
/March 20th - Doubt Session/arrays.js:
--------------------------------------------------------------------------------
1 | let friend1 = 'Samik';
2 | let friend2 = 'Rahul';
3 | let friend3 = 'Pranit';
4 | let friend4 = 'Abhishek';
5 | let friend5 = 'Vamshi';
6 |
7 | sendAnInvite(friend1);
8 | sendAnInvite(friend2);
9 | sendAnInvite(friend3);
10 | sendAnInvite(friend4);
11 | sendAnInvite(friend5);
12 |
13 | function sendAnInvite(friend) {
14 | console.log(`Hey! ${friend}, see you at my birthday party!`)
15 | }
16 |
17 | const friends = ['Samik', 'Rahul', 'Pranit', 'Abhishek', 'Vamshi'];
18 | console.log(friends);
19 |
20 | const friendsUsingConstructor = new Array('Samik', 'Rahul', 'Pranit');
21 | console.log(friendsUsingConstructor);
22 |
23 | const sequence = [1, 1, 2, 3, 5, 8, 13];
24 | const random = ['tree', 795, [0, 1, 2]];
25 |
26 | const shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
27 | console.log(shopping[0]);
28 | // returns "bread"
29 |
30 | shopping[0] = 'tahini';
31 | console.log(shopping);
32 | // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
33 |
34 |
35 | const aboutMe = [
36 | 'Nayanava', // -> 0
37 | 'De', // -> 1
38 | 1990, // -> 2
39 | ['Software Engineer', 'Teacher'], // -> 3
40 | ['Microsoft', 'Relevel By Unacademy'] // -> 4
41 | ]
42 |
43 | console.log(aboutMe[3][0]);
44 |
45 | const aboutMeObj = {
46 | firstName: "Nayanava",
47 | surname: "De",
48 | yearOfBirth: 1990,
49 | occupation: ['Software Engineer', 'Teacher'],
50 | organization: ['Microsoft', 'Relevel By Unacademy'],
51 |
52 | aboutMe : function() {
53 | return `I'm ${this.firstName} ${this.surname}. A ${this.occupation[0]} at ${this.organization[0]}`;
54 | }
55 | }
56 |
57 | aboutMeObj.firstName = 'Samik'
58 |
59 | console.log(aboutMe);
60 | console.log(aboutMeObj.aboutMe());
--------------------------------------------------------------------------------
/March 20th - Doubt Session/script.js:
--------------------------------------------------------------------------------
1 | console.log('script is loading')
2 | console.log(`let's see if this line prints`)
3 | console.log('hello')
4 |
5 | console.log(4 + 5)
6 |
7 | // !, +, -, typeof
8 | console.log( -'hello')
9 | console.log(!'')
10 |
11 | var one;
12 | var two = 'A'
13 | switch (two) {
14 | case 'A':
15 | one += '10';
16 | break;
17 | default:
18 | one += '0'
19 | }
20 | console.log(one)
21 |
22 |
23 | var i = 2, j = 2, k = 0;
24 | if(i == j) {
25 | console.log(i)
26 | }
27 |
28 | // if my input is 0, then add 10 first, for all cases add 5 to the input
29 |
30 | let input = 0;
31 |
32 | if(input === 0) {
33 | input += 10
34 | }
35 |
36 | input += 5;
37 | console.log(input)
38 |
39 | // if(i > 1) {
40 | // break;
41 | // }
42 |
43 | // nested for loop...
44 | /*
45 | 2 -> condition evaluation
46 | 3 -> updation of the counter
47 | */
48 | for(let i = 0; i < 5; i++) {
49 | for(let j = 0; j < 4; j++) {
50 | if(i > 1) {
51 | break;
52 | }
53 | console.log('Relevel ')
54 | }
55 | }
56 | /*
57 | Relevel Relevel Relevel Relevel
58 | Relevel Relevel Relevel Relevel
59 | Relevel Relevel Relevel Relevel
60 | Relevel Relevel Relevel Relevel
61 | Relevel Relevel Relevel Relevel
62 | */
--------------------------------------------------------------------------------
/March 21st/class-examples/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Backend-Cohort-Class
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/March 21st/class-examples/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | display: flex;
3 | justify-content: center;
4 | align-items: center;
5 | height: 100vh;
6 | margin: 0;
7 | background: rgb(77, 154, 77);
8 | font-family: 'Open Sans', sans-serif;
9 | font-size: 120%;
10 | }
11 |
12 | h1.header {
13 | color: aliceblue;
14 | }
--------------------------------------------------------------------------------
/March 21st/march_21st.js:
--------------------------------------------------------------------------------
1 | // //While loop
2 | // //condition
3 | // // let counter = 1;
4 | // // while(counter <= 10) {
5 | // // console.log(counter);
6 | // // counter++;
7 | // // }
8 |
9 | // //WE ARE TRYING TO GENERATE A RANDOM VALUE BETWEEN 1 TO 6
10 |
11 | // let diceRoll;
12 | // console.log(`Dice rolled to ${diceRoll}`);
13 |
14 | // do {
15 | // console.log(`Dice rolled to ${diceRoll}`);
16 | // //WE ARE TRYING TO GENERATE A RANDOM VALUE BETWEEN 1 TO 6
17 | // diceRoll = Math.trunc(Math.random() * 6) + 1;
18 | // } while(diceRoll !== 6);
19 |
20 | // console.log(`Dice rolled to ${diceRoll}`);
21 |
22 | // // let diceRoll = 6;
23 | // // do {
24 | // // console.log(`Value of dice roll is ${diceRoll}`)
25 | // // }while(diceRoll !== 6);
26 |
27 | // //---------------------------BREAK STATEMENT---------------------
28 |
29 | // let counter = 1;
30 | // while(true) {
31 | // if(counter === 5) {
32 | // break;
33 | // }
34 | // //let val = counter++;
35 | // console.log(`${counter++}`); //first assign then increment
36 | // }
37 |
38 | let numerator = 10;
39 | while(numerator > 0) {
40 | //we are trying to choose a value between 0 - 5
41 | let denominator = Math.trunc(Math.random() * 6);
42 | console.log(`denominator: ${denominator}`)
43 | if(denominator === 0) {
44 | break;
45 | }
46 | console.log(`${numerator--/denominator}`)
47 | }
48 | //------------CONTINUE--------------------
49 |
50 | numerator = 10;
51 | while(numerator > 0) {
52 | //we are trying to choose a value between 0 - 5
53 | let denominator = Math.trunc(Math.random() * 6);
54 | console.log(`denominator: ${denominator}`)
55 | numerator--;
56 | if(denominator === 0) {
57 | continue;
58 | }
59 | console.log(`${numerator/denominator}`)
60 | }
61 |
62 |
--------------------------------------------------------------------------------
/March 27th/March_27th.js:
--------------------------------------------------------------------------------
1 |
2 | console.log(number);
3 | var number = 10;
4 | const square = function (num) {
5 | var ans = num * num;
6 | return ans;
7 | }
8 | console.log(square(15));
9 | square = 10;
10 | var squareOf10 = square(number);
11 | var squareOf9 = square(9);
12 |
13 |
14 |
15 | console.log(squareOf10 + " " + squareOf9 + " " + ans);
16 |
17 |
18 | // Three steps
19 | // 1. initialization
20 | // 2. condition
21 | // 3. Modification
22 |
23 | // before the first iteration
24 | // initialization of the variable happens
25 | // and the condition is evaluated
26 |
27 | // after the first iteration
28 | // modification gets triggered first
29 | // condition gets evaluated.
30 |
31 | // counter++ => counter = counter + 1;
32 | // ++counter => counter = counter + 1;
33 | for(let counter = 1; counter++ <= 10; ) {
34 | // first check counter <= 10 and then counter = counter + 1;
35 | console.log(counter);
36 | }
37 |
38 | console.log("Inside pre-increment of for loop")
39 | for(let counter = 1; counter <= 10; counter++) {
40 | // first counter = counter + 1 and then check counter <= 10 ;
41 | console.log(counter);
42 | }
43 | // let counter = 1;
44 | console.log("Inside while loop")
45 | let counter = 1;
46 | while (counter++ <= 10) {
47 | console.log(counter);
48 | }
--------------------------------------------------------------------------------
/March 28th/BED-28th March-deck.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 28th/BED-28th March-deck.pdf
--------------------------------------------------------------------------------
/March 28th/March_28th.js:
--------------------------------------------------------------------------------
1 | //Temporal Dead Zone
2 |
3 | //console.log(constantVariable);
4 | // func();
5 | // var varVariable = 11;
6 | // let letVariable = 10;
7 | // //let letVariable = 20;
8 |
9 | // const constantVariable;
10 |
11 | // var varVariable = 13;
12 | // console.log(square(10));
13 |
14 | // var func = function() {
15 | // console.log("Testing type error");
16 | // }
17 | //TypeError:
18 | /*
19 | */
20 | //SyntaxError
21 |
22 | //ReferenceError:
23 |
24 | //------------ Block----------------
25 | {
26 | repeater();
27 | //var a = 5;
28 | let b = 10;
29 | const c = 20;
30 |
31 | function repeater() {
32 | // for(let i = 1; i <= 10; i++) {
33 | // console.log(i);
34 | // }
35 | }
36 | }
37 | //console.log(square(10));
38 | //console.log(a);
39 | repeater();
40 |
41 | //------- Scope Chain -------------
42 |
43 | // var a = 10;
44 | // function b() {
45 | // c();
46 | // function c() {
47 | // console.log(a);
48 | // }
49 | // }
50 |
51 | // b();
52 |
53 | //-------- Closures -------------
54 |
55 | function countIncrementer() {
56 | var counter = 10;
57 | return function() {
58 | ++counter;
59 | console.log(`value of counter : ${counter}`)
60 | }
61 | }
62 |
63 | const incrementCounter = countIncrementer();
64 | console.log(incrementCounter);
65 | incrementCounter();
66 | incrementCounter();
67 | incrementCounter();
68 |
69 |
--------------------------------------------------------------------------------
/March 2nd/BED CO5-2nd Mar-Lesson Plan.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/BED CO5-2nd Mar-Lesson Plan.pdf
--------------------------------------------------------------------------------
/March 2nd/BED-CO5-2nd March -Deck.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/BED-CO5-2nd March -Deck.pdf
--------------------------------------------------------------------------------
/March 2nd/What is Software Engineering.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/What is Software Engineering.pdf
--------------------------------------------------------------------------------
/March 2nd/device_drivers.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/device_drivers.png
--------------------------------------------------------------------------------
/March 2nd/my_linkedin_profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/my_linkedin_profile.png
--------------------------------------------------------------------------------
/March 2nd/operating_system.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/operating_system.png
--------------------------------------------------------------------------------
/March 2nd/software.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/software.png
--------------------------------------------------------------------------------
/March 2nd/software_engineering_jobs_US.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/software_engineering_jobs_US.png
--------------------------------------------------------------------------------
/March 2nd/software_engineering_jobs_india.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/software_engineering_jobs_india.png
--------------------------------------------------------------------------------
/March 2nd/system_softwares.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/system_softwares.png
--------------------------------------------------------------------------------
/March 2nd/types_of_system_software.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/types_of_system_software.png
--------------------------------------------------------------------------------
/March 2nd/web application architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 2nd/web application architecture.png
--------------------------------------------------------------------------------
/March 30th/Bed-30th March-Deck.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 30th/Bed-30th March-Deck.pdf
--------------------------------------------------------------------------------
/March 4th/Notes for 4th March.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 4th/Notes for 4th March.pdf
--------------------------------------------------------------------------------
/March 4th/chrome-javascript-features.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 4th/chrome-javascript-features.png
--------------------------------------------------------------------------------
/March 4th/node-javascript-features.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 4th/node-javascript-features.png
--------------------------------------------------------------------------------
/March 4th/test_project/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "liveServer.settings.port": 5501
3 | }
--------------------------------------------------------------------------------
/March 4th/test_project/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Weather App
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
23 |
24 |
25 |
Weather in Bengaluru
26 |
24°C
27 |
28 |

29 |
Haze
30 |
31 |
Humidity: 25%
32 |
Wind Speed: 3.6 kmph
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/March 4th/test_project/script.js:
--------------------------------------------------------------------------------
1 | let weather = {
2 | apiKey: "2d3aa7eb5d3cf4e429f6c85a67e1b355",
3 | fetchWeather: function(city) {
4 | fetch("https://api.openweathermap.org/data/2.5/weather?q="
5 | + city
6 | + "&appid=" + this.apiKey
7 | + "&units=metric")
8 | .then(response => response.json())
9 | .then(data => this.displayWeather(data))
10 | },
11 | displayWeather: function(data) {
12 | const {name} = data;
13 | const {icon, description} = data.weather[0];
14 | const { temp, humidity} = data.main;
15 | const { speed } = data.wind;
16 |
17 | document.querySelector(".city").innerText = "Weather in " + name;
18 | document.querySelector(".icon").src = "https://openweathermap.org/img/wn/" + icon + ".png"
19 | document.querySelector(".temp").innerText = temp
20 | document.querySelector(".humidity").innerText = "Humidity: " + humidity + "%";
21 | document.querySelector(".description").innerText = description;
22 | document.querySelector(".wind-speed").innerText = "Wind Speed: " + speed + " kmph";
23 |
24 | //console.log(name, icon, description, temp, humidity, speed)
25 | },
26 | weatherByCity: function () {
27 | const city = document.querySelector(".search-bar").value
28 | this.fetchWeather(city)
29 | }
30 | }
31 |
32 | document.querySelector(".search button").addEventListener("click", function() {
33 | weather.weatherByCity();
34 | })
35 |
36 | document.querySelector(".search-bar").addEventListener("keyup", function(event) {
37 | if(event.key == "Enter") {
38 | weather.weatherByCity()
39 | }
40 | })
--------------------------------------------------------------------------------
/March 4th/test_project/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | display: flex;
3 | justify-content: center;
4 | align-items: center;
5 | height: 100vh;
6 | margin: 0;
7 | background: #222;
8 | background-image: url('https://source.unsplash.com/1920x1080/?nature,water');
9 | font-family: 'Open Sans', sans-serif;
10 | font-size: 100%;
11 | }
12 |
13 | .card {
14 | background: #000000d0;
15 | color: white;
16 | padding: 2em;
17 | border-radius: 30px;
18 | width: 100%;
19 | max-width: 420px;
20 | margin: 1em;
21 | }
22 |
23 | .search {
24 | display: flex;
25 | align-items: center;
26 | justify-content: center;
27 | }
28 |
29 | .description {
30 | text-transform: capitalize;
31 | margin-left: 8px;
32 | }
33 |
34 | button {
35 | margin: 0.5em;
36 | border-radius: 50%;
37 | border: none;
38 | height: 3.3em;
39 | width: 3.3em;
40 | outline: none;
41 | background: #7c7c7c2b;
42 | color: white;
43 | cursor: pointer;
44 | transition: 0.2s ease-in-out;
45 | }
46 |
47 | button:hover {
48 | background: #7c7c7c6b;
49 | }
50 |
51 | input.search-bar {
52 | border: none;
53 | outline: none;
54 | padding: .7em;
55 | border-radius: 24px;
56 | background: #7c7c7c2b;
57 | color: white;
58 | font-family: inherit;
59 | font-size: 100%;
60 | width: calc(100% - 100px);
61 | }
62 |
63 | h1.temp {
64 | margin: 0;
65 | }
66 | .flex {
67 | display: flex;
68 | align-items: center;
69 | }
--------------------------------------------------------------------------------
/March 4th/visualization of chrome and node.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 4th/visualization of chrome and node.png
--------------------------------------------------------------------------------
/March 5th/$ Cassandra.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/$ Cassandra.png
--------------------------------------------------------------------------------
/March 5th/Instructor Table.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/Instructor Table.png
--------------------------------------------------------------------------------
/March 5th/No Objection Certificate.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/No Objection Certificate.pdf
--------------------------------------------------------------------------------
/March 5th/Student Table.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/Student Table.png
--------------------------------------------------------------------------------
/March 5th/What is a database?.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/What is a database?.pdf
--------------------------------------------------------------------------------
/March 5th/Who uses MongoDB.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/Who uses MongoDB.png
--------------------------------------------------------------------------------
/March 5th/Who uses Oracle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/Who uses Oracle.png
--------------------------------------------------------------------------------
/March 5th/Who uses PostgreSQL.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/Who uses PostgreSQL.png
--------------------------------------------------------------------------------
/March 5th/document_store.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/document_store.jpeg
--------------------------------------------------------------------------------
/March 5th/import mongoose from mongoose;.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/import mongoose from mongoose;.png
--------------------------------------------------------------------------------
/March 5th/schemaless_database.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/schemaless_database.png
--------------------------------------------------------------------------------
/March 5th/uses MySQL.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/uses MySQL.png
--------------------------------------------------------------------------------
/March 5th/yrOuTxVLhpb3sdFHw4ihsaoNZuRrC8n-EcnH1rIxl3DivtwAgSxJJlCcnMIQNTzM2BmwHhHsD71EnB90Y95RpROw19DoEZc-6_Qfdvy79bScdnEe9AMFkLzspvNO.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 5th/yrOuTxVLhpb3sdFHw4ihsaoNZuRrC8n-EcnH1rIxl3DivtwAgSxJJlCcnMIQNTzM2BmwHhHsD71EnB90Y95RpROw19DoEZc-6_Qfdvy79bScdnEe9AMFkLzspvNO.png
--------------------------------------------------------------------------------
/March 7th/7th March Class.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/7th March Class.pdf
--------------------------------------------------------------------------------
/March 7th/BED -7th March- Lesson Plan.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/BED -7th March- Lesson Plan.pdf
--------------------------------------------------------------------------------
/March 7th/BED -7th March-Deckpptx.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/BED -7th March-Deckpptx.pdf
--------------------------------------------------------------------------------
/March 7th/blocking.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | console.log("starting")
3 | const text = fs.readFileSync("./contents.json")
4 | console.log(new Buffer.from(text).toString())
5 | console.log("stopping")
--------------------------------------------------------------------------------
/March 7th/contents.json:
--------------------------------------------------------------------------------
1 | {"data":"Hello let's test out blocking and non-blocking I/O"}
--------------------------------------------------------------------------------
/March 7th/hello_world_node.js:
--------------------------------------------------------------------------------
1 | // const user = process.argv[2];
2 | // console.log("Hello " + user)
3 |
4 | const http = require('http')
5 | const url = require('url');
6 |
7 | http.createServer(function (request, response) {
8 | const queryObject = url.parse(request.url, true).query;
9 | console.log(queryObject);
10 | response.writeHead(200, {'Content-Type': 'text/plain'});
11 | response.end('Hello ' + queryObject.name);
12 | }).listen(3000);
--------------------------------------------------------------------------------
/March 7th/html-css-javascript-functions.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/html-css-javascript-functions.png
--------------------------------------------------------------------------------
/March 7th/html-css-javascript.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/html-css-javascript.png
--------------------------------------------------------------------------------
/March 7th/html-css-js-as-parts-of-speech.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/html-css-js-as-parts-of-speech.png
--------------------------------------------------------------------------------
/March 7th/node.js-definition.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/node.js-definition.png
--------------------------------------------------------------------------------
/March 7th/node.js/blocking.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | console.log('Starting application')
3 | const text = fs.readFileSync("./hello_node.txt")
4 | console.log(new Buffer.from(text).toString())
5 | console.log("Stopping application")
--------------------------------------------------------------------------------
/March 7th/node.js/hello_node.txt:
--------------------------------------------------------------------------------
1 | Hellow Class, welcome to the backend course
--------------------------------------------------------------------------------
/March 7th/node.js/non_blocking.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | console.log('Starting application')
3 |
4 | fs.readFile("./hello_node.txt", (err, data) => {
5 | if(err) {
6 | console.log(err);
7 | } else {
8 | console.log(new Buffer.from(data).toString())
9 | }
10 | })
11 | console.log("Stopping application")
--------------------------------------------------------------------------------
/March 7th/non-blocking.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | console.log("starting")
3 | const text = fs.readFile("./contents.json", (err, data) => {
4 | if(err) {
5 | console.log("Error in reading file")
6 | } else {
7 | console.log(new Buffer.from(data).toString())
8 | }
9 | })
10 | console.log("stopping")
--------------------------------------------------------------------------------
/March 7th/what-is-javascript.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 7th/what-is-javascript.png
--------------------------------------------------------------------------------
/March 9th/When I wrote this code,.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/When I wrote this code,.jpg
--------------------------------------------------------------------------------
/March 9th/dynamic_typing_js.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/dynamic_typing_js.png
--------------------------------------------------------------------------------
/March 9th/explain_undefined.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/explain_undefined.png
--------------------------------------------------------------------------------
/March 9th/javascript/FunctionalProgrammingExamples.js:
--------------------------------------------------------------------------------
1 | var globalVariable = 10
2 |
3 | function addToGlobalVariable(firstNumber, secondNumber, globalVariable) {
4 | return firstNumber + secondNumber + globalVariable
5 | }
6 |
7 | // for(var i = 1; i <= 5; i++) {
8 | // console.log(addToGlobalVariable(5, 5, 10) === 20)
9 | // globalVariable = Math.floor(Math.random() * 10) + 1
10 | // }
11 |
12 | var listOfSlicedSandwichIngredients = listOfSandwichIngredients.map(item => slice(item))
13 |
14 | var listOfFilteredSandwichIngredients =
15 | listOfSlicedSandwichIngredients.filter(item => item === 'Tomatoes')
16 | //console.log("Things are not working fine")
17 | var listOfPreparedSandwiches = listOfSlicedSandwichIngredients.reduce(() => prepareTheMagicSandwich())
18 |
19 |
20 | //When the offer was paid out - when a cashback was given to a customer
21 | var metrics = {
22 | "offerId": "OF12345678",
23 | "timeOfPayout": "12:03:2022 22:18:17",
24 | "count": 1
25 | }
26 |
27 | stopWatch.start()
28 | //make a call to api.weatherMap.com
29 | stopWatch.stop()
30 |
31 | metrics = {
32 | "apiName": "api.weatherMap.com",
33 | "tat": stopWatch.elapsedTime,
34 | "timeOfMetrics" : "2012:03:12 22:40:00"
35 | }
--------------------------------------------------------------------------------
/March 9th/javascript/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Backend Development
8 |
9 |
10 |
11 |
12 |
13 | Javascript Variables and DataTypes
14 |
15 |
--------------------------------------------------------------------------------
/March 9th/javascript/script.js:
--------------------------------------------------------------------------------
1 | console.log ('Jonas');
2 | console.log(23.0);
3 |
4 | let years = '';
5 | //variable names in javascript can only contain
6 | //numbers, letters, underscore(_)
7 | //or the dollar sign($)
8 |
9 | let htmlCssJs = 'frontend'
10 |
11 | let _new = 'new'
12 | let _function = 'function'
13 |
14 | let a = '.....';
15 |
16 | function addTwoValues(a, b) {
17 | return a+b
18 | }
19 |
20 | let myFirstJob = 'programmer'
21 | let myCurrentJob = 'teacher'
22 |
23 | let job1 = 'programmer'
24 | let job2 = 'teacher'
25 |
26 |
27 | function adjectify(adjective) {
28 |
29 | return function (noun) {
30 | return adjective + " " + noun
31 | }
32 | }
33 |
34 | console.log(adjectify("warm")('city'))
35 | var adjectify = adjectify('cool')
36 | console.log(adjectify('breeze'))
37 |
38 |
39 | var room = [1, 2, 3]
40 | console.log(typeof(room[2]))
41 | var newRoom = room.map(rm => {
42 | if(rm == '3') {
43 | return '4'
44 | } else {
45 | return rm
46 | }
47 | })
48 | console.log(typeof(newRoom[0]) + " " + typeof newRoom[2])
49 | console.log(newRoom)
50 | /*
51 | 8 bytes - 64 bits - (0 or 1)
52 |
53 | /*
54 | 0, 1, 2, 3 in binary
55 | 000 - 0
56 | 001 - 1
57 | 010 - 2
58 | 011 - 3
59 | 100 - 4
60 | 101 - 5
61 | 110 - 6
62 | 111 - 7
63 |
64 | 2 bits how many numbers could we uniquely identify?
65 | 4 0-3
66 | $ as 0 to (2^2 - 1)
67 | 8 - (0 to 2 ^ 3 -1)
68 |
69 | -2^63 - 1 to 2 ^ 63 - 1
70 |
71 | 0 (000)
72 | 0 = positive
73 | 1 = negative
74 | 1(111) to 0(111)
75 |
76 | */
--------------------------------------------------------------------------------
/March 9th/javascript/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | display: flex;
3 | justify-content: center;
4 | align-items: center;
5 | height: 100vh;
6 | margin: 0;
7 | background: green;
8 | font-family: 'Open Sans', sans-serif;
9 | font-size: 120%;
10 |
11 | }
12 |
13 | h1.main {
14 | color: white;
15 | }
--------------------------------------------------------------------------------
/March 9th/number_string_boolean.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/number_string_boolean.png
--------------------------------------------------------------------------------
/March 9th/object_or_primitive_data_type.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/object_or_primitive_data_type.png
--------------------------------------------------------------------------------
/March 9th/other_four_primitive_data_types.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/other_four_primitive_data_types.png
--------------------------------------------------------------------------------
/March 9th/same_variable_different_data_type.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/March 9th/same_variable_different_data_type.png
--------------------------------------------------------------------------------
/May_23rd/app.js:
--------------------------------------------------------------------------------
1 | /*
2 | List down features
3 | 1. register a user
4 | 2. user login
5 | 3. create book information
6 | 4. get some book
7 | 5. payment
8 | 6.
9 | 7. inventory of the book
10 | .
11 | .
12 | .
13 | */
14 | const bookObj = require('./book');
15 | const validator = require('validator');
16 |
17 | console.log(validator.isEmail("nayanava@example.com"));
18 | //console.log('inside app.js')
19 | console.log(bookObj);
20 | console.log(validator.isURL("http://google.com"));
--------------------------------------------------------------------------------
/May_23rd/async.txt:
--------------------------------------------------------------------------------
1 | Validating asynchronous code
--------------------------------------------------------------------------------
/May_23rd/book.js:
--------------------------------------------------------------------------------
1 | //console.log('Inside book.js');
2 |
3 | const book = {
4 | name: 'a tale of two cities',
5 | author: 'Charles Dickens',
6 | price: 150
7 | };
8 |
9 | module.exports = book;
--------------------------------------------------------------------------------
/May_23rd/may_23rd.js:
--------------------------------------------------------------------------------
1 | /* 1st node.js program
2 | //devmgmt.msc
3 | console.log('Hello World!!'); // - 1 ns
4 | //if I do some network operation - 10 ms -
5 | console.log('network operation completed'); // - 1ns
6 |
7 | // 1 ns + 1ns + 1ns
8 |
9 | */
10 | const fs = require('fs');
11 | console.log('starting');
12 |
13 | // setTimeout(() => {
14 | // console.log("Timer completed after 2 seconds")
15 | // }, 2000);
16 |
17 | // fs.writeFile('./async.txt', 'Validating asynchronous code', () => {
18 | // console.log("File has been printed asynchrnously");
19 | // });
20 |
21 | setTimeout(() => {
22 | console.log("Timer completed immediately");
23 | }, 0);
24 | setImmediate(() => {
25 | console.log("Called inside set Immediately");
26 | })
27 | console.log('stopping');
28 |
29 | /*
30 | A. starting, immediate, stopping, timer completed - true
31 | B. - starting, stopping, immediate, timer completed - false
32 | C. - starting, stopping, timerCompleted, immediate
33 | D - none of the above.
34 | */
35 |
36 | // email address - [A-Z,a-z,0-9]*@example.com
37 | //"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"
--------------------------------------------------------------------------------
/May_23rd/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "may_23rd",
3 | "version": "1.0.0",
4 | "lockfileVersion": 2,
5 | "requires": true,
6 | "packages": {
7 | "": {
8 | "name": "may_23rd",
9 | "version": "1.0.0",
10 | "license": "ISC",
11 | "dependencies": {
12 | "validator": "^13.7.0"
13 | }
14 | },
15 | "node_modules/validator": {
16 | "version": "13.7.0",
17 | "resolved": "https://registry.npmjs.org/validator/-/validator-13.7.0.tgz",
18 | "integrity": "sha512-nYXQLCBkpJ8X6ltALua9dRrZDHVYxjJ1wgskNt1lH9fzGjs3tgojGSCBjmEPwkWS1y29+DrizMTW19Pr9uB2nw==",
19 | "engines": {
20 | "node": ">= 0.10"
21 | }
22 | }
23 | },
24 | "dependencies": {
25 | "validator": {
26 | "version": "13.7.0",
27 | "resolved": "https://registry.npmjs.org/validator/-/validator-13.7.0.tgz",
28 | "integrity": "sha512-nYXQLCBkpJ8X6ltALua9dRrZDHVYxjJ1wgskNt1lH9fzGjs3tgojGSCBjmEPwkWS1y29+DrizMTW19Pr9uB2nw=="
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/May_23rd/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "may_23rd",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "app.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "validator": "^13.7.0"
14 | }
15 | }
--------------------------------------------------------------------------------
/May_27th/class_note.txt:
--------------------------------------------------------------------------------
1 | "We are trying to read this file from js"
--------------------------------------------------------------------------------
/May_27th/countdown_timer_app/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Countdown Timer
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | - DAYS
17 | - HOURS
18 | - MINUTES
19 | - SECONDS
20 | - MILLISECONDS
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/May_27th/countdown_timer_app/src/script.js:
--------------------------------------------------------------------------------
1 | document.getElementById("submit").onclick = function(event) {
2 | const targetTime = document.getElementById("dateTime").value;
3 | let interval = setInterval((targetTime) => {
4 | calculateTime(targetTime);
5 | }, 1, targetTime);
6 | }
7 |
8 | function calculateTime(targetTime) {
9 | let currentTime = new Date();
10 | let diff = new Date(targetTime).getTime() - currentTime.getTime();
11 |
12 | if(diff < 0) {
13 | clearInterval(interval);
14 | document.getElementById("days").innerText = "00";
15 | document.getElementById("hours").innerText = "00";
16 | document.getElementById("minutes").innerText = "00";
17 | document.getElementById("seconds").innerText = "00";
18 | document.getElementById('milliseconds').innerText = 0;
19 | }
20 | //how many days - 1 day = 24 * 60 * 60 * 1000
21 | // 10 ms and 55 ms = 55 % 10 = 5 days and 5 ms
22 | // 5 days and 4 hours - (5 * (24 * 60 * 60 * 1000) + 4 * (60 * 60 * 1000)) % (24 * 60 * 60 * 1000)
23 | // (a + b) % c = a %c + b % c;
24 | // 99 % 100 = 99... (0 - 99)
25 | // 99 % 10 = 9... (0 - 9)
26 | document.getElementById("days").innerText = Math.floor(diff / (24 * 60 * 60 * 1000));
27 | const hours = diff % (24 * 60 * 60 * 1000)
28 | document.getElementById("hours").innerText = Math.floor(hours / (60 * 60 * 1000));
29 |
30 | const minutes = diff % (60 * 60 * 1000);
31 | document.getElementById("minutes").innerText = Math.floor(minutes / (60 * 1000));
32 |
33 | const seconds = diff % (60 * 1000);
34 | document.getElementById("seconds").innerText = Math.floor(seconds / (1000));
35 |
36 | document.getElementById('milliseconds').innerText = (diff % 1000);
37 | }
--------------------------------------------------------------------------------
/May_27th/countdown_timer_app/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: sans-serif;
3 | background-color: #f0e9d2;
4 | display: flex;
5 | flex-direction: column;
6 | align-items: center;
7 | }
8 |
9 | input {
10 | border: none;
11 | }
12 |
13 | .display {
14 | width: calc(100% - 40px);
15 | margin-top: 40px;
16 | background-color: #678983;
17 | border-radius: 20px;
18 | color: black;
19 | display: flex;
20 | align-items: center;
21 | flex-direction: column-reverse;
22 | }
23 |
24 | ul {
25 | width: 100%;
26 | justify-content: space-evenly;
27 | align-content: center;
28 | display: inline-flex;
29 | }
30 |
31 | li {
32 | display: inline-block;
33 | list-style-type: none;
34 | }
35 |
36 | li span {
37 | display: block;
38 | }
39 |
40 | span {
41 | font-size: 50px;
42 | }
43 |
--------------------------------------------------------------------------------
/May_27th/may_27th.js:
--------------------------------------------------------------------------------
1 | /*
2 | Important - http://callbackhell.com/
3 | */
4 |
5 | /* Node.js code */
6 |
7 | // const fs = require('fs');
8 | // console.log("Start");
9 | // fs.readFile("./class_note.txt", () => {
10 | // console.log("Read the file!");
11 | // });
12 |
13 | // console.log("End!");
14 |
15 | //Browser Specific - Synchronous
16 |
17 | // console.log('start');
18 |
19 | function add(a, b) {
20 | const sum = a + b;
21 | return sum;
22 | }
23 |
24 | // console.log(add(3, 4));
25 | // console.log('end');
26 |
27 | // ------ Async Call Stack --------
28 | // console.log('start');
29 |
30 | // function add(a, b) {
31 | // const sum = a + b;
32 | // return sum;
33 | // }
34 | // var a = 10, b = 20;
35 | // setTimeout(() => {
36 | // console.log(add(3, 4));
37 | // }, 10000);
38 | // console.log('end');
39 |
40 | //--- university result code to understand callback hell----
41 | //login validation
42 | // setTimeout(() =>
43 | // {
44 | // console.log("Student logged in successfully");
45 | // //fetch Student details
46 | // setTimeout(() =>
47 | // {
48 | // console.log("Student information fetched successfully");
49 | // //fetch result
50 | // setTimeout(() =>
51 | // {
52 | // console.log("Fetched result successfully");
53 | // }, 3000);
54 | // }, 2000)
55 | // }, 2000);
56 |
57 | //--- setTimeout with parameter ---
58 | //setTimeout()
59 | //console.log("Hello", "my", "name", "is");
60 |
61 | const result = setTimeout((a, b) => {
62 | console.log(add(a, b));
63 | }, 2000, 5, 10, 15);
64 |
65 | clearTimeout(result);
66 |
67 | const interval = setInterval(() => {
68 | console.log("Interval execution");
69 | }, 1000);
70 |
71 | setTimeout(() => clearInterval(interval), 5000);
--------------------------------------------------------------------------------
/May_30th/async_callback.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 | const { parse } = require('path/posix');
3 | fs.readFile("./class_notes.txt", (error, data) => {
4 | if(error) {
5 | console.log("Oops error in reading file", error);
6 | } else {
7 | console.log(data.toString());
8 | }
9 | });
10 |
11 | const ageOfUsers = (skip, limit) => {
12 | const ages = [];
13 | for(let i = skip+1; i <= skip + limit; i++) {
14 | ages.push(10 + parseInt(Math.random() * 111));
15 | }
16 | return ages;
17 | }
18 | const fetchDataFromDB = (skip, limit) => {
19 | setTimeout(() => {
20 | const ages = ageOfUsers(0, 10);
21 | setTimeout(() => {
22 | ages.concat(ageOfUsers);
23 | setTimeout(() => {
24 |
25 | })
26 | }, 2000)
27 | }, 2000)
28 | }
29 |
30 |
31 | //(9 / 100) + (10/100) != (9 + 10)/20
32 |
33 |
--------------------------------------------------------------------------------
/May_30th/class_note.txt:
--------------------------------------------------------------------------------
1 | We are trying to read this file on the 30th of May
--------------------------------------------------------------------------------
/May_6th/may_6th.js:
--------------------------------------------------------------------------------
1 | /*
2 | 10^6 -> (2^3)^6 = 2 ^ 18 * 2 ^ 18 = 2 ^ 36 = O(n^2)
3 | O(nlog2n) -> read it as n * log of n base 2 = 18*2^18
4 | */
5 |
6 | // ---------------- Merge Sort --------------------
7 |
8 | //a1 -> is one of the sorted arrays
9 | //a2 -> the other sorted array.
10 | function merge(a1, a2) {
11 | result = [] //This array stores the sorted result of both a1 and a2
12 | //i points to a1, j points to a2, k points to result
13 | let i = 0, j = 0, k = 0;
14 | const m = a1.length, n = a2.length;
15 |
16 | while( i < m && j < n) {
17 | if(a1[i] < a2[j]) {
18 | result[k++] = a1[i++];
19 | } else {
20 | result[k++] = a2[j++];
21 | }
22 | }
23 | while( i < a1.length) {
24 | result[k++] = a1[i++];
25 | }
26 | while( j < a2.length) {
27 | result[k++] = a2[j++];
28 | }
29 |
30 | return result;
31 | }
32 |
33 | console.table(merge([1, 2, 5, 7], [3, 4, 6, 8]))
34 |
35 | function mergesort(arr, low, high) {
36 | if(low >= high) {
37 | return;
38 | }
39 | const mid = parseInt((low + high) / 2);
40 | mergesort(arr, low, mid);
41 | mergesort(arr, mid+1, high);
42 | mergeForMergeSort(arr, low, mid, high);
43 | }
44 |
45 | function mergeForMergeSort(arr, low, mid, high) {
46 | let i = low, j = mid+1, k = 0;
47 | result = [];
48 | while( i <= mid && j <= high) {
49 | if(arr[i] <= arr[j]) {
50 | result[k++] = arr[i++];
51 | } else {
52 | result[k++] = arr[j++];
53 | }
54 | }
55 | while( i <= mid) {
56 | result[k++] = arr[i++];
57 | }
58 | while(j <= high) {
59 | result[k++] = arr[j++];
60 | }
61 | for(i = low, k = 0; i <= high; i++, k++) {
62 | arr[i] = result[k];
63 | }
64 | }
65 |
66 | arr = [2, 1, 5, 7, 5, 6];
67 | mergesort(arr, 0, 5);
68 | console.log(arr);
69 |
70 |
--------------------------------------------------------------------------------
/May_9th/may_9th.js:
--------------------------------------------------------------------------------
1 | const quicksortUtil = (arr, low, high) => {
2 | if(low >= high) {
3 | return;
4 | }
5 | const pivot = partition(arr, low, high);
6 | quicksortUtil(arr, low, pivot-1);
7 | quicksortUtil(arr, pivot+1, high);
8 | }
9 |
10 | const quicksort = (arr) => {
11 | quicksortUtil(arr, 0, arr.length-1);
12 | }
13 | function partition(arr, low, high) {
14 | let pivot = low;
15 | let greaterPtr = low+1; //tracking for elements greater than the pivot
16 | let lesserPtr = high; // tracking for elements less than the pivot
17 | while(greaterPtr < lesserPtr) {
18 | while( greaterPtr <= high && arr[greaterPtr] <= arr[pivot]) {
19 | greaterPtr++;
20 | }
21 | while(lesserPtr >= low && arr[lesserPtr] > arr[pivot]) {
22 | lesserPtr--;
23 | }
24 |
25 | if(greaterPtr < lesserPtr) {
26 | swap(arr, greaterPtr, lesserPtr);
27 | }
28 | }
29 | swap(arr, pivot, greaterPtr-1);
30 | return greaterPtr-1;
31 | }
32 | function swap(arr, i, j) {
33 | const temp = arr[i];
34 | arr[i] = arr[j];
35 | arr[j] = temp;
36 | }
37 | const parition = (arr) => {
38 | partition(arr, 0, arr.length-1);
39 | }
40 | const arr = [4, 9, 8, 2, 3, 5, 10]
41 | parition(arr);
42 | quicksort(arr);
43 | console.log(arr);
44 |
45 | const arr1 = [4, 3, 8, 2, 1, 10, 9, 7]
46 | parition(arr1);
47 | quicksort(arr1);
48 | console.log(arr1);
49 |
50 | const allGreaterOnRight = [5, 5, 5, 7, 8, 9, 5];
51 | parition(allGreaterOnRight);
52 | quicksort(allGreaterOnRight);
53 | console.log(allGreaterOnRight);
54 |
55 | const allLesserOnRight = [4, 3, 2, 1, 0];
56 | parition(allLesserOnRight);
57 | quicksort(allLesserOnRight);
58 | console.log(allLesserOnRight);
59 |
60 |
61 | const quickSelect = (arr, k) => {
62 | return quickSelectUtil(arr, 0, arr.length - 1, k);
63 | }
64 |
65 | function quickSelectUtil(arr, low, high, k) {
66 | if(low === high) {
67 | return arr[low];
68 | }
69 | const pivot = partition(arr, low, high);
70 | //pivot is the rank in terms of overall context
71 | //but we need the rank in terms of the context of array between low to high
72 | const rank = pivot - low + 1;
73 | if( k === rank ) {
74 | return arr[pivot];
75 | }
76 | if(rank > k) {
77 | return quickSelectUtil(arr, low, pivot - 1, k);
78 | }
79 | return quickSelectUtil(arr, pivot + 1, high, k - rank);
80 | }
81 |
82 | console.log(quickSelect([0, 4, 3, 2, 1, 5, 6], 7));
83 |
84 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/AggressiveCows.js:
--------------------------------------------------------------------------------
1 | //we are not using this
2 | function findPosition(arr, target, lo) {
3 | let hi = arr.length - 1;
4 | while(lo <= hi) {
5 |
6 | const mid = (lo + hi) >>> 1;
7 | if(arr[mid] === target) {
8 | return mid;
9 | } else if(arr[mid] < target) {
10 | lo = mid + 1;
11 | } else {
12 | hi = mid - 1;
13 | }
14 | }
15 | return -(lo + 1);
16 | }
17 |
18 | function findLargestMinimumDistance(arr, k) {
19 | arr.sort((a, b) => a - b);
20 | console.log(arr);
21 | let lo = arr[arr.length - 1], hi = lo - arr[0];
22 | for(let i = 1; i < arr.length; i++) {
23 | lo = min(lo, arr[i] - arr[i-1]);
24 | }
25 | while(lo < hi) {
26 | const mid = (lo + hi + 1) >>> 1;
27 | if(!canPlaceKCows(arr, mid, k)) {
28 | hi = mid - 1;
29 | } else {
30 | lo = mid;
31 | }
32 | }
33 | return lo;
34 | }
35 |
36 | function canPlaceKCows(arr, minDistance, k) {
37 | let count = 1, previousPosition = arr[0], prevIndex = 0;
38 | for(let start = 1; start < arr.length; start ++) {
39 | if(previousPosition + minDistance > arr[start]) {
40 | continue;
41 | }
42 | previousPosition = arr[start];
43 | if(++count === k) {
44 | return true;
45 | }
46 | }
47 | return false;
48 | }
49 |
50 | function min(a, b) {
51 | return a < b ? a : b;
52 | }
53 |
54 | console.log(findLargestMinimumDistance([0, 3, 4, 7, 10, 9], 3));
55 | console.log(findLargestMinimumDistance([0, 3, 4, 7, 10, 9], 4));
56 | console.log(findLargestMinimumDistance([1, 2, 3], 2));
57 | console.log(findLargestMinimumDistance([4, 2, 1, 3, 6], 2));
58 | console.log(findLargestMinimumDistance([1,2,4,8,9], 3));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Arrays/BestTimeToBuySellStock.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} prices
3 | * @return {number}
4 | */
5 | var maxProfit = function(prices) {
6 | let buyPrice = prices[0];
7 | let profit = 0;
8 | for(let price of prices) {
9 | if(price > buyPrice) {
10 | profit = Math.max(profit, price - buyPrice);
11 | } else {
12 | buyPrice = price;
13 | }
14 | }
15 | return profit;
16 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Arrays/ContainerWithMostWater.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} height
3 | * @return {number}
4 | */
5 | var maxArea = function(height) {
6 | let left = 0, right = height.length-1;
7 | let maxArea = 0;
8 | while(left < right) {
9 | const currArea = (right - left) * Math.min(height[right], height[left]);
10 | maxArea = Math.max(maxArea, currArea);
11 | if(height[left] < height[right]) {
12 | left++;
13 | } else {
14 | right--;
15 | }
16 | }
17 | return maxArea;
18 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Arrays/FindMinimumInRotatedSortedArray.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number}
4 | */
5 | var findMin = function(nums) {
6 | let lo = 0, n = nums.length, hi = n-1;
7 | while(lo <= hi) {
8 | const mid = (lo + hi) >>> 1;
9 | if((mid === 0 || nums[mid-1] > nums[mid]) && (mid === n-1 || nums[mid+1] > nums[mid])) {
10 | return nums[mid];
11 | }
12 | if( (nums[mid] >= nums[0]) && (nums[0] > nums[n-1]) ) {
13 | lo = mid + 1;
14 | } else {
15 | hi = mid - 1;
16 | }
17 | }
18 | return -1;
19 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Arrays/MaximumSubarraySum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number}
4 | */
5 | var maxSubArray = function(nums) {
6 | let sumSoFar = 0, maximumSumSoFar = 0, minimumNegative = -Infinity;
7 | let hasPositive = false;
8 | for(let number of nums) {
9 | sumSoFar += number;
10 | if(sumSoFar < 0) {
11 | sumSoFar = 0;
12 | minimumNegative = Math.max(minimumNegative, number);
13 | } else {
14 | hasPositive = true;
15 | }
16 | maximumSumSoFar = Math.max(maximumSumSoFar, sumSoFar);
17 | }
18 | return !hasPositive ? minimumNegative : maximumSumSoFar;
19 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/BookAllocation.js:
--------------------------------------------------------------------------------
1 | /*
2 | We are given the ‘n’ number of books arranged in sorted order. Where each book has a different number of
3 | pages. You have to allocate books to ‘s’ count of students so that the maximum number of pages allotted to a
4 | student is minimum.
5 |
6 | Each student will be allotted at least one book and in contiguous order. Find the minimum possible number and
7 | if the assignment is not valid, return -1.
8 |
9 | input: [12, 34, 67, 90], s = 2
10 | output: 113
11 | Explanation:
12 |
13 | There are 2 students. Books can be distributed
14 |
15 | In below fashion:
16 |
17 |
18 | a) 12 and 34, 67, 90
19 | Maximum number of pages is allocated to student 2 with 34 + 67 + 90 = 191 pages.
20 |
21 | b) 12, 34 and 67, 90
22 | Maximum number of pages is allocated to student 2 with 67 + 90 = 157 pages.
23 |
24 |
25 |
26 | c) 12, 34, 67 and 90
27 | Maximum number of pages is allocated to student 1 with 12 + 34 + 67 = 113 pages.
28 |
29 | The minimum pages = 113.
30 | */
31 |
32 | const minimumRequiredStudents = (books, maxAllowedPages) => {
33 | let count = 1, sum = 0;
34 | for(const pagesInBook of books) {
35 | if(sum + pagesInBook > maxAllowedPages) {
36 | count++;
37 | sum = 0;
38 | }
39 | sum += pagesInBook;
40 | }
41 | return count;
42 | }
43 |
44 | const minimizeMaximumPages = (books, students) => {
45 | let lo = books[0], hi = 0;
46 | for(const pagesInBook of books) {
47 | lo = Math.max(lo, pagesInBook);
48 | hi += pagesInBook;
49 | }
50 | while (lo < hi) {
51 | const maxAllowedPages = (lo + hi) >>> 1;
52 | if(minimumRequiredStudents(books, maxAllowedPages) > students) {
53 | lo = maxAllowedPages + 1;
54 | } else {
55 | hi = maxAllowedPages;
56 | }
57 | }
58 | return lo;
59 | }
60 |
61 | console.log(minimizeMaximumPages([12, 34, 67, 90], 3));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/CountingSort.js:
--------------------------------------------------------------------------------
1 | /*
2 | Home Work
3 | https://leetcode.com/problems/h-index/
4 | https://leetcode.com/problems/height-checker
5 |
6 | */
7 | function countingSort(arr) {
8 | let maxValue = Number.MIN_VALUE, minValue = Number.MAX_VALUE;
9 | for(let number of arr) {
10 | minValue = Math.min(minValue, number);
11 | maxValue = Math.max(maxValue, number);
12 | }
13 | const len = maxValue - minValue + 1;
14 | const freqArr = new Array(len).fill(0);
15 |
16 | for(let number of arr) {
17 | freqArr[number - minValue]++;
18 | }
19 | let index = 0;
20 | //extract the sorted array from the frequency Array
21 | for(let i = 0; i < len; i++) {
22 | if(freqArr[i] === 0) {
23 | continue;
24 | }
25 | for(let it = 1; it <= freqArr[i]; it++) {
26 | arr[index++] = i + minValue;
27 | }
28 | }
29 | return arr;
30 | }
31 |
32 | console.log(countingSort([2, 4, 15, 3, 7, 8, 12, 10]));
33 | console.log(countingSort([2, 10, 3, 7, 6, 2, 10, 4, 3]));
34 | console.log(countingSort([10001, 10012, 10004, 10007, 10006, 10003]));
35 | console.log(countingSort([5, 2, -5, -3, 7, 6, 1, 4, 3]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/ContainerWithMostWater.js:
--------------------------------------------------------------------------------
1 | function containerWithMostWater(heights) {
2 | let maxCapacity = 0, leftPillar = 0, rightPillar = heights.length-1;
3 | while(leftPillar < rightPillar) {
4 | maxCapacity = Math.max(maxCapacity,
5 | Math.min(heights[leftPillar], heights[rightPillar]) * (rightPillar - leftPillar));
6 | if(heights[leftPillar] < heights[rightPillar]) {
7 | leftPillar++;
8 | } else {
9 | rightPillar--;
10 | }
11 | }
12 | return maxCapacity;
13 | }
14 |
15 | console.log(containerWithMostWater([1, 8, 6, 2, 5, 4, 8, 3, 7]))
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/FindTargetInRotatedSortedArray.js:
--------------------------------------------------------------------------------
1 | function findPivot(arr) {
2 | const n = arr.length;
3 | let lo = 0, hi = n-1;
4 | while(lo <= hi) {
5 | const mid = parseInt((lo + hi)/2);
6 | if((mid === 0 || arr[mid] < arr[mid-1])
7 | && (mid === hi || arr[mid] < arr[mid+1])) {
8 | return mid;
9 | }
10 | if(arr[mid] > arr[n-1]) {
11 | lo = mid + 1;
12 | } else {
13 | hi = mid - 1;
14 | }
15 | }
16 | return -1;
17 | }
18 | /*
19 | [4, 5, 6, 0, 1, 2]
20 | pivot = 3,
21 | [4, 5, 6] [0, 1, 2]
22 | */
23 | function findTarget(arr, target) {
24 | if(arr[0] > arr[arr.length - 1]) {
25 | const pivot = findPivot(arr);
26 | if(target < arr[0]) {
27 | return findTargetUtil(arr, pivot, arr.length-1, target);
28 | }
29 | return findTargetUtil(arr, 0, pivot-1, target);
30 | }
31 | return findTargetUtil(arr, 0, arr.length-1, target);
32 | }
33 |
34 | function findTargetUtil(arr, lo, hi, target) {
35 | while(lo <= hi) {
36 | let mid = parseInt((lo + hi)/2);
37 | if(arr[mid] === target) {
38 | return mid;
39 | }
40 | if(arr[mid] < target) {
41 | lo = mid+1;
42 | } else {
43 | hi = mid - 1;
44 | }
45 | }
46 | return -1;
47 | }
48 |
49 | console.log(findTarget([4, 5, 6, 0, 1, 2], 1));
50 | console.log(findTarget([4, 5, 6, 0, 1, 2], 6));
51 | console.log(findTarget([5, 0, 1, 2, 3], 3));
52 | console.log(findTarget([1], 0));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/FindUniqueElement.js:
--------------------------------------------------------------------------------
1 | function findUniqueElement(array) {
2 | let result = 0;
3 | for(let number of array) {
4 | result ^= number;
5 | }
6 | return result;
7 | }
8 |
9 | console.log(findUniqueElement([1, 2, 3, 2, 1]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/LCAInBST.js:
--------------------------------------------------------------------------------
1 | /*https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
2 | */
3 |
4 | /**
5 | * Definition for a binary tree node.
6 | * function TreeNode(val) {
7 | * this.val = val;
8 | * this.left = this.right = null;
9 | * }
10 | */
11 |
12 | /**
13 | * @param {TreeNode} root
14 | * @param {TreeNode} p
15 | * @param {TreeNode} q
16 | * @return {TreeNode}
17 | */
18 | var lowestCommonAncestor = function(root, p, q) {
19 | return p.val > q.val? LCAUtil(root, q, p) : LCAUtil(root, p, q);
20 | };
21 |
22 | var LCAUtil = function(root, smaller, greater) {
23 | if((root.val > smaller.val && root.val < greater.val)
24 | || (root.val === smaller.val || root.val === greater.val)) {
25 | return root;
26 | }
27 | if(root.val < smaller.val) {
28 | return LCAUtil(root.right, smaller, greater);
29 | }
30 | return LCAUtil(root.left, smaller, greater);
31 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/MaxDepthOfBinaryTree.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val, left, right) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.left = (left===undefined ? null : left)
6 | * this.right = (right===undefined ? null : right)
7 | * }
8 | */
9 | /**
10 | * @param {TreeNode} root
11 | * @return {number}
12 | */
13 | var maxDepth = function(root) {
14 | if(!root) {
15 | return 0;
16 | }
17 | const leftDepth = maxDepth(root.left);
18 | const rightDepth = maxDepth(root.right);
19 |
20 | return Math.max(leftDepth, rightDepth) + 1;
21 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/MaximizeProfitFromStock.js:
--------------------------------------------------------------------------------
1 | function maximiseProfitFromStock(price) {
2 | let buyingPrice = price[0], maxProfit = 0;
3 | for(let i = 1; i < price.length; i++) {
4 | if(price[i] < buyingPrice) {
5 | buyingPrice = price[i];
6 | } else {
7 | maxProfit = Math.max(maxProfit, price[i] - buyingPrice);
8 | }
9 | }
10 | return maxProfit;
11 | }
12 |
13 | console.log(maximiseProfitFromStock([7, 1, 5, 3, 6, 4]));
14 | console.log(maximiseProfitFromStock([7, 6, 4, 3, 1]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/MaximumHeightPyramind.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given n objects, with each object has width wi. We need to arrange them in a pyramidal way such that :
3 |
4 | 1. Total width of ith level is greater than (i - 1)th.
5 | 2. Total number of objects in the ith is greater than (i - 1)th.
6 |
7 | The task is to find the maximum height that can be achieved from given objects.
8 |
9 | Input : arr[] = {40, 100, 20, 30}
10 | Output : 2
11 |
12 | 1. 40 (1)
13 | 2. 120(100, 20, 30)
14 |
15 | 100
16 | 60+50+40
17 |
18 | let level = 1, prevWidth = arr[0], prevObjectCount = 1;
19 | let index = 1
20 | while(index < arr.length) {
21 | let currWidth = 0, currObjectCount = 0
22 | while(currWidth <= prevWidth && currObjectCount <= prevObjectCount) {
23 | currWidth += arr[index++];
24 | currObjectCount++;
25 | if(index >= arr.length) {
26 | break;
27 | }
28 | }
29 | level++
30 | }
31 | return level;
32 | */
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/MaximumSumSubarray.js:
--------------------------------------------------------------------------------
1 | function findMaximumSubarraySum(arr) {
2 | /*
3 | 1. we will handle for all negative numbers
4 | 2. we will return the maximum sum
5 | 3. we will find the starting and the ending position
6 | */
7 | let areAllNegative = true;
8 | let maxNegativeIndex = -1;
9 | let sumSoFar = 0, maxSum = 0, possibleStart = 0, end = -1, start = 0;
10 |
11 | for(let i = 0; i < arr.length; i++) {
12 | sumSoFar += arr[i];
13 | if(arr[i] < 0 &&
14 | (maxNegativeIndex == -1 || arr[i] > arr[maxNegativeIndex])) {
15 | maxNegativeIndex = i;
16 | }
17 | if(sumSoFar < 0) {
18 | sumSoFar = 0;
19 | possibleStart = i+1;
20 | } else {
21 | areAllNegative = false;
22 | if(maxSum < sumSoFar) {
23 | maxSum = sumSoFar;
24 | end = i;
25 | start = possibleStart;
26 | }
27 | }
28 | }
29 | return areAllNegative? [arr[maxNegativeIndex], maxNegativeIndex, maxNegativeIndex] :
30 | [maxSum, start, end];
31 | }
32 |
33 | console.log(findMaximumSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4]));
34 | console.log(findMaximumSubarraySum([-1, -2, -3, -4]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/SortArrayWithEquation.js:
--------------------------------------------------------------------------------
1 | /*
2 | Problem Statement - Given an array. Your task is to sort it using Stack.
3 | For example –
4 | Input – [2, 4, 1, 12, 14, 25, 35]
5 | Output – [1, 2, 4, 12, 14, 25, 35]
6 |
7 |
8 | 2, 4, 1, 12, 14, 25, 35
9 |
10 | 2, 1
11 | 35, 25, 14, 12, 4,
12 | temp - 2
13 |
14 | stack - LIFO
15 | topmost - smallest, smaller, small, ....
16 |
17 | stack - monotonically decreasing in nature.
18 |
19 |
20 | []
21 | resultStack - is monotonically decreasing nature
22 | resultstack - 35, 25, 14, 12, 4, 2, 1
23 |
24 | */
25 |
26 | Array.prototype.peek = function() {
27 | return this[this.length-1];
28 | }
29 | Array.prototype.isEmpty = function() {
30 | return this.length == 0;
31 | }
32 | function sortUsingStack(arr) {
33 | const resultStack = new Array();
34 | while(!arr.isEmpty()) {
35 | const current = arr.pop();
36 | while(!resultStack.isEmpty() && resultStack.peek() < current) {
37 | arr.push(resultStack.pop());
38 | }
39 | resultStack.push(current);
40 | }
41 |
42 | while(!resultStack.isEmpty()) {
43 | arr.push(resultStack.pop());
44 | }
45 | return arr;
46 | }
47 |
48 | console.log(sortUsingStack([2, 4, 1, 12, 14, 25, 35]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/SortNearlySortedArray.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an array of n numbers . Each element in the array is at maximum k distance from its actual
3 | position. Your task is to sort this kind of array with minimum time, where n = number of elements and k = distance from its
4 | actual position
5 |
6 | Input: [19, 18, 17, 14, 70, 60, 50], k = 3
7 | Output: [14, 17, 18, 19, 50, 60, 70], k = 3
8 |
9 | One sorting algorithm which takes care of putting an element in its correct position
10 | in an already sorted array. -
11 | 19, 18, 17, 14
12 | [18, 19], [17, 14]
13 | [18, 17, 19], [14]
14 | [17, 18, 19], [14]
15 | [14, 17, 18, 19], [70, 60, 50]
16 | [14, 17, 18, 19, 50, 60, 70]
17 | [18, 18, 19], [14]
18 | [17, 18, 19], [14]
19 | for(i = 1; i < n; i++) {
20 | let temp = arr[i];
21 | let j = i-1;
22 | for(;j >= Math.max(0, i-k) ; j--) {
23 | if(arr[j] > temp) {
24 | arr[j+1] = arr[j];
25 | } else {
26 | arr[j+1] = temp;
27 | break;
28 | }
29 | }
30 | if(arr[j] > temp) {
31 | arr[j] = temp;
32 | }
33 | }
34 |
35 |
36 | [19, 18, 17, 14, 70, 60, 50], k = 3
37 |
38 | [19, 18, 17, 14]
39 | minHeap = 4
40 | 14,
41 | [19 , 70, 60, 50]
42 | k*logK + (n-k)logk
43 | nlogk time
44 | [14, 17, 18, 19, 50, 60, 70]
45 | [19, 18, 17, 70]
46 |
47 | function sortNearlySorted(arr, k) {
48 | let heap = new MinHeap(k+1);
49 | let start = 0
50 | for(i = 0; i <=k; i++) {
51 | heap.insert(arr[i]);
52 | }
53 | for(let i = k+1; i < n; i++) {
54 | arr[start++] = heap.extract(arr[i]);
55 | heap.insert(arr[i]);
56 | }
57 | while(!heap.isEmpty()) {
58 | arr[start++] = heap.extractMin();
59 | }
60 | return arr;
61 | }
62 | */
63 |
64 |
65 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FSD3-AdvancedPS/ThreeSum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number[][]}
4 | */
5 | var threeSum = function(arr) {
6 | let result = [];
7 | const n = arr.length;
8 | arr.sort((a, b) => a - b);
9 | const target = 0;
10 | for(let a = 0; a < n-2; a++) {
11 | if(a !== 0 && arr[a] === arr[a-1]) {
12 | continue;
13 | }
14 | let b = a+1, c = n-1;
15 | while(b < c) {
16 | if(arr[a] + arr[b] + arr[c] === target) {
17 | result.push([arr[a], arr[b], arr[c]]);
18 | b++;c--;
19 | while(b < c && arr[b] === arr[b-1]) {
20 | b++;
21 | }
22 | while(c > b && arr[c] === arr[c+1]) {
23 | c--;
24 | }
25 | } else if(arr[a] + arr[b]+ arr[c] < target) {
26 | b++;
27 | while(b < c && arr[b] === arr[b-1]) {
28 | b++;
29 | }
30 | } else {
31 | c--;
32 | while(c > b && arr[c] === arr[c+1]) {
33 | c--;
34 | }
35 | }
36 | }
37 | }
38 | return result;
39 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FindDuplicateInArray.js:
--------------------------------------------------------------------------------
1 | /*
2 | You are Given a series of positive integer numbers in the form of a sorted array as A[i] where i is the index. N is the positive number which you have to check in the given array A[i] whether the given N is duplicate in the Array or not. If it is duplicate output as "TRUE" if it is non duplicate output as "FALSE".
3 | Note: Use Binary search algorithm to find the N.
4 | let arr = [1, 3, 5, 5, 7, 8, 9]; findNumber = 5;
5 | */
6 |
7 | const hasDuplicate = (arr, target) => {
8 | let lo = 0, hi = arr.length - 1;
9 | while(lo <= hi) {
10 | const mid = (lo + hi)/2;
11 | if(arr[mid] === target) {
12 | if((mid > 0 && arr[mid-1] === target) || (mid < arr.length - 1 &&arr[mid+1] === target)) {
13 | return true;
14 | }
15 | return false;
16 | } else if(arr[mid] < target) {
17 | lo = mid + 1;
18 | } else {
19 | hi = mid - 1;
20 | }
21 | }
22 | return false;
23 | }
24 |
25 | let arr = [1, 3, 5, 5, 7, 8, 9];
26 | console.log(hasDuplicate(arr, 5));
27 | console.log(hasDuplicate(arr, 7));
28 | console.log(hasDuplicate(arr, 10));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FindPairsThatSumToTarget.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an array of positive integers, and a value sum, determine if there is a sub-array of the given set with sum equal to given sum. Find the two numbers that summation will be equal to the value in the sum variable.
3 | Input: arr = [1, 3, 4, 5, 7, 10, 11, 12, 15, 17, 20] , sum = 4
4 | Output: 5 4
5 | */
6 |
7 | const findConsecutiveNumbers = (arr, target) => {
8 | let lo = 0, hi = arr.length - 1;
9 | while( lo <= hi) {
10 | const mid = parseInt((lo + hi) / 2);
11 | if(mid > 0 && arr[mid] + arr[mid-1] === target) {
12 | return [arr[mid-1], arr[mid]];
13 | }
14 | if(mid < arr.length-1 && arr[mid] + arr[mid+1] === target) {
15 | return [arr[mid], arr[mid+1]];
16 | }
17 | if((mid > 0 && arr[mid] + arr[mid-1] > target) || (mid < arr.length-1 && arr[mid] + arr[mid+1] > target)) {
18 | hi = mid - 1;
19 | } else {
20 | lo = mid + 1;
21 | }
22 | }
23 | return [];
24 | }
25 |
26 | const arr = [1, 3, 4, 5, 7, 10, 11, 12, 15, 17, 20]
27 | console.log(findConsecutiveNumbers(arr, 4));
28 | console.log(findConsecutiveNumbers(arr, 9));
29 | console.log(findConsecutiveNumbers(arr, 20));
30 | console.log(findConsecutiveNumbers(arr, 32));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/FirstAndLastOccurenceOfANumberInArray.js:
--------------------------------------------------------------------------------
1 | //[1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7]
2 | //first occurence and the last occurence
3 | //first occurence is at index 2
4 | // first occurence - leftmost from the right (hi = mid, keep moving backwards)
5 | //last occurence is at index 7
6 | // last occurence - rightmost from the left (lo = mid and keep moving forward)
7 |
8 | function firstOccurence(arr, target) {
9 | let lo = -1, hi = arr.length;
10 | while(lo < hi) {
11 | const mid = parseInt((lo + hi - 1) / 2);
12 | if(arr[mid] < target) {
13 | lo = mid + 1;
14 | } else {
15 | hi = mid;
16 | }
17 | }
18 | return lo;
19 | }
20 |
21 | function lastOccurrence(arr, target) {
22 | let lo = 0, hi = arr.length-1;
23 | while(lo < hi) {
24 | const mid = parseInt((lo + hi + 1)/2);
25 | if(arr[mid] <= target) {
26 | lo = mid;
27 | } else {
28 | hi = mid - 1;
29 | }
30 | }
31 | return lo;
32 | }
33 | const arr = [1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7];
34 | console.log(firstOccurence(arr, 2), lastOccurrence(arr, 2));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/HashMaps/ContinuousSubarraySumToTarget.js:
--------------------------------------------------------------------------------
1 | /*
2 | If all numbers are positive.
3 | [1, 2, 3, 7, 5, 5], k = 10
4 | sumArray = [1, 3, 6, 13, 18, 23]
5 |
6 | a - b where b is positive always will always reduce the value
7 | a - b where b is negative will always increase the value
8 | 10 - 5 = 5
9 | 10 - (-5) = 15
10 |
11 | while we have not traversed the entire array
12 | if at any point my sum becomes > my target
13 | while(sum > target) {
14 | //keep removing from the front
15 | }
16 | if(sum === target) {
17 | result++;
18 | }
19 | }
20 | return result
21 |
22 | let's say we encountered a negative number.
23 | => currently total sum = sum,
24 | => sum - x = target
25 | => sum - target = x
26 |
27 | 1, 2, 3, -4 k = 2
28 | 1 ....... 1........ 3
29 | 1 - 1
30 | 3 - 2 = 1
31 | map = (sum, 1);
32 | sum += arr[i];
33 | if(sum - target is present in map) {
34 | result += map.get(sum - target);
35 | }
36 | map.put(sum, map.get(sum) + 1);
37 |
38 | return count;
39 | */
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/HashMaps/Hashing.txt:
--------------------------------------------------------------------------------
1 | insert(45), insert(66), insert(55), delete(66), insert(65)
2 |
3 | 0 - 9
4 |
5 | 0 - ___
6 | 1 - ___
7 | 2 - ___
8 | 3 - ___
9 | 4 - ___
10 | 5 - 45
11 | 6 - 66
12 | 7 - 55
13 |
14 | h(k) % s
15 | (h(k)+1)%s
16 | (h(k) + 2) % s
17 |
18 | h(k) % 16 === h(k) % 32 ??
19 | 17 % 16 = 1
20 | 17 % 32 = 17
21 |
22 | if I increase the size of my hashmap, will I be able to correctly fetch the index position
23 | that was allotted to keys when the size was half?? - no
24 |
25 | we would actually recalculate the index positions of every key in the older hashMap
26 | and move them to the new index in the current hashMap. - Rehashing of the keys.
27 |
28 |
29 | total 10 values, 12
30 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/HashMaps/LongNonRepeatingSubstring.js:
--------------------------------------------------------------------------------
1 | /*
2 | a bca defgh abb
3 |
4 | aaaaghabca
5 | a = 3 = 1
6 | a g h = 3
7 | length = 6 - 3 = 3
8 | b c a d e f g h
9 | a = 3
10 | b = 1
11 | c = 2
12 | d = 4
13 | e = 5
14 |
15 | f = 6 length = 6
16 | g = 7 length = 7
17 | h = 8, length = 8
18 | a = 9,
19 | b = 10, length = 7
20 | b = 11,
21 | // maxLength = 8;
22 | // length = 8
23 | // length = length - seen[a] + 1
24 | //aaa gh a .... 5 - 2 = 3
25 | I am supposed to consider all characters starting from the
26 | character next to the repeating character till the current character
27 | if(current character was seen before and lies in the current window) {
28 | length = i - seen[char[i]];
29 | maxLength = 3;
30 | } else {
31 | length++;
32 | }
33 | seen[char] = i;
34 |
35 |
36 | */
37 | /**
38 | * @param {string} s
39 | * @return {number}
40 | */
41 | var lengthOfLongestSubstring = function(s) {
42 | const occurenceMap = new Array(256).fill(-1);
43 | let maxLength = 0, length = 0;
44 | for(let i = 0; i < s.length; i++) {
45 | const charAscii = s[i].charCodeAt();
46 | if(occurenceMap[charAscii] >= i - length) {
47 | length = i - occurenceMap[charAscii];
48 | } else {
49 | length++;
50 | }
51 | maxLength = Math.max(length, maxLength);
52 | occurenceMap[charAscii] = i;
53 | }
54 | return maxLength;
55 | };
56 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/HashMaps/SubarrayWithExactlyKDistinctIntegers.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @param {number} k
4 | * @return {number}
5 | */
6 | var subarraysWithKDistinct = function(nums, k) {
7 | // subarrays with atmost(2) distinct - it will include 1 and 2
8 | //subarrays with atmost(1) distinct - it will include 1
9 | // atmost(2) - atmost(1) = exactly (2) ???
10 |
11 | // atmost(3) = it will include - 1, 2 and 3
12 | // atmost(2) = it will include - 1 and 2
13 | //atmost(3) - atmost(2) = exactly(3) ??
14 | return subarraysWithAtmostKDistinct(nums, k) - subarraysWithAtmostKDistinct(nums, k-1);
15 | };
16 |
17 | const subarraysWithAtmostKDistinct = function (nums, k) {
18 | const count = {};
19 | let length = 0;
20 | for(let i = 0, start = 0; i < nums.length; i++) {
21 | if(!count[nums[i]]) {
22 | count[nums[i]] = 0;
23 | }
24 | count[nums[i]] += 1;
25 | if(count[nums[i]] === 1) {
26 | k--;
27 | }
28 | while(k < 0) {
29 | count[nums[start]] --;
30 | start++;
31 | if(count[nums[start]] === 0) {
32 | k++;
33 | }
34 | }
35 | length += (i - start + 1);
36 | }
37 | return length;
38 | }
39 |
40 | //how to find atmost k
41 | /*
42 | k = 1, 0, -1
43 | 1, 2, 1,[2, 3]
44 | 1, 2, 1, 2
45 | [1], [1, 2], [2]
46 | [1, 2, 1], [2, 1], [1]
47 | [1, 2, 1, 2], [2, 1, 2], [1, 2], [2]
48 | [2, 3], [3]
49 |
50 | [1]
51 | [2]
52 | [1]
53 | [2]
54 | [3]
55 | count = 1 + 1 + 1 + 1 + 1 = 5
56 | k = -1
57 | while( k < 0) {
58 | count[nums[start]] -= 1;
59 | if(count[nums[start]] === 0) {
60 | k ++;
61 | }
62 | }
63 | if (k >= 0) {
64 | count += 3 + (2-0+1) = 6 + (3 - 0 + 1) = 4 = 10 + (4 - 3) + 1 = 12
65 | }
66 | }
67 | 12 - 5 = 7
68 | */
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/HashMaps/TestHashTable.js:
--------------------------------------------------------------------------------
1 | const HashTable = require("./HashTable");
2 |
3 | const hashTable = new HashTable();
4 |
5 | const inputArray = [
6 | ["set", "testKey1", "testValue1"],
7 | ["set", "testKey2", "testValue2"],
8 | ["set", "testKey3", "testValue3"],
9 | ["get" , "testKey3"],
10 | ["set", "tsetKey3", "tsetValue3"],
11 | ["set", "testKey3", "updatedTestValue3"],
12 | ["get" , "testKey4"],
13 | ["get" , "testKey3"],
14 | ["get" , "tsetKey3"],
15 | ["delete" , "testKey3"],
16 | ["get" , "testKey3"],
17 | ["get" , "tsetKey3"],
18 | ["get" , "testKey1"],
19 | ];
20 |
21 | const testHashTable = (inputArr) => {
22 | for(const arr of inputArr) {
23 | switch(arr[0]) {
24 | case "set":
25 | hashTable.set(arr[1], arr[2]);
26 | break;
27 | case "get":
28 | const result = hashTable.get(arr[1]);
29 | result ? console.log(`${arr[1]} : ${result}`) :
30 | console.log(`key ${arr[1]} is not present`);
31 | break;
32 | case "delete":
33 | hashTable.delete(arr[1]);
34 | break;
35 | default:
36 | throw Error("Invalid Operation on Hashtable");
37 | }
38 | }
39 | }
40 |
41 | testHashTable(inputArray);
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Heap/LargestAreaHistogram.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} heights
3 | * @return {number}
4 | */
5 |
6 | Array.prototype.peek = function() {
7 | return this[this.length-1];
8 | }
9 |
10 | var largestRectangleArea = function(heights) {
11 | const st = new Array();
12 | st.push(-1);
13 | let maxArea = Number.MIN_VALUE;
14 | for(let i = 0; i < heights.length; i++) {
15 | let minHeight = Number.MAX_VALUE;
16 | while(st.peek() !== -1 && heights[st.peek()] >= heights[i]) {
17 | const index = st.pop();
18 | maxArea = Math.max(maxArea, heights[index] * ((i-1) - st.peek()));
19 | }
20 | st.push(i);
21 | }
22 | const length = heights.length;
23 | while(st.peek() !== -1) {
24 | let index = st.pop();
25 | maxArea = Math.max(maxArea, heights[index] * ((length-1) - st.peek()));
26 | }
27 | return maxArea;
28 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Heap/MaxHeap.js:
--------------------------------------------------------------------------------
1 | class MaxHeap {
2 | constructor(length = -1) {
3 | this.heap = new Array();
4 | if(length !== -1) {
5 | this.maxCapacity = length;
6 | }
7 | this.size = 0;
8 | }
9 |
10 | insert = function (value) {
11 | if(this.isFull()) {
12 | throw new Error("Heap is full");
13 | }
14 | this.heap.push(value);
15 | let index = this.size++;
16 | while(index > 0) {
17 | const pIndex = parseInt((index-1)/2);
18 | if(this.heap[pIndex] > this.heap[index]) {
19 | break;
20 | }
21 | this._swap(pIndex, index);
22 | index = pIndex;
23 | }
24 | }
25 | isFull = function() {
26 | return this.size === this.maxCapacity;
27 | }
28 | _swap(pIndex, index) {
29 | const temp = this.heap[index];
30 | this.heap[index] = this.heap[pIndex];
31 | this.heap[pIndex] = temp;
32 | }
33 |
34 | getMax = function() {
35 | return this.heap[0];
36 | }
37 |
38 | heapify = function(index) {
39 | const leftIndex = 2*index + 1;
40 | let largest = index;
41 | if(leftIndex < this.size && this.heap[leftIndex] > this.heap[index]) {
42 | largest = leftIndex;
43 | }
44 | const rightIndex = 2*index + 2;
45 | if(rightIndex < this.size && this.heap[rightIndex] > this.heap[largest]) {
46 | largest = rightIndex;
47 | }
48 | if(largest !== index) {
49 | this._swap(largest, index);
50 | this.heapify(largest);
51 | }
52 | }
53 | extractMax = function() {
54 | this._swap(0, --this.size);
55 | const max = this.heap.pop();
56 | this.heapify(0);
57 | return max;
58 | }
59 | printHeap() {
60 | for(let i = 0; i < this.size; i++) {
61 | process.stdout.write(this.heap[i] + " ");
62 | }
63 | console.log();
64 | }
65 | isEmpty = function () {
66 | return this.size === 0;
67 | }
68 | }
69 |
70 | module.exports = MaxHeap;
71 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Heap/PriorityQueue.js:
--------------------------------------------------------------------------------
1 | class PriorityQueue {
2 | constructor(comparator = null) {
3 | this.comparator = comparator !== null ? comparator : (a, b) => {
4 | return a > b;
5 | };
6 | this.heap = new Array();
7 | }
8 |
9 | insert = function(value) {
10 | this.heap.push(value);
11 | let index = this.heap.length-1;
12 | while(index > 0) {
13 | const parentIndex = parseInt((index-1)/2);
14 | if(!this.comparator(this.heap[parentIndex], this.heap[index])) {
15 | return;
16 | }
17 | this._swap(parentIndex, index);
18 | index = parentIndex;
19 | }
20 | }
21 |
22 | heapify = function(index) {
23 | const leftIndex = 2 * index + 1;
24 | let targetIndex = index;
25 | if(leftIndex < this.heap.length && this.comparator(this.heap[index], this.heap[leftIndex])) {
26 | targetIndex = leftIndex;
27 | }
28 | const rightIndex = 2 * index + 2;
29 | if(rightIndex < this.heap.length && this.comparator(this.heap[targetIndex], this.heap[rightIndex])) {
30 | targetIndex = rightIndex;
31 | }
32 | if(targetIndex !== index) {
33 | this._swap(targetIndex, index);
34 | this.heapify(targetIndex);
35 | }
36 | }
37 |
38 | extract = function () {
39 | if(this.isEmpty()) {
40 | return null;
41 | }
42 | const root = this.heap[0];
43 | this._swap(0, this.heap.length-1);
44 | this.heap.pop();
45 | this.heapify(0);
46 |
47 | return root;
48 | }
49 | isEmpty = function() {
50 | return !(this.heap && this.heap.length);
51 | }
52 | printHeap() {
53 | for(let i = 0; i < this.heap.length; i++) {
54 | process.stdout.write(this.heap[i] + " ");
55 | }
56 | console.log();
57 | }
58 | peek = function () {
59 | return this.heap[0];
60 | }
61 | _swap = function(i, j) {
62 | const temp = this.heap[i];
63 | this.heap[i] = this.heap[j];
64 | this.heap[j] = temp;
65 | }
66 | }
67 |
68 | module.exports = PriorityQueue;
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Heap/RearrangeStrings.js:
--------------------------------------------------------------------------------
1 | const PriorityQueue = require("./PriorityQueue");
2 |
3 | var reorganizeString = function(s) {
4 |
5 | /*
6 | first count of every element.
7 | a - 2, b - 1
8 | aabbbcddefghb
9 | a - 2, b - 4, c - 1, d- 2, e - 1, f - 1, g - 1, h - 1
10 | b - 3, a- 2, d - 2, c, e, f, g, h - 1
11 | b, in the next case if my element remains as b
12 | then temporarily pop b and use the next element
13 |
14 | b-2,a-1,d-2,c....-1
15 | b,a,b,d,b......
16 | b-1,a-1,d-1,c-1
17 | b - 2, d - 2
18 | b,d, b-1, d-1
19 | b
20 |
21 | aabbbcddefghb, k = 3
22 | b-3,a-2,d-2,c-1,e..h-1
23 | b-2,a-1,c..h - 1
24 | b-1,d..h - 1
25 | f..h - 1
26 | badbacbdefgh
27 | */
28 | const pq = new PriorityQueue((a, b) => {
29 | if(a.freq !== b.freq) {
30 | return b.freq > a.freq;
31 | }
32 | });
33 | const freqArr = new Array(26).fill(0);
34 | for(const char of s) {
35 | freqArr[char.charCodeAt() - 'a'.charCodeAt()]++;
36 | }
37 | for(let i = 0; i < 26; i++) {
38 | if(freqArr[i] !== 0) {
39 | pq.insert({value: String.fromCharCode('a'.charCodeAt() + i), freq: freqArr[i]});
40 | }
41 | }
42 | let result = new Array();
43 | while(!pq.isEmpty()) {
44 | const obj = pq.extract();
45 | result.push(obj.value);
46 | if(--obj.freq > 0) {
47 | pq.insert(obj);
48 | }
49 | if(!pq.isEmpty() && pq.peek().value === obj.value) {
50 | const temp = pq.extract();
51 | if(pq.isEmpty()) {
52 | return "";
53 | }
54 | const next = pq.extract();
55 | result.push(next.value);
56 | if(--next.freq > 0) {
57 | pq.insert(next);
58 | }
59 | pq.insert(temp);
60 | }
61 | }
62 | return result.join("");
63 | };
64 |
65 | console.log(reorganizeString("aab"));
66 | console.log(reorganizeString("aaab"));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Heap/TestHeap.js:
--------------------------------------------------------------------------------
1 | const MaxHeap = require("./MaxHeap");
2 | const PriorityQueue = require("./PriorityQueue");
3 | const heap = new MaxHeap();
4 | const priorityQueue = new PriorityQueue();
5 | const arr = [7, 5, 4, 8, 12, 10, 9];
6 |
7 | for(const number of arr) {
8 | heap.insert(number);
9 | priorityQueue.insert(number);
10 | console.log("MaxHeap -----");
11 | heap.printHeap();
12 | console.log("PriorityQueue -----");
13 | priorityQueue.printHeap();
14 | }
15 |
16 | /*
17 | 4, 5
18 | 5
19 | /
20 | 4
21 | 5, 4
22 | 7
23 | / \
24 | 4 5
25 | 7, 4, 5
26 |
27 | 8
28 | / \
29 | 7 5
30 | /
31 | 4
32 | 8 7 5 4
33 | 9
34 | / \
35 | 8 5
36 | / \
37 | 4 7
38 | 9 8 5 4 7
39 |
40 | 10
41 | / \
42 | 8 9
43 | / \ /
44 | 4 7 5
45 |
46 | 10 8 9 4 7 5
47 | 12
48 | / \
49 | 8 10
50 | / \ / \
51 | 4 7 5 9
52 |
53 | 12 8 10 4 7 5 9
54 |
55 |
56 | 4
57 | 5 4
58 | 7 4 5
59 | 8 7 5 4
60 | 9 8 5 4 7
61 | 10 8 9 4 7 5
62 | 12 8 10 4 7 5 9
63 | */
64 | console.log("Max Heap - extract all");
65 | while(!heap.isEmpty()) {
66 | process.stdout.write(heap.extractMax() + " ");
67 | }
68 | console.log("Priority Queue - extract all");
69 | while(!priorityQueue.isEmpty()) {
70 | process.stdout.write(priorityQueue.extract() + " ");
71 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/IsBadVersion.js:
--------------------------------------------------------------------------------
1 | /**
2 | * 278. First Bad Version
3 | * Definition for isBadVersion()
4 | *
5 | * @param {integer} version number
6 | * @return {boolean} whether the version is bad
7 | * isBadVersion = function(version) {
8 | * ...
9 | * };
10 | */
11 |
12 | /**
13 | * @param {function} isBadVersion()
14 | * @return {function}
15 | */
16 | var solution = function(isBadVersion) {
17 | /**
18 | * @param {integer} n Total versions
19 | * @return {integer} The first bad version
20 | */
21 | return function(n) {
22 | let lo = 1, hi = n;
23 | while( lo < hi) {
24 | const mid = (lo + hi) >>> 1;
25 | if(!isBadVersion(mid)) {
26 | lo = mid + 1;
27 | } else {
28 | hi = mid;
29 | }
30 | }
31 | return lo;
32 | };
33 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/AddToLinkedLists.js:
--------------------------------------------------------------------------------
1 | /*
2 | Two numbers represented in the form of a linkedlist
3 | 346 + 123
4 |
5 | 3 -> 4 -> 6
6 | 1 -> 2 -> 3
7 | -------------
8 | 4 -> 6 -> 9
9 | */
10 |
11 | /**
12 | * 445. Add Two Numbers II
13 | * Definition for singly-linked list.
14 | * function ListNode(val, next) {
15 | * this.val = (val===undefined ? 0 : val)
16 | * this.next = (next===undefined ? null : next)
17 | * }
18 | */
19 | /**
20 | * @param {ListNode} l1
21 | * @param {ListNode} l2
22 | * @return {ListNode}
23 | */
24 | var addTwoNumbers = function(l1, l2) {
25 | const length1 = length(l1);
26 | const length2 = length(l2);
27 | let result;
28 | if(length2 > length1) {
29 | result = addToLargerNumber(l2, l1, length2 - length1);
30 | } else {
31 | result = addToLargerNumber(l1, l2, length1 - length2);
32 | }
33 | if(result[0]) {
34 | let newHead = new ListNode(1);
35 | newHead.next = currHead;
36 | return newHead;
37 | } else {
38 | return result[1];
39 | }
40 | };
41 |
42 | const addToLargerNumber = function(largerNumber, smallerNumber, diff) {
43 | if(--diff < 0) {
44 | return addToNumbersEqualLength(largerNumber, smallerNumber);
45 | }
46 | const [carry, currHead] = addToLargerNumber(largerNumber.next, smallerNumber, diff);
47 | return sumOfDigits(largerNumber.val, 0, carry, currHead);
48 | }
49 |
50 | const addToNumbersEqualLength = function(head1, head2) {
51 | if(head1 === null) {
52 | return [0, null];
53 | }
54 | const [carry, currHead] = addToNumbersEqualLength(head1.next, head2.next);
55 | return sumOfDigits(head1.val, head2.val, carry, currHead);
56 | }
57 |
58 | const sumOfDigits = function (val1, val2, carry, currHead) {
59 | const sum = val1 + val2 + carry;
60 | const newHead = new ListNode(sum%10);
61 | newHead.next = currHead;
62 | return [parseInt(sum / 10), newHead];
63 | }
64 |
65 | const length = function(l1) {
66 | let count = 0;
67 | while(l1 != null) {
68 | count++;
69 | l1 = l1.next;
70 | }
71 | return count;
72 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/Caches.txt:
--------------------------------------------------------------------------------
1 | Cache Eviction Policies
2 | 1. the one that came in first, will be the first (FIFO)
3 | 2. the ones with higher priority - priority based eviction.
4 | 3. size based eviction policy - based on the size of the data
5 | 4. Least recently used - will be evicted first - LRU
6 | 5. Least Frequently used - the one with the least frequency of use is evicted first
7 | if there multiple keys in contention,
8 | the one which was least recently used will be deleted first
9 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/CycleDetection-II.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 142
3 | * Definition for singly-linked list.
4 | * function ListNode(val) {
5 | * this.val = val;
6 | * this.next = null;
7 | * }
8 | */
9 |
10 | /**
11 | * @param {ListNode} head
12 | * @return {ListNode}
13 | */
14 | var detectCycle = function(head) {
15 | let slow = head, fast = head;
16 | while(fast && fast.next) {
17 | slow = slow.next;
18 | fast = fast.next.next;
19 |
20 | if(slow === fast) {
21 | break;
22 | }
23 | }
24 | if(!fast || !fast.next) {
25 | return null;
26 | }
27 | let temp = head;
28 | while(temp !== slow) {
29 | temp = temp.next;
30 | slow = slow.next;
31 | }
32 | return temp;
33 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/CycleDetection.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 141
3 | * Definition for singly-linked list.
4 | * function ListNode(val) {
5 | * this.val = val;
6 | * this.next = null;
7 | * }
8 | */
9 |
10 | /**
11 | * @param {ListNode} head
12 | * @return {boolean}
13 | */
14 | var hasCycle = function(head) {
15 | let slow = head, fast = head;
16 | while(fast && fast.next) {
17 | slow = slow.next;
18 | fast = fast.next.next;
19 |
20 | if(slow === fast) {
21 | return true;
22 | }
23 | }
24 | return false;
25 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/IntersectionOfTwoLists.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 160
3 | * Definition for singly-linked list.
4 | * function ListNode(val) {
5 | * this.val = val;
6 | * this.next = null;
7 | * }
8 | */
9 |
10 | /**
11 | * @param {ListNode} headA
12 | * @param {ListNode} headB
13 | * @return {ListNode}
14 | */
15 | var getIntersectionNode = function(headA, headB) {
16 | let lengthA = length(headA);
17 | let lengthB = length(headB);
18 |
19 | if(lengthB > lengthA) {
20 | let diff = lengthB-lengthA;
21 | while(--diff >= 0) {
22 | headB = headB.next;
23 | }
24 | } else if(lengthA > lengthB) {
25 | let diff = lengthA-lengthB;
26 | while(--diff >= 0) {
27 | headA = headA.next;
28 | }
29 | }
30 | while(headA) {
31 | if(headA === headB) {
32 | break;
33 | }
34 | headA = headA.next;
35 | headB = headB.next;
36 | }
37 | return headA;
38 | };
39 |
40 | const length = function(head) {
41 | let count = 0;
42 | while(head != null) {
43 | count++;
44 | head = head.next;
45 | }
46 | return count;
47 | }
48 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/MergeKSortedLists.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val, next) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.next = (next===undefined ? null : next)
6 | * }
7 | */
8 | /**
9 | * @param {ListNode[]} lists
10 | * @return {ListNode}
11 | */
12 | var mergeKLists = function(lists) {
13 | if(!lists || !lists.length) {
14 | return null;
15 | }
16 | return mergeSort(lists, 0, lists.length-1);
17 | };
18 |
19 | var mergeSort = function (lists, lo, hi) {
20 | if(lo === hi) {
21 | return lists[lo];
22 | }
23 | const mid = (lo + hi) >>> 1;
24 | const left = mergeSort(lists, lo, mid);
25 | const right = mergeSort(lists, mid+1, hi);
26 |
27 | return merge(left, right);
28 | }
29 |
30 | var merge = function(list1, list2) {
31 | if(!list1) {
32 | return list2;
33 | }
34 | if(!list2) {
35 | return list1;
36 | }
37 | let resultList = null;
38 | let tracker = null;
39 | while(list1 && list2) {
40 | let smaller;
41 | if(list1.val < list2.val) {
42 | smaller = list1;
43 | list1 = list1.next;
44 | } else {
45 | smaller = list2;
46 | list2 = list2.next;
47 | }
48 | if(!resultList) {
49 | resultList = tracker = smaller;
50 | } else {
51 | tracker.next = smaller;
52 | tracker = tracker.next;
53 | }
54 | }
55 | if(list1) {
56 | tracker.next = list1;
57 | }
58 | if(list2) {
59 | tracker.next = list2;
60 | }
61 | return resultList;
62 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/MergeTwoSortedLists.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val, next) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.next = (next===undefined ? null : next)
6 | * }
7 | */
8 | /**
9 | * @param {ListNode} list1
10 | * @param {ListNode} list2
11 | * @return {ListNode}
12 | */
13 | var mergeTwoLists = function(list1, list2) {
14 | if(!list1) {
15 | return list2;
16 | }
17 | if(!list2) {
18 | return list1;
19 | }
20 | let resultList = null;
21 | let tracker = null;
22 | while(list1 && list2) {
23 | let smaller;
24 | if(list1.val < list2.val) {
25 | smaller = list1;
26 | list1 = list1.next;
27 | } else {
28 | smaller = list2;
29 | list2 = list2.next;
30 | }
31 | if(!resultList) {
32 | resultList = tracker = smaller;
33 | } else {
34 | tracker.next = smaller;
35 | tracker = tracker.next;
36 | }
37 | }
38 | if(list1) {
39 | tracker.next = list1;
40 | }
41 | if(list2) {
42 | tracker.next = list2;
43 | }
44 | return resultList;
45 | };
46 |
47 | /*
48 | 1-> 2 -> 3-> 4
49 | 1->2
50 |
51 | 1->1->2->2->3->4
52 | */
53 | //1 -> 1 -> 2 -> 3
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/MiddleOfALinkedList.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 876
3 | * Definition for singly-linked list.
4 | * function ListNode(val, next) {
5 | * this.val = (val===undefined ? 0 : val)
6 | * this.next = (next===undefined ? null : next)
7 | * }
8 | */
9 | /**
10 | * @param {ListNode} head
11 | * @return {ListNode}
12 | */
13 | var middleNode = function(head) {
14 | let slow = head, fast = head;
15 | while(fast && fast.next) {
16 | slow = slow.next;
17 | fast = fast.next.next;
18 | }
19 | return slow;
20 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/ReorderList.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 143
3 | * Definition for singly-linked list.
4 | * function ListNode(val, next) {
5 | * this.val = (val===undefined ? 0 : val)
6 | * this.next = (next===undefined ? null : next)
7 | * }
8 | */
9 | /**
10 | * @param {ListNode} head
11 | * @return {void} Do not return anything, modify head in-place instead.
12 | */
13 | var reorderList = function(head) {
14 | const lastNode = findMiddle(head);
15 | let right = lastNode.next, left = head;
16 | right = reverseList(right);
17 | lastNode.next = null;
18 | while(right) {
19 | let nextInLeftLL = left.next;
20 | let nextInRightLL = right.next;
21 | left.next = right;
22 | right.next = nextInLeftLL;
23 | left = nextInLeftLL;
24 | right = nextInRightLL;
25 | }
26 | return head;
27 | };
28 |
29 | function reverseList(head) {
30 | let curr = head, prev = null;
31 | while(curr) {
32 | let next = curr.next;
33 | curr.next = prev;
34 | prev = curr;
35 | curr = next;
36 | }
37 | return prev;
38 | }
39 |
40 | function findMiddle(head) {
41 | let slow = head, fast = head;
42 | while(fast.next && fast.next.next) {
43 | slow = slow.next;
44 | fast = fast.next.next;
45 | }
46 | return slow;
47 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/ReverseList.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 206
3 | * Definition for singly-linked list.
4 | * function ListNode(val, next) {
5 | * this.val = (val===undefined ? 0 : val)
6 | * this.next = (next===undefined ? null : next)
7 | * }
8 | */
9 | /**
10 | * @param {ListNode} head
11 | * @return {ListNode}
12 | */
13 | var reverseList = function(head) {
14 | let curr = head, prev = null, next = null;
15 | while(curr) {
16 | next = curr.next;
17 | curr.next = prev;
18 | prev = curr;
19 | curr = next;
20 | }
21 | return prev;
22 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/ReverseNodesInKGroups.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val, next) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.next = (next===undefined ? null : next)
6 | * }
7 | */
8 | /**
9 | * @param {ListNode} head
10 | * @param {number} k
11 | * @return {ListNode}
12 | */
13 | var reverseKGroup = function(head, k) {
14 | let resHead, previous = head, temp = head;
15 | while(temp != null) {
16 | const start = temp;
17 | let count = 0;
18 | while(++count < k && temp.next) {
19 | temp = temp.next;
20 | }
21 | if(count < k) {
22 | previous.next = start;
23 | break;
24 | }
25 | const next = temp.next;
26 | temp.next = null;
27 | const reversed = reverseList(start);
28 | if(!resHead) {
29 | resHead = reversed;
30 | } else {
31 | previous.next = reversed;
32 | previous = start;
33 | }
34 | temp = next;
35 | }
36 | return resHead;
37 | };
38 |
39 | const reverseList = function(start) {
40 | let prev = null, curr = start;
41 | while(curr) {
42 | const next = curr.next;
43 | curr.next = prev;
44 | prev = curr;
45 | curr = next;
46 | }
47 | return prev;
48 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/SortTriplets.js:
--------------------------------------------------------------------------------
1 | //https://practice.geeksforgeeks.org/problems/given-a-linked-list-of-0s-1s-and-2s-sort-it/1
2 | class Solution {
3 | //Function to sort a linked list of 0s, 1s and 2s.
4 | segregate(head)
5 | {
6 | //your code here
7 | let zeroList = null, oneList = null, twoList = null;
8 | let temp = head;
9 | while(temp != null) {
10 | const next = temp.next;
11 | temp.next = null;
12 | if(temp.data === 0) {
13 | zeroList = this.addToBegin(zeroList, temp);
14 | } else if(temp.data === 1) {
15 | oneList = this.addToBegin(oneList, temp);
16 | } else {
17 | twoList = this.addToBegin(twoList, temp);
18 | }
19 | temp = next;
20 | }
21 | return this.concat(zeroList, oneList, twoList);
22 | }
23 | addToBegin(list, node) {
24 | if(list === null) {
25 | list = node;
26 | } else {
27 | node.next = list;
28 | list = node;
29 | }
30 | return list;
31 | }
32 | concat(zeroList, oneList, twoList) {
33 | let head, temp;
34 | if(!zeroList && !oneList) {
35 | return twoList;
36 | }
37 | if(zeroList) {
38 | head = temp = zeroList;
39 | while(temp.next != null) {
40 | temp = temp.next;
41 | }
42 | temp.next = oneList;
43 | }
44 | if(oneList) {
45 | if(!head) {
46 | head = oneList;
47 | }
48 | temp = oneList;
49 | while(temp.next != null) {
50 | temp = temp.next;
51 | }
52 | }
53 | temp.next = twoList;
54 | return head;
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/SortedLinkedListToBST.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val, next) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.next = (next===undefined ? null : next)
6 | * }
7 | */
8 | /**
9 | * Definition for a binary tree node.
10 | * function TreeNode(val, left, right) {
11 | * this.val = (val===undefined ? 0 : val)
12 | * this.left = (left===undefined ? null : left)
13 | * this.right = (right===undefined ? null : right)
14 | * }
15 | */
16 | /**
17 | * @param {ListNode} head
18 | * @return {TreeNode}
19 | */
20 |
21 | let listHead;
22 | var sortedListToBST = function(head) {
23 | listHead = head;
24 | const length = listLength(head);
25 | return listToTree(1, length);
26 | };
27 |
28 | const listLength = function(head) {
29 | let count = 0;
30 | while(head != null) {
31 | head = head.next;
32 | count++;
33 | }
34 | return count;
35 | }
36 |
37 | const listToTree = function(start, end) {
38 | if(start > end) {
39 | return null;
40 | }
41 | let mid = parseInt((end + start) / 2);
42 | const left = listToTree(start, mid-1);
43 | const root = new TreeNode(listHead.val);
44 | listHead = listHead.next;
45 | root.left = left;
46 | root.right = listToTree( mid+1, end);
47 |
48 | return root;
49 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/SwapNodesInKPair.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val, next) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.next = (next===undefined ? null : next)
6 | * }
7 | */
8 | /**
9 | * @param {ListNode} head
10 | * @return {ListNode}
11 | */
12 | var swapPairs = function(head) {
13 | if(!head || !head.next) {
14 | return head;
15 | }
16 | return reverseKGroup(head, 2);
17 | };
18 | var reverseKGroup = function(head, k) {
19 | let resHead, previous = head, temp = head;
20 | while(temp != null) {
21 | const start = temp;
22 | let count = 0;
23 | while(++count < k && temp.next) {
24 | temp = temp.next;
25 | }
26 | if(count < k) {
27 | previous.next = start;
28 | break;
29 | }
30 | const next = temp.next;
31 | temp.next = null;
32 | const reversed = reverseList(start);
33 | if(!resHead) {
34 | resHead = reversed;
35 | } else {
36 | previous.next = reversed;
37 | previous = start;
38 | }
39 | temp = next;
40 | }
41 | return resHead;
42 | };
43 |
44 | const reverseList = function(start) {
45 | let prev = null, curr = start;
46 | while(curr) {
47 | const next = curr.next;
48 | curr.next = prev;
49 | prev = curr;
50 | curr = next;
51 | }
52 | return prev;
53 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/SwapPairs.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val, next) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.next = (next===undefined ? null : next)
6 | * }
7 | */
8 | /**
9 | * @param {ListNode} head
10 | * @return {ListNode}
11 | */
12 | var swapPairs = function(head) {
13 | if(!head || !head.next) {
14 | return head;
15 | }
16 | return reverseKGroup(head, 2);
17 | };
18 | var reverseKGroup = function(head, k) {
19 | let resHead, previous = head, temp = head;
20 | while(temp != null) {
21 | const start = temp;
22 | let count = 0;
23 | while(++count < k && temp.next) {
24 | temp = temp.next;
25 | }
26 | if(count < k) {
27 | previous.next = start;
28 | break;
29 | }
30 | const next = temp.next;
31 | temp.next = null;
32 | const reversed = reverseList(start);
33 | if(!resHead) {
34 | resHead = reversed;
35 | } else {
36 | previous.next = reversed;
37 | previous = start;
38 | }
39 | temp = next;
40 | }
41 | return resHead;
42 | };
43 |
44 | const reverseList = function(start) {
45 | let prev = null, curr = start;
46 | while(curr) {
47 | const next = curr.next;
48 | curr.next = prev;
49 | prev = curr;
50 | curr = next;
51 | }
52 | return prev;
53 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LinkedLists/increment_operator_using_ll.js:
--------------------------------------------------------------------------------
1 | // you have to implement the increment operator using a linked list
2 | /*
3 | a number will be represented in the form of a linked list
4 | if number is 123, it will look like
5 | 1 -> 2 -> 3
6 | number++ = 1->2->4
7 | adding two numbers, 1->2->3 and the other number is 1->null
8 | a++ =
9 |
10 | *** Solve it without recursion
11 |
12 |
13 | 1 -> 2 -> 3
14 |
15 | 1->2->9
16 | 1->3->0
17 | 9 9 9 0
18 | 8 9 9 8
19 | 1 0 9 9
20 | 1 1 0 0
21 | 8 9 9 8 9 9
22 |
23 | consecutive 9 are 2
24 | toal length = 6
25 | 8 9 9 9 0 0
26 | 9 9 9 9
27 | 1 -> 0 -> 0 -> 0 -> 0
28 |
29 | 1. if there is no 9 in the end
30 | 2. if there is a 9 in the end
31 | 2.1 total 9's from the end = x
32 | 2.2if(total 9's are less than total length){
33 | 2.2.1 till (n - x - 1) copy as it is.
34 | 2.2.2 n-xth digit = (digit + 1)
35 | 2.2.3 remaining x digits = 0
36 | }
37 | 2.3 else {
38 | 2.3.1 initialize newHead with 1 as the val,
39 | 2.3.2 remaining n digits = 0;
40 | }
41 |
42 | */
43 |
44 | function increment(head) {
45 |
46 | return newNode; //which is basically the incremented value.
47 | }
48 |
49 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LongestIncreasingSubsequence-BS.js:
--------------------------------------------------------------------------------
1 | /**
2 | * 300. Longest Increasing Subsequence
3 | * @param {number[]} nums
4 | * @return {number}
5 | */
6 | var lengthOfLIS = function(nums) {
7 | let lis = [];
8 | let hi = -1;
9 | for(let num of nums) {
10 | let index = binarySearch(lis, 0, hi, num);
11 | if(index < 0) {
12 | index = -(index + 1);
13 | }
14 | lis[index] = num;
15 | if(index > hi) {
16 | hi = index;
17 | }
18 | }
19 | return hi + 1;
20 | };
21 |
22 | function binarySearch(arr, lo, hi, target) {
23 | while( lo <= hi) {
24 | const mid = (lo + hi) >>> 1;
25 | if(arr[mid] === target) {
26 | return mid;
27 | } else if(arr[mid] < target) {
28 | lo = mid + 1;
29 | } else {
30 | hi = mid - 1;
31 | }
32 | }
33 | return -(lo + 1);
34 | }
35 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/LongestIncreasingSubsequence-DP.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number}
4 | *
5 | * Given an integer array nums, return the length of the longest strictly increasing subsequence.
6 |
7 | A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
8 | */
9 | var lengthOfLIS = function(nums) {
10 | //longest increasing subsequence
11 | //NOT - subarray.
12 | //[0, 3, 1, 6, 2, 2, 7]
13 | // - [0, 3, 6, 7]
14 | // - [0, 1, 6, 7]
15 | // - [0, 1, 2, 7]
16 | // - [3, 6, 7]
17 | // - [1, 6, 7]
18 | // - [1, 2, 7]
19 | // - length is 4
20 | // - [5, 4, 5, 2, 3, 1]
21 | let longestSubsequence = 1;
22 | let result = new Array(nums.length).fill(0);
23 | for(let i = 0; i < nums.length; i++) {
24 | longestSubsequence = max(longestSubsequence, dfs(nums, i, result));
25 | }
26 | return longestSubsequence;
27 | };
28 |
29 | function dfs(arr, index, result) {
30 | if(result[index] > 0) {
31 | return result[index];
32 | }
33 | let longestSubsequence = 0;
34 | for(let i = index + 1; i < arr.length; i++) {
35 | if(arr[i] <= arr[index]) {
36 | continue;
37 | }
38 | longestSubsequence = max(longestSubsequence, dfs(arr, i, result));
39 | }
40 | result[index] = longestSubsequence+1;
41 | return result[index];
42 | }
43 |
44 | function max(a, b) {
45 | return a > b ? a : b;
46 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/MedianOfTwoSortedArrays.js:
--------------------------------------------------------------------------------
1 | function findMedian(arr1, arr2) {
2 | let lo = 0, hi = arr1.length;
3 | const totalLength = arr1.length + arr2.length;
4 | const split = (totalLength + 1) >>> 1;
5 | while(lo <= hi) {
6 | const mid = (lo + hi) >>> 1;
7 | const arr1Left = mid === 0 ? Number.MIN_VALUE : arr1[mid - 1];
8 | const arr2Left = mid === split ? Number.MIN_VALUE : arr2[split - mid - 1];
9 | const arr1Right = mid === arr1.length ? Number.MAX_VALUE : arr1[mid];
10 | const arr2Right = split - mid === arr2.length ? Number.MAX_VALUE : arr2[split - mid];
11 | if(arr1Left > arr2Right) {
12 | hi = mid - 1;
13 | } else if (arr2Left > arr1Right){
14 | lo = mid + 1;
15 | } else {
16 | if(totalLength % 2 === 0) {
17 | return (Math.max(arr1Left, arr2Left) + Math.min(arr1Right, arr2Right))/2;
18 | }
19 | else {
20 | return Math.max(arr1Left, arr2Left);
21 | }
22 | }
23 | }
24 | return -1;
25 | }
26 |
27 | console.log(findMedian([1, 3, 5, 7], [4, 6, 9, 12, 14, 16]));
28 | console.log(findMedian([1, 3, 5, 7], [4, 6, 9, 12, 16]));
29 | console.log(findMedian([-5,3,6,12,15], [-12,-10,-6,-3,4,10]))
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/MeetingRooms-II.js:
--------------------------------------------------------------------------------
1 | /*
2 | [0, 30], [5, 10], [15, 20]
3 | flatten the information in a 2-D array
4 | where each individual array stores 2 informations
5 | 1. time of event
6 | 2. type of event
7 | 1 start
8 | -1 => end
9 | [[0, start], [30, end], [5, start], [10, end], [10, start], [20, end]]
10 | [0, start] - one MR
11 | [5, start] - two MR
12 | //this ??
13 | [10, start] - three MR
14 | [10, end] - two MR
15 | //or this??
16 | [10, end] - one MR,
17 | [10, start] - two MR
18 | [20, end] - one MR
19 | [30, end] - zero MR
20 |
21 | [[0, 1], [30, -1], [5, 1], [10, -1], [10, 1], [20, -1]]
22 | mr += event[index][1]
23 |
24 | (event1, event2) => {
25 | if(event1[0] < event2[0]) {
26 | return event1[0] - event2[0];
27 | } else {
28 | return event1[1] - event2[1];
29 | }
30 | }
31 | [[], [], []]
32 | */
33 |
34 | function meetingRooms(intervals) {
35 | const len = intervals.length;
36 | const events = new Array(2*len);
37 | let index = 0;
38 | for(let interval of intervals) {
39 | events[index++] = [interval[0], 1];
40 | events[index++] = [interval[1], -1];
41 | }
42 |
43 | events.sort((event1, event2) => {
44 | if(event1[0] !== event2[0]) {
45 | return event1[0] - event2[0];
46 | } else {
47 | return event1[1] - event2[1];
48 | }
49 | });
50 | let occupiedMRs = 0, minMRsRequired = 0;
51 | for(let event of events) {
52 | occupiedMRs += event[1];
53 | minMRsRequired = Math.max(minMRsRequired, occupiedMRs);
54 | }
55 | return minMRsRequired;
56 | }
57 |
58 | console.log(meetingRooms([[0, 30], [5, 10], [15, 20]]));
59 | console.log(meetingRooms([[0, 30], [5, 10], [10, 20]]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/MinimumCapacityToShipInDDays.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} weights
3 | * @param {number} days
4 | * @return {number}
5 | */
6 |
7 | /*
8 | Leetcode
9 | 1011. Capacity To Ship Packages Within D Days
10 |
11 | We were given we have to ship everything in 1 day = sum of all weights (55)
12 | we were given that we have to ship all items without any bar on the days = 10
13 |
14 | the range of my weights will lie between max value and total
15 |
16 | 10, 55 mid = 32, 2 days
17 |
18 | 10, 32 = 21, 3 days
19 | 10, 21 = 15,
20 |
21 | 15 and 16 are two values in which we can ship within 5 days
22 | minimize the maximum
23 | [F,F,F, T, T, T, T, T, F, F, F]
24 | leftmost from the right - hi = mid and low = mid + 1
25 |
26 | let lo = arr[0], hi = 0;
27 | for(let weight of weights) {
28 | if(lo < weight) {
29 | lo = weight;
30 | }
31 | hi += weight;
32 | }
33 | while(lo < hi) {
34 | const maxCapacity = parseInt((lo + hi) / 2);
35 | if(numberOfDaysToShip(weights, maxCapacity) < target) {
36 | lo = mid + 1;
37 | } else {
38 | hi = mid;
39 | }
40 | }
41 | return lo;
42 | }
43 |
44 | function numberOfDaysToShip(weights, maxCapacity) {
45 | let sum = 0, days = 1;
46 | for(let weight of weights) {
47 | if(sum + weight > maxCapacity) {
48 | days ++;
49 | sum = weight;
50 | }
51 | }
52 | return days;
53 | }
54 | */
55 | var shipWithinDays = function(weights, days) {
56 | let lo = weights[0], hi = 0;
57 | for(let weight of weights) {
58 | if(lo < weight) {
59 | lo = weight;
60 | }
61 | hi += weight;
62 | }
63 | while(lo < hi) {
64 | const maxCapacity = parseInt((lo + hi) / 2);
65 | if(numberOfDaysToShip(weights, maxCapacity) > days) {
66 | lo = maxCapacity + 1;
67 | } else {
68 | hi = maxCapacity;
69 | }
70 | }
71 | return lo;
72 | }
73 |
74 | function numberOfDaysToShip(weights, maxCapacity) {
75 | let sum = 0, days = 1;
76 | for(let weight of weights) {
77 | if(sum + weight > maxCapacity) {
78 | days ++;
79 | sum = weight;
80 | }
81 | else {
82 | sum += weight;
83 | }
84 | }
85 | return days;
86 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/MinimumSizeSubarraySum.js:
--------------------------------------------------------------------------------
1 | /*
2 | Leetcode 209. Minimum Size Subarray Sum
3 | */
4 | /**
5 | * @param {number} target
6 | * @param {number[]} nums
7 | * @return {number}
8 | */
9 | var minSubArrayLen = function(target, nums) {
10 | let total = 0;
11 | for(let num of nums) {
12 | total += num;
13 | }
14 | if(total < target) {
15 | return 0;
16 | }
17 | let lo = 1, hi = nums.length;
18 | while(lo < hi) {
19 | const subArrayLength = (lo + hi) >>> 1; //parseInt((low + hi)/2)
20 | if(isAnySubarraySumGreaterThanEqualToTarget(nums, subArrayLength, target)) {
21 | hi = subArrayLength;
22 | } else {
23 | lo = subArrayLength + 1;
24 | }
25 | }
26 | return lo;
27 | };
28 |
29 | function isAnySubarraySumGreaterThanEqualToTarget(arr, subArrayLength, target) {
30 | let sum = 0, i = 0;
31 | for(; i < subArrayLength; i++) {
32 | sum += arr[i];
33 | }
34 | if(sum >= target) {
35 | return true;
36 | }
37 | for(i = subArrayLength; i < arr.length; i++) {
38 | sum += arr[i] - arr[i-subArrayLength];
39 | if(sum >= target) {
40 | return true;
41 | }
42 | }
43 | return false;
44 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/MissingNumberInSortedArray.js:
--------------------------------------------------------------------------------
1 | function findMissingNumber(arr) {
2 | let lo = 0, hi = arr.length-1;
3 | while(lo < hi) {
4 | const mid = (lo + hi) >>> 1;
5 | if(arr[mid] === mid + 1) {
6 | lo = mid + 1;
7 | } else {
8 | hi = mid;
9 | }
10 | }
11 | return lo + 1;
12 | }
13 |
14 | console.log(findMissingNumber([1, 2, 3, 4, 6, 7, 8]));
15 | console.log(findMissingNumber([1, 2, 3, 4, 5, 6, 8, 9]));
16 | console.log(findMissingNumber([2, 3, 4, 5, 6, 7, 8, 9]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/NQueens.js:
--------------------------------------------------------------------------------
1 | function NQueens(N) {
2 | matrix = new Array(N)
3 | for(let i = 0; i < N; i++) {
4 | matrix[i] = new Array(N).fill(0);
5 | }
6 | if(NQueensUtil(matrix, 0, N)) {
7 | return matrix;
8 | } else {
9 | return [];
10 | }
11 | }
12 | const NQueensUtil = (matrix, row, N) => {
13 | if(row === N) {
14 | return true;
15 | }
16 | for(let i = 0; i < N; i++) {
17 | if(isSafe(matrix, row, i, N)) {
18 | matrix[row][i] = 'Q';
19 | if(NQueensUtil(matrix, row+1, N)) {
20 | return true;
21 | }
22 | matrix[row][i] = 0;
23 | }
24 | }
25 | return false;
26 | }
27 |
28 | function isSafe(matrix, row, col, N) {
29 | //vertical
30 | for(let i = 0; i < N; i++) {
31 | if(matrix[i][col] === 'Q') {
32 | return false;
33 | }
34 | }
35 |
36 | //diagonal
37 | for(let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
38 | if(matrix[i][j] === 'Q') {
39 | return false;
40 | }
41 | }
42 | //anti-diagonal
43 | for(let i = row - 1, j = col + 1; i >= 0 && j < N; i--, j++) {
44 | if(matrix[i][j] === 'Q') {
45 | return false;
46 | }
47 | }
48 | return true;
49 | }
50 | console.log(NQueens(4));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/PainterPartition.js:
--------------------------------------------------------------------------------
1 | /*
2 | You are provided with ‘n’ number of boards of length [b1, b2,..bn].There are ‘a’ painters available in the market
3 | and each painter takes one(1) unit time to paint one(1) unit of board. We need to find the minimum time to get the job done under the constraints that any painter will only paint contiguous sections of the board.
4 | Note Two painters cannot share boards to paint.
5 | Constrints
6 | a(1 <= n <= 10007
7 | arr(1 <= arr[i] <= 10^5)
8 | Input
9 | Array of boards(arr[])
10 | No of painters(a)
11 | Sample Input
12 | [10, 20, 30, 40]
13 | [0th byte, 1st byte], [2nd, 3rd byte], [4th byte, 5th byte]
14 |
15 | 2
16 | Sample Output
17 | 60
18 | */
19 |
20 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/CircularTour.js:
--------------------------------------------------------------------------------
1 | function circularTour(petrol, distance) {
2 | let totalRemainingPetrol = 0, remainingPetrolNow = 0;
3 | let startingPoint = 0;
4 |
5 | for(let i = 0; i < petrol.length; i++) {
6 | totalRemainingPetrol += petrol[i] - distance[i];
7 | remainingPetrolNow += petrol[i] - distance[i];
8 | if(remainingPetrolNow < 0) {
9 | remainingPetrolNow = 0;
10 | startingPoint = i+1;
11 | }
12 | }
13 |
14 | return totalRemainingPetrol >= 0 ? startingPoint : -1;
15 | }
16 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/Deque.js:
--------------------------------------------------------------------------------
1 | const Node = require("./Node");
2 | const Queue = require("./Queue");
3 |
4 | class Deque extends Queue {
5 | //additional support for
6 | //1. addFront()
7 | addFront = function(val) {
8 | if(this.isFull()) {
9 | throw Error("Queue is already full!");
10 | }
11 | const newNode = new Node(val);
12 | //1. if there are no elements in the queue currently
13 | if(this.isEmpty()) {
14 | this.front = this.rear = newNode;
15 | } else {
16 | this.front.prev = newNode;
17 | newNode.next = this.front;
18 | this.front = newNode;
19 | }
20 | this.size++;
21 | return newNode;
22 | }
23 |
24 | deleteRear = function() {
25 | if(this.isEmpty()) {
26 | throw Error("Queue is already empty!");
27 | }
28 | const deletedNode = this.rear;
29 | if(this.size === 1) {
30 | this.front = this.rear = null;
31 | } else {
32 | this.rear = this.rear.prev;
33 | this.rear.next = null;
34 | deletedNode.prev = null;
35 | }
36 | this.size--;
37 | return deletedNode;
38 | }
39 |
40 | getRear = function() {
41 | return this.isEmpty() ? null : this.rear.val;
42 | }
43 | }
44 |
45 | module.exports = Deque;
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/FirstNonRepeatingCharacter.js:
--------------------------------------------------------------------------------
1 | const Queue = require("./Queue");
2 |
3 | class FirstNonRepeatingCharacterFinder {
4 | constructor() {
5 | this.queue = new Queue();
6 | this.freq = new Array(26).fill(0);
7 | }
8 | firstNonRepeatingCharacter = function(character) {
9 | const asciiOfA = 'a'.charCodeAt();
10 | const positionOfCharacter = character.charCodeAt() - asciiOfA;
11 | if(this.freq[positionOfCharacter]++ === 0) {
12 | this.queue.enqueue(character);
13 | }
14 | while(!this.queue.isEmpty()) {
15 | const asciiOfFrontChar = this.queue.getFront().charCodeAt() - asciiOfA;
16 | if(this.freq[asciiOfFrontChar] > 1) {
17 | this.queue.dequeue();
18 | } else {
19 | break;
20 | }
21 | }
22 | return this.queue.isEmpty() ? -1 : this.queue.getFront();
23 | }
24 | }
25 |
26 | const str = "abacacb";
27 | const resultFinder = new FirstNonRepeatingCharacterFinder();
28 | for(const char of str) {
29 | console.log(resultFinder.firstNonRepeatingCharacter(char));
30 | }
31 |
32 | //a - a
33 | //b - a
34 | //a - b
35 | //b - -1
36 |
37 | // [a - 2, b - 2, ]
38 | //a, b, a, b
39 |
40 | //a, b, a, c, a, c, b
41 |
42 | /*
43 | freq [a - 2, b - 2, c - 2];
44 | queue addToRear - []
45 | a, a, b, b, b, b, -1
46 | */
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/LemonadeChange.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} bills
3 | * @return {boolean}
4 | */
5 | var lemonadeChange = function(bills) {
6 | let notesOf5 = 0, notesOf10 = 0;
7 | for(const bill of bills) {
8 | if(bill === 5) {
9 | notesOf5++;
10 | } else if(bill === 10) {
11 | if(notesOf5-- === 0) {
12 | return false;
13 | }
14 | notesOf10++;
15 | } else {
16 | if(notesOf5 === 0) {
17 | return false;
18 | }
19 | if(notesOf10) {
20 | notesOf10--;
21 | notesOf5--;
22 | } else {
23 | notesOf5 -= 3;
24 | }
25 | if(notesOf5 < 0) {
26 | return false;
27 | }
28 | }
29 | }
30 | return true;
31 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/Node.js:
--------------------------------------------------------------------------------
1 | class Node {
2 | constructor(val) {
3 | this.val = val;
4 | this.next = null;
5 | this.prev = null;
6 | }
7 | }
8 |
9 | module.exports = Node;
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/OperationsOnDeque.js:
--------------------------------------------------------------------------------
1 | const Deque = require("./Deque");
2 |
3 | const deque = new Deque();
4 | deque.enqueue(2);
5 | deque.enqueue(3);
6 | deque.addFront(1);
7 | deque.traverse();
8 | deque.deleteRear();
9 | deque.enqueue(4);
10 | deque.dequeue();
11 | deque.traverse();
12 |
13 | //1 2 3
14 | //2 4
15 |
16 | //1 2 3 4 5
17 | //5 4 3 2 1
18 |
19 | //1. enqueue, 2. dequeue
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/OperationsOnQueue.js:
--------------------------------------------------------------------------------
1 | const Deque = require("./Deque");
2 | const Queue = require("./Queue");
3 |
4 | const queue = new Queue(5);
5 | //const queue = new Queue(5);
6 | //------------------enqueue----------------
7 | try {
8 | queue.enqueue("Abhigyan");
9 | console.log(queue.getFront());
10 | queue.enqueue("Pranit");
11 | queue.enqueue("Samik");
12 | queue.enqueue("Rehan");
13 | queue.enqueue("Vinayak");
14 | //throw isFull error
15 | queue.enqueue("Nayanava");
16 | } catch (error) {
17 | console.log(error.message);
18 | }
19 |
20 | //------------------dequeue----------------
21 | try {
22 | let dequeued = queue.dequeue();
23 | console.log("Dequeued person", dequeued.val);
24 | console.log("Person in the front", queue.getFront());
25 | dequeued = queue.dequeue();
26 | console.log("Dequeued person", dequeued.val);
27 | console.log("Person in the front", queue.getFront());
28 | dequeued = queue.dequeue();
29 | console.log("Dequeued person", dequeued.val);
30 | console.log("Person in the front", queue.getFront());
31 | dequeued = queue.deleteRear();
32 | console.log("Dequeued person", dequeued.val);
33 | console.log("Person in the front", queue.getFront());
34 | dequeued = queue.dequeue();
35 | console.log("Dequeued person", dequeued.val);
36 | console.log("Person in the front", queue.getFront());
37 | console.log(queue.isEmpty())
38 | dequeued = queue.dequeue();
39 | } catch(error) {
40 | console.log(error.message);
41 | }
42 |
43 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/PossibleToProvideChange.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/Module - 3/AdvancedPS/Queues/PossibleToProvideChange.js
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/PrintNumbersInBinaryFormat.js:
--------------------------------------------------------------------------------
1 | const Queue = require("./Queue");
2 |
3 | function printFirstNNumbersInBinary(n) {
4 | const queue = new Queue(n);
5 | queue.enqueue("1");
6 | const result = new Array(n);
7 | let index = 0;
8 | while(index < n) {
9 | const val = queue.dequeue();
10 | result[index++] = val;
11 | if(index + queue.length() < n) {
12 | queue.enqueue(val + "0");
13 | }
14 | if(index + queue.length() < n) {
15 | queue.enqueue(val + "1");
16 | }
17 |
18 | }
19 | console.log(queue.length());
20 | return result;
21 | }
22 | //10, 11,
23 | //11, 100, 101
24 | //100, 101, 110, 111
25 |
26 | console.log(printFirstNNumbersInBinary(5));
27 | console.log(printFirstNNumbersInBinary(10));
28 | console.log(printFirstNNumbersInBinary(12));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/Queue.js:
--------------------------------------------------------------------------------
1 | const Node = require("./Node");
2 |
3 | class Queue {
4 | constructor(maxCapacity = -1) {
5 | if(maxCapacity !== -1 && maxCapacity <= 0) {
6 | throw new Error("Invalid queue capacity. ")
7 | }
8 | this.maxCapacity = maxCapacity;
9 | this.front = null;
10 | this.rear = null;
11 | this.size = 0;
12 | }
13 |
14 | isEmpty = function() {
15 | return this.size === 0;
16 | }
17 |
18 | isFull = function () {
19 | return this.size === this.maxCapacity;
20 | }
21 |
22 | length = function () {
23 | return this.size;
24 | }
25 | // same as insertAtEnd of linkedList.
26 | enqueue = function (val) {
27 | if(this.isFull()) {
28 | throw new Error("The Queue has reached its maximum capacity!");
29 | }
30 | const newNode = new Node(val);
31 | if(this.front === null) {
32 | this.front = this.rear = newNode;
33 | } else {
34 | this.rear.next = newNode;
35 | newNode.prev = this.rear;
36 | this.rear = newNode;
37 | //or
38 | //this.rear.next = this.rear
39 | }
40 | this.size++;
41 | return newNode;
42 | }
43 |
44 | dequeue = function() {
45 | if(this.isEmpty()) {
46 | throw new Error("The Queue is already empty!");
47 | }
48 | let deletedNode;
49 | deletedNode = this.front;
50 | if(this.size === 1) {
51 | this.front = this.rear = null;
52 | } else {
53 | this.front = this.front.next;
54 | this.front.prev = null;
55 | deletedNode.next = deletedNode.prev = null;
56 | }
57 | this.size--;
58 | return deletedNode.val;
59 | }
60 |
61 | getFront = function() {
62 | return this.isEmpty() ? null : this.front.val;
63 | }
64 |
65 | traverse() {
66 | let temp = this.front;
67 | while(temp != null) {
68 | process.stdout.write(temp.val + " ");
69 | temp = temp.next;
70 | }
71 | console.log();
72 | }
73 | }
74 |
75 | module.exports = Queue;
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/QueueUsingStack.js:
--------------------------------------------------------------------------------
1 | Array.prototype.isEmpty = function() {
2 | return !this || !this.length;
3 | }
4 | class QueueUsingStack {
5 | constructor() {
6 | this.s1 = new Array();
7 | this.s2 = new Array();
8 | }
9 |
10 | enqueue = function (value) {
11 | while(!this.s2.isEmpty()) {
12 | this.s1.push(this.s2.pop());
13 | }
14 | this.s1.push(value);
15 | }
16 |
17 | dequeue = function () {
18 | while(!this.s1.isEmpty()) {
19 | this.s2.push(this.s1.pop());
20 | }
21 | return this.s2.isEmpty() ? null : this.s2.pop();
22 | }
23 | }
24 |
25 | const queue = new QueueUsingStack();
26 | queue.enqueue(1);
27 | queue.enqueue(2);
28 | queue.enqueue(3);
29 |
30 | console.log(queue.dequeue());
31 | queue.enqueue(4);
32 | console.log(queue.dequeue());
33 | console.log(queue.dequeue());
34 | console.log(queue.dequeue());
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/ReverseFirstKElementsInQueue.js:
--------------------------------------------------------------------------------
1 | const Queue = require("./Queue");
2 |
3 | function reverseKElementsInQueue(queue, n, k) {
4 | const stack = new Array();
5 | let count = 0;
6 | while(++count <= k) {
7 | stack.push(queue.dequeue());
8 | }
9 | while(stack.length) {
10 | queue.enqueue(stack.pop());
11 | }
12 | count = 0;
13 | while(++count <= n-k) {
14 | queue.enqueue(queue.dequeue());
15 | }
16 | }
17 |
18 | const queue = new Queue();
19 | for(let i = 1; i <= 10; i++) {
20 | queue.enqueue(i);
21 | }
22 | reverseKElementsInQueue(queue, 10, 4);
23 | queue.traverse();
24 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Queues/SlidingWindowMaximum.js:
--------------------------------------------------------------------------------
1 | //[1, 3, -1, -3, 5, 3, 6, 7] length = 8, k = 3
2 | // 3, 3, 5, 5, 6, 7 => 6 n - k + 1
3 | const Deque = require("./Deque");
4 | function slidingWindowMaximum(arr, k) {
5 | const res = new Array(arr.length - k + 1);
6 | const deque = new Deque();
7 | let index = 0;
8 | for(let i = 0; i < k; i++) {
9 | while(!deque.isEmpty() && arr[deque.getRear()] < arr[i]) {
10 | deque.deleteRear();
11 | }
12 | deque.enqueue(i);
13 | }
14 | res[index++] = arr[deque.getFront()];
15 | for(let i = k; i < arr.length; i++) {
16 | while(!deque.isEmpty() && deque.getFront() <= i-k){
17 | deque.dequeue();
18 | }
19 | while(!deque.isEmpty() && arr[deque.getRear()] < arr[i]) {
20 | deque.deleteRear();
21 | }
22 | deque.enqueue(i);
23 | res[index++] = arr[deque.getFront()];
24 | }
25 | return res;
26 | }
27 |
28 | console.log(slidingWindowMaximum([1, 3, -1, -3, 5, 3, 6, 7], 3));
29 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/RadixSort.js:
--------------------------------------------------------------------------------
1 | /*
2 | 1. getDigits(maxNumber)
3 | 2. getDigitAtPosition(number, divisor)
4 | main function - radixSort(arr)
5 | */
6 |
7 | /*Homework
8 | //k = 4 and maxDigit has 3 digits, how long will we run?? we will run up to 3 digits only
9 | // if k is less than digits in maxNumber then we will run up to k digits.
10 | // => return the sorted array till that point.
11 |
12 | // Question 2: - given a string which contains characters or alphabets, we have to sort the string. only one string not multiple strings.
13 | // input :- unacademy
14 | // output :- aacdemnuy
15 |
16 | */
17 | const radixSort = (arr) => {
18 | //1. find the maximum number in the array
19 | let maxNumber = arr[0];
20 | for(let number of arr) {
21 | maxNumber = Math.max(number, maxNumber);
22 | }
23 | let maxDigits = getdigits(maxNumber);
24 | let divisor = 1;
25 | while(--maxDigits >= 0) {
26 | const buckets = new Array(10);
27 | for(let i = 0; i < buckets.length; i++) {
28 | buckets[i] = [];
29 | }
30 | for(let number of arr) {
31 | const index = getDigitAtPosition(number, divisor);
32 | buckets[index].push(number);
33 | }
34 | console.log(buckets);
35 | divisor *= 10;
36 | let index = 0;
37 | for(const bucket of buckets) {
38 | for(const number of bucket) {
39 | arr[index++] = number;
40 | }
41 | }
42 | }
43 | return arr;
44 | }
45 |
46 | const getdigits = (maxNumber) => {
47 | let count = 0;
48 | while(maxNumber > 0) {
49 | maxNumber = parseInt(maxNumber / 10);
50 | count++;
51 | }
52 | return count;
53 | }
54 |
55 | const getDigitAtPosition = (number, divisor) => {
56 | return parseInt(number/divisor) % 10;
57 | }
58 |
59 | console.log(radixSort([237, 146, 259, 348, 152, 163, 235, 48, 36, 62]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/RatInAMaze.js:
--------------------------------------------------------------------------------
1 |
2 | //avoid using global variables try returning values instead from deeper recursions
3 | // let countOfPaths = 0;
4 | function countPathsInMaze(matrix) {
5 | return countPathsInMazeUtil(matrix, 0, 0);
6 | //bad practice below approach
7 | // countPathsInMazeUtil(matrix, 0, 0);
8 | // return countOfPaths;
9 | }
10 | let rows = [0, 1];
11 | let cols = [1, 0];
12 |
13 | function countPathsInMazeUtil(matrix, rowIndex, colIndex) {
14 | if(rowIndex === matrix.length - 1 && colIndex === matrix[0].length-1) {
15 | return 1;
16 | //bad practice below approach
17 | //countOfPaths++;
18 | }
19 | let countOfPaths = 0;
20 | for(let i = 0; i < rows.length; i++) {
21 | const nextRow = rowIndex + rows[i];
22 | const nextCol = colIndex + cols[i];
23 | if(isSafe(matrix, nextRow, nextCol)) {
24 | countOfPaths += countPathsInMazeUtil(matrix, nextRow, nextCol);
25 |
26 | }
27 | }
28 | return countOfPaths;
29 | }
30 |
31 | function isSafe(matrix, row, col) {
32 | return row >= 0 && row < matrix.length && col >= 0 && col < matrix[0].length
33 | && matrix[row][col] === 1
34 | }
35 |
36 | console.log(countPathsInMaze([[1, 0, 0],
37 | [1, 1, 1],
38 | [1, 1, 1]]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/RelativeSortArray.js:
--------------------------------------------------------------------------------
1 | /**
2 | * LeetCode 1122. Relative Sort Array
3 | * @param {number[]} arr1
4 | * @param {number[]} arr2
5 | * @return {number[]}
6 | */
7 | var relativeSortArray = function(arr1, arr2) {
8 | const freqArr = new Array(1001).fill(0);
9 | for(let number of arr1) {
10 | freqArr[number]++;
11 | }
12 | let index = 0;
13 | for(let number of arr2) {
14 | for(let it = 1; it <= freqArr[number]; it++) {
15 | arr1[index++] = number;
16 | }
17 | freqArr[number] = 0;
18 | }
19 | for(let i = 0; i < 1001; i++) {
20 | if(freqArr[i] === 0) {
21 | continue;
22 | }
23 | for(let it = 1; it <= freqArr[i]; it++) {
24 | arr1[index++] = i;
25 | }
26 | }
27 | return arr1;
28 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/RevisionBinarySearch.js:
--------------------------------------------------------------------------------
1 | /*
2 | T(n) = T(n-k) + 2
3 | T(n-1) = T(n-k) + 2 + 2
4 | T(n) = T(1) + 2+2+2+....+K
5 | T(n) = T(1) + 2*k
6 | T(n) = O(n)
7 |
8 | T(n) = T(n/2) + 2
9 | = T(n/4) + 2 + 2
10 | = T(n/8) + 2 + 2 + 2
11 | .
12 | .
13 | .
14 | .
15 | = T(n/2^k) + 2 * k
16 | n/2^k = 1
17 | n = 2^k
18 | logn = log2^k
19 | logn = klog2
20 | k = logn/log2
21 | k = log(2)n
22 | */
23 |
24 | const binarySearchIterative = (arr, target) => {
25 | let lo = 0, hi = arr.length-1;
26 | while(lo <= hi) {
27 | const mid = parseInt((lo + hi) / 2);
28 | if(arr[mid] === target) {
29 | return mid;
30 | } else if(arr[mid] < target) {
31 | lo = mid + 1;
32 | } else {
33 | hi = mid - 1;
34 | }
35 | }
36 | return -(lo + 1);
37 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Sorting/MaximumAbsoluteDifference.js:
--------------------------------------------------------------------------------
1 | const maxAbsoluteDifference = (arr, k) => {
2 | arr.sort((a, b) => {
3 | return a - b;
4 | });
5 | console.log(arr);
6 | let i = 0, j = arr.length - 1;
7 | let sumOfMin = 0, sumOfMax = 0;
8 | for(; i < k; i++, j--) {
9 | sumOfMin += arr[i];
10 | sumOfMax += arr[j];
11 | }
12 | let remaining = 0;
13 | for(let next = i; next <= j; next++) {
14 | remaining += arr[next];
15 | }
16 | return Math.max(Math.abs(sumOfMax + remaining - sumOfMin), Math.abs(sumOfMin + remaining - sumOfMax));
17 | }
18 |
19 | console.log(maxAbsoluteDifference([18,4,15,12,10], 2));
20 |
21 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Sorting/SortUsingStack.js:
--------------------------------------------------------------------------------
1 | Array.prototype.peek = function() {
2 | return this[this.length-1];
3 | }
4 | Array.prototype.isEmpty = function () {
5 | return !(this && this.length);
6 | }
7 | const sortUsingStack = function (arr) {
8 | const outputStack = new Array();
9 |
10 | while(!arr.isEmpty()) {
11 | let curr = arr.pop();
12 | while(!outputStack.isEmpty() && outputStack.peek() > curr) {
13 | arr.push(outputStack.pop());
14 | }
15 | outputStack.push(curr);
16 | }
17 | return outputStack;
18 | }
19 |
20 | console.log(sortUsingStack([18, 4, 15, 12, 10]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/SplitArrayLargestSum.js:
--------------------------------------------------------------------------------
1 | /*
2 | Leetcode: 410
3 | Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
4 | Write an algorithm to minimize the largest sum among these m subarrays.
5 | */
6 | /**
7 | * @param {number[]} nums
8 | * @param {number}
9 | * @return {number}
10 | */
11 | var splitArray = function(nums, m) {
12 | let lo = max(nums), hi = total(nums);
13 | while(lo < hi) {
14 | const maximumSum = (lo + hi) >>> 1;
15 | if(numberOfSubArraysWithMaximumSum(nums, maximumSum) > m) {
16 | lo = maximumSum+1;
17 | } else {
18 | hi = maximumSum;
19 | }
20 | }
21 | return lo;
22 | };
23 |
24 | function max(arr) {
25 | let max = arr[0];
26 | for(let num of arr) {
27 | max = max > num ? max : num;
28 | }
29 | return max;
30 | }
31 | function total(arr) {
32 | return arr.reduce((sum, curr) => sum += curr, 0);
33 |
34 | }
35 |
36 |
37 | function numberOfSubArraysWithMaximumSum(arr, maximumSum) {
38 | let sum = 0, countOfSubArrays = 1;
39 | for(let num of arr) {
40 | if(sum + num > maximumSum) {
41 | countOfSubArrays++;
42 | sum = num;
43 | } else {
44 | sum += num;
45 | }
46 | }
47 | return countOfSubArrays;
48 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/SquarefulArray.js:
--------------------------------------------------------------------------------
1 | function isPerfectSquare(sum) {
2 | for(i = 1; i * i <= sum; i++) {
3 | if(i * i === sum) {
4 | return true;
5 | }
6 | }
7 | return false;
8 | }
9 |
10 | function dfs(arr) {
11 | const visited = new Array(arr.length).fill(false);
12 | let countOfSquarefulArrays = 0;
13 | for(let i = 0; i < arr.length; i++) {
14 | visited[i] = true;
15 | countOfSquarefulArrays += dfsUtil(arr, visited, 1, arr[i]);
16 | visited[i] = false;
17 | }
18 | return countOfSquarefulArrays;
19 | }
20 | function dfsUtil(arr, visited, index, value) {
21 | if(index === arr.length) {
22 | return 1;
23 | }
24 | let countOfSquarefulArrays = 0;
25 | for(let i = 0; i < arr.length; i++) {
26 | if(!visited[i] && isPerfectSquare(value + arr[i])) {
27 | visited[i] = true;
28 | countOfSquarefulArrays += dfsUtil(arr, visited, index+1, arr[i]);
29 | visited[i] = false;
30 | }
31 | }
32 | return countOfSquarefulArrays;
33 | }
34 |
35 | console.log(dfs([1, 17, 8]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/InfixToPostfix.js:
--------------------------------------------------------------------------------
1 | const precedence = (op) => {
2 | switch (op) {
3 | case '^':
4 | return 3;
5 | case '*':
6 | case '/':
7 | return 2;
8 | case '+':
9 | case '-':
10 | return 1;
11 | default:
12 | return -1;
13 | }
14 | }
15 | const isCharacterAnOperand = (character) => {
16 | return (character.charCodeAt() >= 'a'.charCodeAt() && character.charCodeAt() <= 'z'.charCodeAt())
17 | || (character.charCodeAt() >= 'A'.charCodeAt() && character.charCodeAt() <= 'Z'.charCodeAt());
18 | }
19 |
20 | Array.prototype.isEmpty = function() {
21 | return !this || !this.length;
22 | }
23 |
24 | Array.prototype.peek = function() {
25 | return this[this.length-1];
26 | }
27 |
28 | const infixToPostfix = (string) => {
29 | const resultArr = [];
30 | const stack = [];
31 |
32 | for(const character of string) {
33 | if(isCharacterAnOperand(character)) {
34 | resultArr.push(character);
35 | } else {
36 | /*
37 | 1. it can be open parenthesis
38 | 2. it can be closing parenthesis
39 | 3. it can have an operator - check for precedence
40 | */
41 | if(character == '(') {
42 | stack.push(character);
43 | } else if(character == ')') {
44 | while(stack.peek() !== '(') {
45 | resultArr.push(stack.pop());
46 | }
47 | stack.pop();
48 | } else {
49 | while(!stack.isEmpty() && precedence(stack.peek()) >= precedence(character)) {
50 | resultArr.push(stack.pop());
51 | }
52 | stack.push(character);
53 | }
54 | }
55 | }
56 | while(!stack.isEmpty()) {
57 | resultArr.push(stack.pop());
58 | }
59 | return resultArr;
60 | }
61 |
62 | process.stdout.write(infixToPostfix("a+b*c^d-e^(f+g*h)-i").join(""));
63 | console.log();
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/MatchBrackets.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Homework
4 | Given a string s of brackets `( { [ ] } )` , you need to determine if the provided string S is valid or not? Condition for the string to be valid:
5 | 1. Each opening bracket should have there corresponding closing bracket
6 | 2. Order of the opening and the closing bracket should be maintained
7 | Sample Input-1: (({}))
8 | Output:
9 | True
10 | */
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/MaximumOfMinimumOfAllWindowSizes.js:
--------------------------------------------------------------------------------
1 | Array.prototype.isEmpty = function() {
2 | return !this || !this.length;
3 | }
4 |
5 | Array.prototype.peek = function() {
6 | return this[this.length-1];
7 | }
8 |
9 | const previousSmallerOnLeft = (arr) => {
10 | const stack = [];
11 | const PSL = new Array(arr.length);
12 | for(let i = 0; i < arr.length; i++) {
13 | while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
14 | stack.pop();
15 | }
16 | PSL[i] = stack.isEmpty() ? -1 : stack.peek();
17 | stack.push(i);
18 | }
19 | return PSL;
20 | }
21 |
22 | const nextSmallerOnRight = (arr) => {
23 | const stack = [];
24 | const NSR = new Array(arr.length);
25 | for(let i = arr.length-1; i >= 0; i--) {
26 | while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
27 | stack.pop();
28 | }
29 | NSR[i] = stack.isEmpty() ? arr.length : stack.peek();
30 | stack.push(i);
31 | }
32 | return NSR;
33 | }
34 |
35 | const maximumOfMinimumOfAllWindowSizes = (arr) => {
36 | const PSL = previousSmallerOnLeft(arr);
37 | const NSR = nextSmallerOnRight(arr);
38 |
39 | const resultArr = new Array(arr.length).fill(Number.MIN_SAFE_INTEGER);
40 | for(let i = 0; i < arr.length; i++) {
41 | const length = NSR[i] - PSL[i] - 1;
42 | resultArr[length-1] = Math.max(resultArr[length-1], arr[i]);
43 | }
44 |
45 | for(let i = arr.length - 2; i >= 0; i--) {
46 | resultArr[i] = Math.max(resultArr[i], resultArr[i+1]);
47 | }
48 | return resultArr;
49 | }
50 |
51 | console.log(maximumOfMinimumOfAllWindowSizes([10, 20, 30, 50, 10, 70, 30]));
52 | console.log(maximumOfMinimumOfAllWindowSizes([10, 20, 30]));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/MinimumDeletionsToBalanceString.js:
--------------------------------------------------------------------------------
1 | /*
2 | Leetcode - 1653
3 | Given a string S made up of characters `a` and `b`. You need to count the minimum deletion needed to make the string balanced.
4 | A string is said to be balanced only if there doesnt exists a pair (i,j) where i arr[i]) {
15 | res[i] = arr[j];
16 | break;
17 | }
18 | }
19 | }
20 | return res;
21 | */
22 |
23 | Array.prototype.top = function() {
24 | if(this.length) {
25 | return this[this.length-1];
26 | }
27 | }
28 | function nextGreaterElement(arr) {
29 | const len = arr.length;
30 | const res = new Array(len).fill(-1);
31 |
32 | const stack = new Array();
33 | for(let i = 0; i < len; i++) {
34 | while(stack.length && arr[stack.top()] < arr[i]) {
35 | res[stack.pop()] = arr[i];
36 | }
37 | stack.push(i);
38 | }
39 | return res;
40 | }
41 |
42 | console.log(nextGreaterElement([2, 7, 3, 5, 4, 6, 8]));
43 | console.log(nextGreaterElement([8, 7, 6, 5, 4, 3, 8]));
44 | console.log(nextGreaterElement([7, 6, 5, 4, 3, 2]));
45 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/RecursivelyReverseStack.js:
--------------------------------------------------------------------------------
1 | const Stack = require("../LinkedLists/stack");
2 | /*
3 | Reverse a stack recursively.
4 | Using the functionalities provided by the stack.
5 | Reverse the stack recursively.
6 | You are only allowed to use the functions push(), pop() and peek();
7 |
8 |
9 | 3 -> 2 -> 1
10 | */
11 |
12 | function reverseAStack(stack, resultStack) {
13 | if(stack.isEmpty()) {
14 | return;
15 | }
16 | const popped = stack.pop().val;
17 | resultStack.push(popped);
18 | reverseAStack(stack, resultStack);
19 | }
20 |
21 | const st = new Stack();
22 | st.push(1);
23 | st.push(2);
24 | st.push(3);
25 | console.log(st);
26 | const resultStack = new Stack();
27 | reverseAStack(st, resultStack);
28 | console.log(resultStack);
29 |
30 | values = inputs.map(input => {
31 | key = input.key;
32 | return {...input}
33 | })
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/RemoveAllAdjacentDuplicates.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 1047
3 | * 1047. Remove All Adjacent Duplicates In String
4 | * @param {string} s
5 | * @return {string}
6 | */
7 | Array.prototype.top = function () {
8 | if(this.length) {
9 | return this[this.length - 1];
10 | }
11 | return undefined;
12 | }
13 |
14 | var removeDuplicates = function(s) {
15 | const st = new Array();
16 | for(const ch of s) {
17 | if(st.length && st.top() === ch) {
18 | st.pop();
19 | } else {
20 | st.push(ch);
21 | }
22 | }
23 | return st.join("");
24 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/RemoveKDigits.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode 402
3 | * @param {string} num
4 | * @param {number} k
5 | * @return {string}
6 | */
7 |
8 | Array.prototype.isEmpty = function() {
9 | return this.length === 0;
10 | }
11 | Array.prototype.peek = function() {
12 | return this[this.length-1];
13 | }
14 |
15 | var removeKdigits = function(num, k) {
16 |
17 | // 1 4 3 2 2 1 9 choose x among some these digits
18 | //1 + 1 + 1
19 | // 1 2
20 |
21 | //1 0 2 0 0
22 | //1
23 | //0 2 0 0 - 200
24 |
25 | // 4 3 2 1 9 9 , k = 3
26 | /* 1 + 1 + 1
27 | 1 + 9 + 9 = 199
28 | */
29 | const stack = new Array();
30 | for(const char of num) {
31 | while(!stack.isEmpty() && k > 0 && stack.peek() > parseInt(char)) {
32 | stack.pop();
33 | k--;
34 | }
35 | stack.push(parseInt(char));
36 | }
37 |
38 | let result = "";
39 | for(let i = 0; i < stack.length - k; i++) {
40 | if(i === 0 && stack[i] === 0) {
41 | while(stack[i] === 0) {
42 | i++;
43 | }
44 | i--;
45 | } else {
46 | result += stack[i];
47 | }
48 | }
49 | return result === "" ? "0" : result;
50 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/Stack.txt:
--------------------------------------------------------------------------------
1 | 1. A LIFO based Data structure where LIFO stands for
2 | Last in first out.
3 | 2. Stack datastructures provide us with three basic functionalities
4 | 2.1) push() - pushes to the top of the stack.
5 | 2.2) pop() - pops the first element from the top of the stack.
6 | 2.3) top()/peek() - returns the value on the top of the stack.
7 | **NOTE- it doesn't pop the element from the top.
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/SumOfSubarrayMinimums.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Leetcode - 907
3 | * 907. Sum of Subarray Minimums
4 | * @param {number[]} arr
5 | * @return {number}
6 | */
7 | var sumSubarrayMins = function(arr) {
8 |
9 | };
10 |
11 | //[3, 1, 2, 4] -> [3], [1], [2], [4], [3, 1], [1, 2], [2, 4], [3, 1, 2], [1, 2, 4], [3, 1, 2, 4]
12 | // 3, 1, 2, 4, 1, 1, 2, 1, 1, 1
13 | //total = 17
14 | /*
15 | [3, 1, 2, 4] - [2, 4] - [2], [2, 4] - 2 * count on right hand side * count on left hand side
16 |
17 |
18 | [3, 4, 2, 5] - [3, 4, 2], [4, 2], [2], [2, 5], , [4, 2, 5], [3, 4, 2, 5] - 12
19 |
20 | on right hand side count = (4 - 2) = 2,
21 | on left hand side count = (2 - (-1)) = 3
22 | overall sum with contribution of 2 = 3 * 2 * 2 = 8
23 |
24 | [3] - 1,
25 | [2-0] - 2
26 |
27 | 3 * 2 = 6
28 | [3], [3, 4] = 3 + 3 = 6
29 |
30 | for 4
31 | count on left = 1
32 | count on right = 1 - [4]
33 | [4] = 1 * 4 * 1
34 |
35 | // two requirements -
36 | 1. finding the previous smaller element - index
37 | 2. finding the next smaller element - index
38 | */
39 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/ValidParenthesis.js:
--------------------------------------------------------------------------------
1 | /*
2 | Implement a function that takes a string which contains various parenthesis like ( ) { } [ ] as an
3 | input and returns whether it checks if it is the valid parenthesis or not .
4 | ● E.g. when we pass the following string to the function "({[]})” it should return true and if we pass
5 | this string “{[(]}]” , it should return false
6 | ● Try to implement this logic using following stack functions : push , pop , isEmpty
7 | */
8 |
9 | const Stack = require("./stack");
10 |
11 | function isvalidParentheses(parentheses) {
12 | if(parentheses.length%2 !== 0) {
13 | return false;
14 | }
15 | const stack = new Stack(parentheses.length/2);
16 | for(let bracket of parentheses) {
17 | if(isClosingBracket(bracket)) {
18 | if(stack.isEmpty()) {
19 | return false;
20 | }
21 | const openingBracket = stack.pop().val;
22 | if(!isMatchingBrackets(openingBracket, bracket)) {
23 | return false;
24 | }
25 | } else {
26 | if(stack.isFull()) {
27 | return false;
28 | }
29 | stack.push(bracket);
30 | }
31 | }
32 | return stack.isEmpty();
33 | }
34 |
35 | function isClosingBracket(bracket) {
36 | return bracket === ')' || bracket === '}' || bracket === ']';
37 | }
38 |
39 | function isMatchingBrackets(openingBracket, closingBracket) {
40 | switch (closingBracket) {
41 | case '}':
42 | return openingBracket === '{';
43 | case ')':
44 | return openingBracket === '(';
45 | case ']':
46 | return openingBracket === '[';
47 | default:
48 | return false;
49 | }
50 | }
51 |
52 | console.log(isvalidParentheses('[{()}]'));
53 | console.log(isvalidParentheses('[{()}'));
54 | console.log(isvalidParentheses('[{()'));
55 | console.log(isvalidParentheses(')}]({['));
56 | console.log(isvalidParentheses('(()()[[]]{{{}}})'))
57 | console.log(isvalidParentheses('()()[[]]{{{}}}))'))
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Stacks/stack.js:
--------------------------------------------------------------------------------
1 |
2 | class Stack {
3 | constructor(capacity = -1) {
4 | this.top = null;
5 | if(capacity === -1) {
6 | capacity = Infinity;
7 | }
8 | else if(capacity <= 0) {
9 | throw new Error("the capacity of the stack should be at least 1");
10 | }
11 | this.capacity = capacity; // the maximum number of elements the stack can hold
12 | this.size = 0; // the current number of elements in the stack.
13 | }
14 | push(val) {
15 | if(this.isFull()) {
16 | throw new Error(`the stack has already reached its maximum capacity of ${this.capacity}`);
17 | }
18 | const newNode = new Node(val);
19 | if(!this.top) {
20 | this.top = newNode;
21 | } else {
22 | newNode.next = this.top;
23 | this.top = newNode;
24 | }
25 | this.size++;
26 | return newNode;
27 | }
28 | pop() {
29 | if(this.isEmpty()) {
30 | throw new Error('Stack is already empty');
31 | }
32 | let toBePopped = this.top;
33 | if(!this.top.next) {
34 | this.top = null;
35 | } else {
36 | this.top = this.top.next;
37 | }
38 | this.size--;
39 | return toBePopped;
40 | }
41 |
42 | peek() {
43 | return this.top;
44 | }
45 | isEmpty() {
46 | return this.top === null
47 | }
48 |
49 | isFull() {
50 | return this.size === this.capacity;
51 | }
52 | }
53 |
54 | class Node {
55 | constructor(val) {
56 | this.val = val;
57 | this.next = null;
58 | }
59 | }
60 |
61 |
62 | try {
63 | const stack = new Stack(2);
64 | stack.push(1);
65 | stack.push(2);
66 | stack.push(3);
67 | console.log(stack.pop().val);
68 | console.log(stack.pop().val);
69 | stack.push(4);
70 | console.log(stack.pop().val);
71 | console.log(stack.peek().val);
72 | stack.push(5);
73 | console.log(stack.peek().val);
74 |
75 | console.log(stack.pop().val);
76 | console.log(stack.pop().val);
77 | console.log(stack.pop().val);
78 | } catch (error) {
79 | console.log(error.message);
80 | }
81 |
82 | module.exports = Stack;
83 | /*
84 | Homework
85 | Implement a function called insertElementAtBottom which takes a number as input and it inserts the
86 | value at the bottom of that stack.
87 | */
88 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/ThreeSum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number[][]}
4 | */
5 | var threeSum = function(arr) {
6 | /*
7 | first lets solve considering that there are no duplicates in the array
8 | */
9 | arr.sort((a,b) => a-b);
10 | const length = arr.length;
11 | const result = new Array();
12 | const target = 0;
13 | // {-4, -1, 0, 1, 2}, length = 5,
14 | // [ 0, 1, 2, 3, 4], only up to 2, length - 3
15 | for(let i = 0; i < length - 2; i++) {
16 | if(i > 0 && arr[i] === arr[i-1]) {
17 | continue;
18 | }
19 | let j = i + 1, k = length - 1;
20 | const remainingTarget = target - arr[i];
21 | while( j < k) {
22 | if(arr[j] + arr[k] === remainingTarget) {
23 | result.push([ arr[i], arr[j], arr[k] ]);
24 | j++;
25 | k--;
26 | while(j < k && arr[j] === arr[j-1]) {
27 | j++;
28 | }
29 | while(k > j && arr[k] === arr[k+1]) {
30 | k--;
31 | }
32 | } else if(arr[j] + arr[k] > remainingTarget){
33 | k--;
34 | } else {
35 | j++;
36 | }
37 | }
38 | }
39 | return result;
40 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/AverageOfLevels.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val, left, right) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.left = (left===undefined ? null : left)
6 | * this.right = (right===undefined ? null : right)
7 | * }
8 | */
9 | /**
10 | * @param {TreeNode} root
11 | * @return {number[]}
12 | */
13 |
14 | var averageOfLevels = function(root) {
15 | const queue = new Array();
16 | queue.push(root);
17 | const result = [];
18 | while(queue.length) {
19 | let size = queue.length;
20 | let nodesCount = size, sum = 0;
21 | while(--size >= 0) {
22 | const node = queue.shift();
23 | sum += node.val;
24 | if(node.left) {
25 | queue.push(node.left);
26 | }
27 | if(node.right) {
28 | queue.push(node.right);
29 | }
30 | }
31 | result.push(sum / nodesCount);
32 | }
33 | return result;l
34 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/BinaryTree.js:
--------------------------------------------------------------------------------
1 | const Queue = require("../../Queues/Queue");
2 | exports.preorderTraversal = function(root) {
3 | if(root === null) {
4 | return;
5 | }
6 | process.stdout.write(root.val + " ");
7 | this.preorderTraversal(root.left);
8 | this.preorderTraversal(root.right);
9 | }
10 |
11 | exports.inorderTraversal = function(node) {
12 | if(node === null) {
13 | return;
14 | }
15 | this.inorderTraversal(node.left);
16 | process.stdout.write(node.val + " ");
17 | this.inorderTraversal(node.right);
18 | }
19 |
20 | exports.levelOrderTraversal = function(root) {
21 | if(root == null) {
22 | return;
23 | }
24 | const queue = new Queue();
25 | queue.enqueue(root);
26 |
27 | while(!queue.isEmpty()) {
28 | let size = queue.length();
29 | while(--size >= 0) {
30 | const temp = queue.dequeue();
31 | if(temp.left) {
32 | queue.enqueue(temp.left);
33 | }
34 | if(temp.right) {
35 | queue.enqueue(temp.right);
36 | }
37 | process.stdout.write(temp.val + " ");
38 | }
39 | console.log();
40 | }
41 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/ConstructTreeFromPreAndInorder.js:
--------------------------------------------------------------------------------
1 | const Node = require("./Node");
2 |
3 | function constructTree(preorder, inorder) {
4 | const inorderMap = {};
5 | for(let index in inorder) {
6 | inorderMap[inorder[index]] = index;
7 | }
8 | return constructTreeUtil(preorder, inorderMap, 0, preorder.length-1);
9 | }
10 | let preIndex = 0;
11 | function constructTreeUtil(preorder, inorderMap, start, end) {
12 | if(start > end) {
13 | return null;
14 | }
15 | const node = new Node(preorder[preIndex]);
16 | const inorderIndex = inorderMap[preorder[preIndex]];
17 | node.left = constructTreeUtil(preorder, inorderMap, start, index-1);
18 | node.right = constructTreeUtil(preorder, inorderMap, index+1, end);
19 |
20 | return node;
21 | }
22 |
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/DistanceOfNodeFromRoot.js:
--------------------------------------------------------------------------------
1 | function distance(root, node) {
2 | if(root === null) {
3 | return 0;
4 | }
5 | if(root === node) {
6 | return 1;
7 | }
8 | left = distance(root.left, node);
9 | right = distance(root.right, node);
10 |
11 | return left || right ? left + right + 1 : 0;
12 | }
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/FindLeavesGivenPreorderTraversalOfBST.js:
--------------------------------------------------------------------------------
1 | let index = 1;
2 | const leaves = [];
3 | function findLeaves(pre) {
4 | if(pre.length <= 1) {
5 | return pre;
6 | }
7 | return findLeavesUtil(pre, -Infinity, 890, Infinity);
8 | }
9 |
10 | function findLeavesUtil(pre, min, curr, max) {
11 | if(index >= pre.length) {
12 | return;
13 | }
14 | const rootValue = pre[index];
15 | const rootIndex = index;
16 | if(min < rootValue && rootValue < curr) {
17 | index++;
18 | findLeavesUtil(pre, min, rootValue, curr);
19 | }
20 | if(curr < rootValue && rootValue < max) {
21 | index++;
22 | findLeavesUtil(pre, curr, rootValue, max);
23 | }
24 | if(rootIndex === index - 1) {
25 | leaves.push(rootValue);
26 | }
27 | }
28 | findLeaves([890, 325, 290, 530, 965]);
29 | console.log(leaves);
30 | process.stdout.write(leaves.join(", "));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/FindRootToNodePath.js:
--------------------------------------------------------------------------------
1 | const Node = require("./Node");
2 |
3 | function rootToNodePath(root, x) {
4 | const stack = [];
5 | rootToNodePathUtil(root, x, stack);
6 | let length = stack.length;
7 | const result = []
8 | while(stack.length) {
9 | result.push(stack.pop());
10 | }
11 | return result;
12 | }
13 |
14 | function rootToNodePathUtil(root, x, stack) {
15 | if(root === null) {
16 | return false;
17 | }
18 | if(root.val === x) {
19 | stack.push(root.val);
20 | return true;
21 | }
22 | const left = rootToNodePathUtil(root.left, x, stack);
23 | if(left) {
24 | stack.push(root.val);
25 | return left;
26 | }
27 | const right = rootToNodePathUtil(root.right, x, stack);
28 | if(right) {
29 | stack.push(root.val);
30 | return right;
31 | }
32 | return false;
33 | }
34 |
35 | const node = new Node(1);
36 | node.left = new Node(2);
37 | node.right = new Node(3);
38 | node.left.left = new Node(4);
39 | node.left.right = new Node(5);
40 | node.right.left = new Node(6);
41 | node.right.right = new Node(7);
42 |
43 | console.log(rootToNodePath(node, 5));
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/LevelOrderTraversal.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Nayanava/relevel-backend-development/84b179366fe7bc20a40dda69804c1d741c8e8482/Module - 3/AdvancedPS/Trees/Binary/LevelOrderTraversal.js
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/LowestCommonAncestor.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val) {
4 | * this.val = val;
5 | * this.left = this.right = null;
6 | * }
7 | */
8 |
9 | const Node = require("./Node");
10 |
11 | /**
12 | * @param {TreeNode} root
13 | * @param {TreeNode} p
14 | * @param {TreeNode} q
15 | * @return {TreeNode}
16 | */
17 | var lowestCommonAncestor = function(root, p, q) {
18 | const map = {};
19 | lca(root, p, q, [], map);
20 | while(map[p.val].length > map[q.val].length) {
21 | map[p.val].pop();
22 | }
23 | while(map[q.val].length > map[p.val].length) {
24 | map[q.val].pop();
25 | }
26 | while(map[p.val].length) {
27 | const pNode = map[p.val].pop();
28 | const qNode = map[q.val].pop();
29 | if(pNode === qNode) {
30 | return pNode;
31 | }
32 | }
33 | return null;
34 | };
35 |
36 | const lca = function(root, p, q, ancestors, map) {
37 | if(root === null) {
38 | return;
39 | }
40 | ancestors.push(root);
41 | if(root === p || root === q) {
42 | map[root.val] = [...ancestors];
43 | }
44 | if(map[p.val] && map[q.val]) {
45 | return;
46 | }
47 | lca(root.left, p, q, ancestors, map);
48 | lca(root.right, p, q, ancestors, map);
49 | ancestors.pop();
50 | }
51 | //[3,5,1,6,2,0,8,null,null,7,4]
52 | const node = new Node(3);
53 | node.left = new Node(5);
54 | node.right = new Node(1);
55 | node.left.left = new Node(6);
56 | node.left.right = new Node(2);
57 | node.left.right.left = new Node(7);
58 | node.left.right.right = new Node(4);
59 | node.right.left = new Node(0);
60 | node.right.right = new Node(8);
61 | const p = node.left;
62 | const q = node.left.right.left;
63 |
64 | console.log(lowestCommonAncestor(node, p, q).val)
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/Node.js:
--------------------------------------------------------------------------------
1 | class Node {
2 | constructor(val) {
3 | this.val = val;
4 | this.left = null;
5 | this.right = null;
6 | }
7 | }
8 |
9 | module.exports = Node;
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/NodesAtKDistance.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val) {
4 | * this.val = val;
5 | * this.left = this.right = null;
6 | * }
7 | */
8 |
9 | const Node = require("./Node");
10 |
11 | /**
12 | * @param {TreeNode} root
13 | * @param {TreeNode} target
14 | * @param {number} k
15 | * @return {number[]}
16 | */
17 | var distanceK = function(root, target, k) {
18 | //1. let us find the targetNode, to store the list of ancestors.
19 | const ancestors = [];
20 | const result = [];
21 | findAncestors(root, target, ancestors);
22 | console.log(ancestors);
23 | //2. given a starting node, and distance k, find the other nodes.
24 | for(const node of ancestors) {
25 | findNodes(node, k, result);
26 | k -= 1;
27 | }
28 | return result;
29 | };
30 |
31 | const findAncestors = function(root, target, ancestors) {
32 | if(root == null) {
33 | return false;
34 | }
35 | if(root === target) {
36 | ancestors.push(root);
37 | return true;
38 | }
39 | if(findAncestors(root.left, target, ancestors)) {
40 | ancestors.push(root);
41 | return true;
42 | }
43 | if(findAncestors(root.right, target, ancestors)) {
44 | ancestors.push(root);
45 | return true;
46 | }
47 | return false;
48 | }
49 |
50 | const findNodes = function(root, k, result) {
51 | if(root === null || k < 0) {
52 | return;
53 | }
54 | if(k === 0) {
55 | result.push(root.val);
56 | return;
57 | }
58 | findNodes(root.left, k-1, result);
59 | findNodes(root.right, k-1, result);
60 | }
61 |
62 | const root = new Node(3);
63 | root.left = new Node(5);
64 | root.right = new Node(1);
65 | root.left.left = new Node(6);
66 | root.left.right = new Node(2);
67 | root.left.right.left = new Node(7);
68 | root.left.right.right = new Node(4);
69 | root.right.left = new Node(0);
70 | root.right.right = new Node(8);
71 |
72 |
73 | /*
74 |
75 | class Employee {
76 | constructor(name, address, salary, designation, dateOfJoining, dateOfBirth) {
77 | this.name = name;
78 | this.address = address;
79 | this.salary = salary;
80 | this.designation = designation;
81 | this.dateOfJoining = dateOfJoining;
82 | this.dateOfBirth = dateOfBirth;
83 | }
84 |
85 | //1. uniquely identifiable
86 | //2. same hash generated for same key.
87 | _hash()
88 | }
89 | */
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/RightViewOfABinaryTree.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val, left, right) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.left = (left===undefined ? null : left)
6 | * this.right = (right===undefined ? null : right)
7 | * }
8 | */
9 | /**
10 | * @param {TreeNode} root
11 | * @return {number[]}
12 | */
13 | var rightSideView = function(root) {
14 | if(!root) {
15 | return [];
16 | }
17 | const map = {};
18 | const queue = new Array();
19 | queue.push(root);
20 | let level = 0;
21 | while(queue && queue.length) {
22 | let size = queue.length;
23 | while(--size >= 0) {
24 | const temp = queue.shift();
25 | map[level] = temp.val;
26 | if(temp.left) {
27 | queue.push(temp.left);
28 | }
29 | if(temp.right) {
30 | queue.push(temp.right);
31 | }
32 | }
33 | level += 1;
34 | }
35 | const result = new Array(level);
36 | for(let i = 0; i < level; i++) {
37 | result[i] = map[i];
38 | }
39 | return result;
40 | };
--------------------------------------------------------------------------------
/Module - 3/AdvancedPS/Trees/Binary/TreeTraversals.js:
--------------------------------------------------------------------------------
1 | const Node = require("./Node");
2 | const BinaryTree = require("./BinaryTree");
3 |
4 | const node = new Node(1);
5 | node.left = new Node(2);
6 | node.right = new Node(4);
7 |
8 | node.left.right = new Node(5);
9 | node.left.right.right = new Node(7);
10 | node.left.right.right.left = new Node(6);
11 |
12 | node.right.left = new Node (12);
13 | node.right.right = new Node(8);
14 | node.right.left.right = new Node(13);
15 |
16 |
17 | BinaryTree.preorderTraversal(node);
18 | console.log();
19 | BinaryTree.inorderTraversal(node);
20 | console.log();
21 | BinaryTree.levelOrderTraversal(node);
22 | //Homework - implementing postorder and level order traversal.
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Heap/KthSmallestElement.js:
--------------------------------------------------------------------------------
1 | /*
2 | Find the kth smallest element in an array of n elements without actually sorting an array. Expected time complexity: O(nlogk) Expected Space Complexity: O(k)
3 | Example: Input [2,3,45,6,79,1,15], k = 2
4 | Output 2
5 |
6 | kth smallest - kth value 3
7 | */
8 |
9 | const PriorityQueue = require("./PriorityQueue")
10 |
11 | kthSmallestElement = function(arr, k) {
12 | const pq = new PriorityQueue(k);
13 | for(let i = 0; i < k; i++) {
14 | pq.enqueue(arr[i]);
15 | }
16 | for(let i = k; i < arr.length; i++) {
17 | if(arr[i] < pq.peek()) {
18 | pq.dequeue();
19 | pq.enqueue(arr[i]);
20 | }
21 | }
22 |
23 | return pq.peek();
24 | }
25 | console.log(kthSmallestElement([2,3,45,6,79,1,15], 5));
26 |
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Heap/MaxHeap.js:
--------------------------------------------------------------------------------
1 | /*
2 | Max Heap -> a binary tree data structure(represented in the form of an array)
3 | where every parent node(non-leaf node || internal node) is greater than both its children
4 | */
5 |
6 | class MaxHeap {
7 | constructor(maxCapacity) {
8 | this.heap = new Array();
9 | this.maxCapacity = maxCapacity;
10 | }
11 |
12 | isFull = function() {
13 | return this.heap.length === this.maxCapacity;
14 | }
15 |
16 | insert = function(data) {
17 | if(this.isFull()) {
18 | throw new Error('already reached maximum limit');
19 | }
20 | this.heap.push(data);
21 | let child = this.heap.length-1;
22 | while(child > 0) {
23 | const parent = parseInt((child-1)/2);
24 | if(this.heap[parent] > this.heap[child]) {
25 | return;
26 | }
27 | this._swap(child, parent);
28 | child = parent;
29 | }
30 | }
31 | _swap(index1, index2) {
32 | const temp = this.heap[index1];
33 | this.heap[index1] = this.heap[index2];
34 | this.heap[index2] = temp;
35 | }
36 |
37 | extractMax = function() {
38 | if(this.isEmpty()) {
39 | throw new Error('Heap is already empty');
40 | }
41 | const max = this.heap[0];
42 | this._swap(0, this.heap.length-1);
43 | this.heap.pop();
44 | this.heapify(0);
45 | return max;
46 | }
47 |
48 | isEmpty = function() {
49 | return this.heap.length === 0;
50 | }
51 | heapify = function(index) {
52 | let targetIndex = index;
53 | const leftIndex = 2*index + 1;
54 | if(leftIndex < this.heap.length && this.heap[leftIndex] > this.heap[index]) {
55 | targetIndex = leftIndex;
56 | }
57 | const rightIndex = 2 * index+2;
58 | if(rightIndex < this.heap.length && this.heap[rightIndex] > this.heap[targetIndex]) {
59 | targetIndex = rightIndex;
60 | }
61 |
62 | if(targetIndex !== index) {
63 | this._swap(targetIndex, index);
64 | this.heapify(targetIndex);
65 | }
66 | }
67 |
68 | printHeap = function() {
69 | for(let i = 0; i < this.heap.length; i++) {
70 | process.stdout.write(this.heap[i] + " ");
71 | }
72 | }
73 | }
74 |
75 | module.exports = MaxHeap;
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Heap/MergeKSortedArrays.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given a 2 D array consists of sorted rows. You have to combine all the arrays in 1 sorted array.
3 | Input:
4 | arr[][] = { {1, 3, 5, 7},
5 | {2, 4, 6, 8},
6 | {0, 9, 10, 11}} ;
7 | Output: 0 1 2 3 4 5 6 7 8 9 10 11
8 | add all elements to heap - m*n * log(m*n)
9 | Heap - the first element that should be returned is the minimum - MinHeap
10 | */
11 |
12 | const PriorityQueue = require("./PriorityQueue");
13 |
14 |
15 | function megeKSortedArrays(mat) {
16 | const pq = new PriorityQueue(Infinity, (a, b) => a[0] < b[0]);
17 | const M = mat.length, N = mat[0].length;
18 |
19 | for(let row = 0; row < M; row++) {
20 | pq.enqueue([mat[row][0], row, 0]);
21 | }
22 |
23 | const ans = [];
24 | while(!pq.isEmpty()) {
25 | const [value, row, col] = pq.dequeue();
26 | ans.push(value);
27 | if(col < N - 1) {
28 | pq.enqueue([mat[row][col+1], row, col+1]);
29 | }
30 | }
31 |
32 | return ans;
33 | }
34 |
35 | console.log(megeKSortedArrays([[1, 3, 5, 7],
36 | [2, 4, 6, 8],
37 | [0, 9, 10, 11]]));
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Heap/SortArrayByFrequency.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
4 |
5 | Return the sorted string. If there are multiple answers, return any of them.
6 |
7 | s consists of uppercase and lowercase English letters and digits.
8 |
9 | Example 1:
10 |
11 | Input: s = "tree"
12 | Output: "eert"
13 | Explanation: 'e' appears twice while 'r' and 't' both appear once.
14 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
15 | Example 2:
16 |
17 | Input: s = "cccaaa"
18 | Output: "aaaccc"
19 | Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
20 | Note that "cacaca" is incorrect, as the same characters must be together.
21 | Example 3:
22 |
23 | Input: s = "Aabb"
24 | Output: "bbAa"
25 | Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
26 | Note that 'A' and 'a' are treated as two different characters.
27 |
28 | */
29 |
30 | const PriorityQueue = require("./PriorityQueue");
31 |
32 | /*
33 | character - 1 byte
34 | - 8 Bits
35 | -128 0 127 - ASCII
36 | */
37 | /*
38 | tree
39 | e - 101
40 | r - 112
41 | t - 113
42 | */
43 | function frequencyBasedSort(s) {
44 | const freqArr = new Array(128).fill(0);
45 | for(const character of s) {
46 | freqArr[character.charCodeAt()]++;
47 | }
48 | //arr - [char, freq]
49 | const pq = new PriorityQueue((a, b) => a[1] > b[1]);
50 | for(let i = 0; i < 128; i++) {
51 | if(freqArr[i]) {
52 | pq.enqueue([String.fromCharCode(i), freqArr[i]]);
53 | }
54 | }
55 | let res = "";
56 | while(!pq.isEmpty()) {
57 | let [char, freq] = pq.dequeue();
58 | while(--freq >= 0) {
59 | res = res.concat(char);
60 | }
61 | }
62 | return res;
63 | }
64 |
65 | console.log(frequencyBasedSort("tree"));
66 |
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Heap/TaskScheduler.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
3 |
4 | However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
5 |
6 | Return the least number of units of times that the CPU will take to finish all the given tasks.
7 |
8 |
9 |
10 | Example 1:
11 |
12 | Input: tasks = ["A","A","A","B","B","B"], n = 2
13 | Output: 8
14 | Explanation:
15 | A -> B -> idle -> A -> B -> idle -> A -> B
16 | 1 -> 2 -> idle -> A
17 | There is at least 2 units of time between any two same tasks.
18 | Example 2:
19 |
20 | Input: tasks = ["A","A","A","B","B","B"], n = 0
21 | Output: 6
22 | */
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Heap/TestMaxHeap.js:
--------------------------------------------------------------------------------
1 | /*
2 | 1. we try to extract value from empty heap - throw error
3 | 2. we try to insert into full heap - throw error
4 | 3. insert into heap and print heap - the heap should satisfy MaxHeap property
5 | 4. extractMax - print the maxValue and then print the heap, this should also be in MaxHeap format.
6 | 5. again insert a new value - MaxHeap property should be satisfied
7 | 6. If we call extractMax till the heap becomes empty - we should see the result in descending order.
8 | */
9 |
10 | const PriorityQueue = require("./PriorityQueue");
11 | const MaxHeap = require("./MaxHeap");
12 |
13 | function testHeap() {
14 | const heap = new MaxHeap(3);
15 | try {
16 | heap.extractMax();
17 | } catch(e) {
18 | console.log(e.message);
19 | }
20 | try {
21 | for(let i = 1; i <= 5; i++) {
22 | let value = parseInt(Math.random() * 500) + 1;
23 | heap.insert(value);
24 | heap.printHeap();
25 | console.log();
26 | }
27 | }catch(e) {
28 | console.log(e.message);
29 | }
30 | while(!heap.isEmpty()) {
31 | console.log(`extracted max value = ${heap.extractMax()}`);
32 | heap.printHeap();
33 | console.log();
34 | }
35 | }
36 |
37 | function sortNumbers() {
38 | const arr = [1, 2, 3, 11, 12];
39 | arr.sort((a, b) => a - b);
40 | console.log(arr);
41 | }
42 |
43 | function TestPriorityQueue() {
44 | const minHeapPQ = new PriorityQueue(5, (a, b) => a < b);
45 | }
46 | //testHeap();
47 | sortNumbers();
48 |
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Queue/FirstNegativeInWindow.js:
--------------------------------------------------------------------------------
1 | const Queue = require("../../AdvancedPS/Queues/Queue");
2 |
3 | function findFirstNegativesInWindow(arr, k) {
4 | const queue = new Queue();
5 | const res = new Array(arr.length - k + 1);
6 | for(let i = 0; i < k; i++) {
7 | if(arr[i] < 0) {
8 | queue.enqueue(i);
9 | }
10 | }
11 | let resIndex = 0;
12 | res[resIndex++] = queue.isEmpty() ? NaN : arr[queue.getFront()];
13 | for(let i = k; i < arr.length; i++) {
14 | while(!queue.isEmpty() && queue.getFront() <= i - k) {
15 | queue.dequeue();
16 | }
17 | if(arr[i] < 0) {
18 | queue.enqueue(i);
19 | }
20 | res[resIndex++] = queue.isEmpty() ? NaN : arr[queue.getFront()];
21 | }
22 | return res;
23 | }
24 |
25 | console.log(findFirstNegativesInWindow([-2, 0, -3, 4], 2));
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Queue/GasStation.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} gas
3 | * @param {number[]} cost
4 | * @return {number}
5 | */
6 | var canCompleteCircuit = function(petrol, distance) {
7 | let totalAvailablePetrol = 0, totalRequiredPetrol = 0;
8 | for(let i = 0; i < petrol.length; i++) {
9 | totalAvailablePetrol += petrol[i];
10 | totalRequiredPetrol += distance[i];
11 | }
12 | if(totalAvailablePetrol < totalRequiredPetrol) {
13 | return -1;
14 | }
15 |
16 | let totalAvailableGas = 0, startingPoint = 0;
17 | for(let i = 0; i < petrol.length; i++) {
18 | totalAvailableGas += petrol[i] - distance[i];
19 | if(totalAvailableGas < 0) {
20 | totalAvailableGas = 0;
21 | startingPoint = i+1;
22 | }
23 | }
24 | return startingPoint;
25 | };
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Queue/LemonadeChange.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} bills
3 | * @return {boolean}
4 | */
5 | var lemonadeChange = function(bills) {
6 | let fiveDollarNotes = 0, tenDollarNotes = 0;
7 | for(const bill of bills) {
8 | if(bill === 5) {
9 | fiveDollarNotes++;
10 | } else if (bill === 10) {
11 | if(fiveDollarNotes === 0) {
12 | return false;
13 | }
14 | fiveDollarNotes--;
15 | tenDollarNotes++;
16 | } else {
17 | if(tenDollarNotes && fiveDollarNotes) {
18 | tenDollarNotes--;
19 | fiveDollarNotes--;
20 | } else if(tenDollarNotes === 0) {
21 | if(fiveDollarNotes < 3) {
22 | return false;
23 | }
24 | fiveDollarNotes -= 3;
25 | } else {
26 | return false;
27 | }
28 | }
29 | }
30 | return true;
31 | };
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Queue/Queue.js:
--------------------------------------------------------------------------------
1 | const Node = require("./Node");
2 |
3 | class Queue {
4 | constructor(maxCapacity = -1) {
5 | if(maxCapacity !== -1 && maxCapacity <= 0) {
6 | throw new Error("Invalid queue capacity. ")
7 | }
8 | this.maxCapacity = maxCapacity;
9 | this.front = null;
10 | this.rear = null;
11 | this.size = 0;
12 | }
13 |
14 | isEmpty = function() {
15 | return this.size === 0;
16 | }
17 |
18 | isFull = function () {
19 | return this.size === this.maxCapacity;
20 | }
21 |
22 | length = function () {
23 | return this.size;
24 | }
25 | // same as insertAtEnd of linkedList.
26 | enqueue = function (val) {
27 | if(this.isFull()) {
28 | throw new Error("The Queue has reached its maximum capacity!");
29 | }
30 | const newNode = new Node(val);
31 | if(this.front === null) {
32 | this.front = this.rear = newNode;
33 | } else {
34 | this.rear.next = newNode;
35 | newNode.prev = this.rear;
36 | this.rear = newNode;
37 | //or
38 | //this.rear.next = this.rear
39 | }
40 | this.size++;
41 | return newNode;
42 | }
43 |
44 | dequeue = function() {
45 | if(this.isEmpty()) {
46 | throw new Error("The Queue is already empty!");
47 | }
48 | let deletedNode;
49 | deletedNode = this.front;
50 | if(this.size === 1) {
51 | this.front = this.rear = null;
52 | } else {
53 | this.front = this.front.next;
54 | this.front.prev = null;
55 | deletedNode.next = deletedNode.prev = null;
56 | }
57 | this.size--;
58 | return deletedNode.val;
59 | }
60 |
61 | getFront = function() {
62 | return this.isEmpty() ? null : this.front.val;
63 | }
64 |
65 | traverse() {
66 | let temp = this.front;
67 | while(temp != null) {
68 | process.stdout.write(temp.val + " ");
69 | temp = temp.next;
70 | }
71 | console.log();
72 | }
73 | }
74 |
75 | module.exports = Queue;
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Queue/ValidateStackSequence.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} pushed
3 | * @param {number[]} popped
4 | * @return {boolean}
5 | */
6 | Array.prototype.isEmpty = function() {
7 | return !this || !this.length;
8 | }
9 | Array.prototype.peek = function() {
10 | return this[this.length-1];
11 | }
12 | var validateStackSequences = function(pushed, popped) {
13 | const stack = new Array();
14 | let index = 0;
15 | for(const number of pushed) {
16 | stack.push(number);
17 | while(!stack.isEmpty()) {
18 | if(stack.peek() === popped[index]) {
19 | stack.pop();
20 | index++;
21 | } else {
22 | break;
23 | }
24 | }
25 | }
26 | return stack.isEmpty();
27 | };
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Stack/LargestRectangleHistogram.js:
--------------------------------------------------------------------------------
1 | Array.prototype.isEmpty = function() {
2 | return this.length === 0;
3 | }
4 | Array.prototype.peek = function() {
5 | return this[this.length-1];
6 | }
7 |
8 | function largestRectangleHistogram(heights) {
9 | const stack = new Array();
10 | stack.push(-1);
11 | let index;
12 | let maxArea = 0;
13 | for(index = 0; index < heights.length; index++) {
14 | let minHt = Number.MAX_VALUE;
15 | while(stack.peek() !== -1 && heights[stack.peek()] >= heights[index]) {
16 | const curr = stack.pop();
17 | minHt = Math.min(minHt, heights[curr]);
18 | const area = minHt * (index - stack.peek() - 1);
19 | maxArea = Math.max(maxArea, area);
20 | }
21 | stack.push(index);
22 | }
23 | let minHt = Number.MAX_VALUE;
24 | while(stack.peek() !== -1) {
25 | const curr = stack.pop();
26 | minHt = Math.min(minHt, heights[curr]);
27 | const area = minHt * (index - stack.peek() - 1);
28 | maxArea = Math.max(maxArea, area);
29 | }
30 | return maxArea;
31 | }
32 |
33 | console.log(largestRectangleHistogram([2,1,5,6,2,3]));
34 | console.log(largestRectangleHistogram([2,4]));
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Stack/MinimumDeletions.js:
--------------------------------------------------------------------------------
1 | Array.prototype.isEmpty = function() {
2 | return this.length === 0;
3 | }
4 | Array.prototype.peek = function() {
5 | return this[this.length-1];
6 | }
7 |
8 | var minimumDeletions = function(s) {
9 | const stack = new Array();
10 | let count = 0;
11 | for(const char of s) {
12 | if(char === 'a') {
13 | if(!stack.isEmpty() && stack.peek() === 'b') {
14 | count++;
15 | stack.pop();
16 | } else {
17 | stack.push(char);
18 | }
19 | } else {
20 | stack.push(char);
21 | }
22 | }
23 | return count;
24 | }
25 |
26 | console.log(minimumDeletions("aababbab"));
27 | console.log(minimumDeletions("bbaaaaabb"));
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Stack/RemoveKdigits.js:
--------------------------------------------------------------------------------
1 | Array.prototype.top = function() {
2 | return this[this.length-1];
3 | }
4 |
5 | Array.prototype.isEmpty = function() {
6 | return !this || !this.length
7 | }
8 |
9 | function removeKDigits(number, k) {
10 | const stack = new Array();
11 | if(k > number.length) {
12 | return -1;
13 | }
14 | let index;
15 | for(index = 0; index < number.length; index++) {
16 | const char = number[index];
17 | while(!stack.isEmpty() && stack.top().charCodeAt() > char.charCodeAt() && --k >= 0) {
18 | stack.pop();
19 | }
20 | stack.push(char);
21 | }
22 | return stack.join("");
23 | }
24 |
25 | console.log(removeKDigits("123421", 3));
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/Stack/TrappingRainWater.js:
--------------------------------------------------------------------------------
1 | Array.prototype.isEmpty = function() {
2 | return this.length === 0;
3 | }
4 | Array.prototype.peek = function() {
5 | return this[this.length-1];
6 | }
7 |
8 | function trappingRainWater(heights) {
9 | const stack = new Array();
10 | let result = 0;
11 | for(let index = 0; index < heights.length; index++) {
12 | while(!stack.isEmpty() && heights[stack.peek()] < heights[index]) {
13 | const lastIndex = stack.pop();
14 | if(stack.isEmpty()) {
15 | break;
16 | }
17 | result += (Math.min(heights[index], heights[stack.peek()]) - heights[lastIndex]) * (index - stack.peek() - 1);
18 | }
19 | stack.push(index);
20 | }
21 | return result;
22 | }
23 |
24 | console.log(trappingRainWater([0,1,0,2,1,0,1,3,2,1,2,1]));
25 | console.log(trappingRainWater([4,2,0,3,2,5]));
--------------------------------------------------------------------------------
/Module - 3/FE-7-AdvancedPS/TryCatch/Exception.js:
--------------------------------------------------------------------------------
1 | function tryFetchingData(allIssWell) {
2 | if(allIssWell) {
3 | return "things are fine"
4 | }
5 | throw new Error("Something went wrong");
6 | }
7 |
8 | function functionB() {
9 | try {
10 | tryFetchingData(false);
11 | } catch (err) {
12 | // throw new Error(`tryFetchingData threw -> ${err.message}`);
13 | console.log("tryFetchingData threw error");
14 | } finally {
15 | console.log("this will be executed no matter what!");
16 | }
17 |
18 | }
19 |
20 | function functionA() {
21 | try {
22 | functionB();
23 | } catch(err) {
24 | console.log("functionB threw ", err.message);
25 | } finally {
26 | console.log("finally is working inside functionA also");
27 | }
28 | }
29 |
30 | functionA();
--------------------------------------------------------------------------------
/PasswordHashing/hash-password.js:
--------------------------------------------------------------------------------
1 | const bcrypt = require('bcrypt');
2 | const encryptPassword = async (password) => {
3 | //const password = req.body.password;
4 | const salt = await bcrypt.genSalt();
5 | const hashedPassword = await bcrypt.hash(password, salt);
6 | console.log(salt);
7 | console.log(hashedPassword);
8 |
9 | return hashedPassword;
10 | }
11 |
12 | const authenticate = async(password, hashedPassword) => {
13 | return await bcrypt.compare(password, hashedPassword);
14 | }
15 |
16 | const password = 'pasword_123'
17 | encryptPassword(password)
18 | .then(hashedPassword => {
19 | return authenticate(password, hashedPassword);
20 | }).then(result => console.log(result))
21 | .catch(err => console.log(err));
--------------------------------------------------------------------------------
/PasswordHashing/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "passwordhashing",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "hash-password.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bcrypt": "^5.0.1"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
11 | Randomised Quicksort and Problem Solving on Sorting!
12 |
13 |
--------------------------------------------------------------------------------
/jwt-demo/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jwt-demo",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "dotenv": "^16.0.1",
14 | "express": "^4.18.1",
15 | "jsonwebtoken": "^8.5.1"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/jwt-demo/server.js:
--------------------------------------------------------------------------------
1 | //require('crypto').randomBytes(64).toString('hex'); - to create secret
2 | const express = require('express');
3 | const jwt = require('jsonwebtoken');
4 | require('dotenv').config();
5 | const app = express();
6 | app.use(express.json());
7 | const posts = [
8 | {
9 | 'username': 'Samik',
10 | 'post': 'Post1'
11 | },
12 | {
13 | 'username': 'Rehan',
14 | 'post': 'Are we job ready!!!'
15 | }
16 | ]
17 |
18 | app.get('/posts', validateToken, (req, res) => {
19 | res.status(200).send(posts.filter(post => post.username === req.user.name));
20 | });
21 |
22 | app.post('/login', (req, res) => {
23 | // the user is valid - did password authentication
24 | const username = req.body.username;
25 | console.log(username);
26 | const user = {
27 | name: username
28 | }
29 | const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET);
30 | res.status(200).send({accessToken: accessToken});
31 | });
32 |
33 | function validateToken(req, res, next) {
34 | const authHeader = req.headers['authorization'];
35 | const accessToken = authHeader.split(' ')[1];
36 | if(!accessToken) {
37 | res.send(401);
38 | return;
39 | }
40 | jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET, (err, payload) => {
41 | if(err) {
42 | res.sendStatus(403);
43 | return;
44 | }
45 | req.user = payload;
46 | next();
47 | });
48 | }
49 | app.listen(3000, (err) => {
50 | if(err) {
51 | console.log('Error in starting server!', err);
52 | }
53 | });
--------------------------------------------------------------------------------