├── AlgoMarathon
├── Trie
│ ├── README.md
│ └── PairLearning
│ │ └── TriewShauray.py
├── Arrays
│ ├── SpeedDrill
│ │ ├── flipAnArray.js
│ │ ├── minimumVal.js
│ │ ├── TwoMaxElems.js
│ │ ├── path.js
│ │ ├── indicesAndValues.js
│ │ └── InsertTargetElem.js
│ ├── ArithmeticSlices.js
│ ├── PairLearning
│ │ ├── pairSkillsLevelwRichard.js
│ │ ├── repeatedXElemswStoney.js
│ │ ├── KandaneAlgowKengYu_07-15-22.js
│ │ ├── KadaneAlgowMaggie.js
│ │ ├── cellTowerswBrian.js
│ │ └── dogsAndHatswNancy.js
│ ├── smallestDifference.js
│ ├── verticalZigzag2DMatrix.js
│ ├── ConvertArrToZigzag.js
│ ├── TwoNumSum.js
│ ├── repeatedXtimes.js
│ ├── mergeThreeLists.js
│ ├── Searching
│ │ └── ShiftedBinarySearch.js
│ ├── isMonotonicArray.js
│ └── LongestPalidromicSubstring.js
├── LinkedList
│ ├── PairLearning
│ │ ├── DeleteKNodesAfterMiddle_understandCodes(2)_07-23-22.js
│ │ └── DeleteKNodesAfterMiddle_wGigi_07-23-22.js
│ └── frequency.js
├── Strings
│ ├── isAnagram.js
│ ├── GroupAnagrams.js
│ ├── Pair Learning
│ │ ├── GroupAnagramswArthurDamm.js
│ │ └── implementStrstrwCarlos.js
│ └── BackSpaceStringCompare.js
├── BinaryTree
│ ├── findTargetInBinaryTree_Template.js
│ ├── DiameterBinaryTree.js
│ ├── balancedBinaryTree.js
│ ├── PathSumTree_07-27-22.js
│ ├── binaryTreePath.js
│ ├── findMaxBinaryTree_3Ways.js
│ ├── binaryTreeLeftView.js
│ ├── PairLearning
│ │ ├── BSTtoDoublyLLwAngel.js
│ │ └── README.md
│ └── LowestCommonAncestor.js
├── Backtracking
│ ├── uniqueCombo.js
│ └── Permutations_practice.js
└── Dynamic Programming
│ └── WaterArea.js
├── AlgoMockedInterview
├── Basics_Self_Practice
│ ├── Array
│ │ ├── ValidAnagrams.js
│ │ └── containsDuplicates.js
│ └── Recursion
│ │ ├── fib.js
│ │ ├── combo.js
│ │ ├── subsets.js
│ │ └── paranthesis.js
├── 1-on-1-with-Mentor
│ ├── Afeez_08-31-22.js
│ └── Afeez_08-25-22.js
├── AdvancedArray
│ └── numberOfIslands_practice.js
└── DynamicProgramming
│ └── ConceptDrillwSumeet_09-27-22.js
├── CoreAlgos
├── Array
│ ├── Find
│ │ ├── numOfDuplicated.js
│ │ ├── numOfUnique.js
│ │ ├── firstRepeated.js
│ │ └── binarySearch.js
│ └── Sort
│ │ ├── bubble.js
│ │ ├── selection.js
│ │ ├── merge.js
│ │ └── insertion.js
├── BinaryTree
│ ├── height.js
│ ├── BinarySearchTree
│ │ ├── findElem.js
│ │ ├── insertElem.js
│ │ └── validateBST.js
│ ├── max.js
│ ├── count.js
│ ├── bt_BFS.js
│ ├── bt_DFS.js
│ └── sum.js
├── LinkedList
│ ├── 1_Accumulating
│ │ ├── sum.js
│ │ ├── countQ2.js
│ │ └── count.js
│ ├── 4_Adding
│ │ └── appendTarget.js
│ ├── 5_Removing
│ │ ├── removeTarget.js
│ │ └── removeAllTarget.js
│ ├── 3_Finding_TwoPointers
│ │ └── findMiddle.js
│ ├── 2_Finding_NoPointerNeeded
│ │ └── findElem.js
│ ├── 7_Summing_LinkedLists
│ │ └── sumTwoEqualLL.js
│ └── 6_Reversing
│ │ └── reverse.js
├── FibSequence
│ └── fib.js
└── README.md
├── Independent_Frontend_Practice
├── DOMTreeTraversak_self-practice.js
├── README.md
└── sample_react_app_sort-filter-practice.js
├── 1-DailyReflection
└── README.md
├── 1-on-1-w-Mentor-Fellow
├── power-of-two-w-brianzhu.js
├── sortedSquaredwMitch.js
├── TriePerspective_w_Mitch.js
└── authurDamm_DFS_Recursion.js
├── AlgoWorkout
├── Vinit
│ ├── 04-20-22(2).py
│ ├── 04-20-22(1).js
│ ├── 06-29-22.py
│ └── 05-04-22.js
├── Temi
│ ├── 05-18-22.js
│ ├── 05-09-22.js
│ └── 05-10-22.js
├── Arnold
│ └── binaryTreeInStringDepth.js
└── Stanley
│ └── autocomplete.js
├── Weekly Gather Mentor Office Hours
├── backtrackingRecursionwDaniel_06-10-22.js
├── RobotCleanRoomwDanielTomko_06-29-22.js
├── TreetoLL&BacktrackingwDaniel_06-23-22.js
├── AlgoMarathonwDaniel_06-02-22.js
├── BacktrackingwSophie_06-16-22.js
├── SodukuMatrixRotateMatrixwTonyandDaniel_07-21-22.py
└── AddOneRowToATreewDaniel_07-07-22.js
├── README.md
├── SmallGroupPractice
└── README.md
├── SystemDesign
└── README.md
├── AlgoSprint
├── README.md
└── frequencyElem.js
├── LiveCoding
└── LiveCodingwChinedu.js
├── MockedBehavioralPhoneScreen
└── README.md
└── Public-Formation-Events
└── README.md
/AlgoMarathon/Trie/README.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/SpeedDrill/flipAnArray.js:
--------------------------------------------------------------------------------
1 | /*PASSED
2 | Q. Given an array of integers, flip an array.
3 |
4 | Example:
5 | Input: [1, 2, 3, 4, 5, 6]
6 | Output: [6, 5, 4, 3, 2, 1]
7 |
8 | */
9 |
10 | function solution(array) {
11 | let res = [];
12 | for (let i = array.length - 1; i > -1; i--) {
13 | res.push(array[i]);
14 | }
15 | return res;
16 | }
17 |
--------------------------------------------------------------------------------
/AlgoMockedInterview/Basics_Self_Practice/Array/ValidAnagrams.js:
--------------------------------------------------------------------------------
1 | /*
2 | Current Solution:
3 | T: O(N)
4 | S: O(N)
5 |
6 | */
7 | var isAnagram = function(s, t) {
8 | let freqMap = new Map();
9 | for (let char of s) {
10 | let count = freqMap.get(char) || 0;
11 | count++;
12 | freqMap.set(char, count);
13 | }
14 | for (let char of t) {
15 | let count = freqMap.get(char) || 0;
16 | count--;
17 | freqMap.set(char, count);
18 | }
19 | for (let value of freqMap) {
20 | if (value[1] !== 0) {
21 | return false;
22 | }
23 | }
24 | return true;
25 | };
--------------------------------------------------------------------------------
/CoreAlgos/Array/Find/numOfDuplicated.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an unsorted array, return the number of duplicated elements that appear more than once in the array.
3 |
4 | Examples:
5 | • Given an array: [3, 1, 1, 2, 3, 1, 1, 1, 4] // returns 2 (duplicated elements: 3 and 1)
6 | • Given an array: [1] // returns 0
7 | */
8 |
9 | function numDuplicates(array) {
10 |
11 | }
12 |
13 | // Test Cases
14 | console.log(numDuplicates([])) // 0
15 | console.log(numDuplicates([3, 1, 1, 2, 3, 1, 1, 1, 4])) // 2
16 | console.log(numDuplicates([1])) // 0
17 |
18 | //----------------------------------------------------------------------------------
19 |
20 | //Approaches:
21 |
22 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/SpeedDrill/minimumVal.js:
--------------------------------------------------------------------------------
1 | /* PASSED
2 | Q. Given two integer arrays of equal length, merge them into one by taking the minimum value at the each index.
3 |
4 | Example:
5 | Inputs: [1, 2, 3, 4, 5] and [5, 4, 3, 2, 1]
6 | Output:[1, 2, 3, 2, 1] // at the index 0, 1 is smaller than 5. Thus, take 1 as the first element.
7 |
8 | Input:
9 | a1: [1]
10 | a2: [1]
11 | Output:
12 | [1]
13 |
14 | Input:
15 | a1: [1]
16 | a2: [2]
17 | Output:
18 | [1]
19 |
20 | */
21 |
22 |
23 | function solution(a1, a2) {
24 | let res = [];
25 | for (let i = 0; i < a1.length; i++) {
26 | if (a1[i] > a2[i]) res.push(a2[i]);
27 | else res.push(a1[i]);
28 | }
29 | return res;
30 | }
31 |
--------------------------------------------------------------------------------
/AlgoMarathon/LinkedList/PairLearning/DeleteKNodesAfterMiddle_understandCodes(2)_07-23-22.js:
--------------------------------------------------------------------------------
1 |
2 | function findMiddle(head) {
3 | const dummy = new Node("dummy", head);
4 | let middle = dummy;
5 | let curr = head;
6 |
7 | while (curr !== null) {
8 | middle = middle.next;
9 | curr = curr.next;
10 | curr = curr ? curr.next : null;
11 | }
12 |
13 | return middle;
14 | }
15 |
16 | function removeKAfterMiddle(head, k) {
17 | const middle = findMiddle(head);
18 |
19 | let curr = middle;
20 | while (curr && k >= 0) {
21 | curr = curr.next;
22 | k--;
23 | }
24 |
25 | middle.next = curr;
26 | return head;
27 | }
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/SpeedDrill/TwoMaxElems.js:
--------------------------------------------------------------------------------
1 | /* PASSED
2 | Q. Given an unsorted array of unique integers, return the two biggest elements in an array of ascending order. You may assume there are at least two elements.
3 |
4 | [execution time limit] 4 seconds (js)
5 |
6 | [input] array.integer array
7 |
8 | [output] array.integer
9 |
10 | Input:
11 | array: [12, 5, 7, 10, 1, 160]
12 |
13 | Expected Output:
14 | [12, 160]
15 |
16 | Input:
17 | array: [12, 17, 161, 5, 7, 10, 1, 160]
18 |
19 | Output:
20 | [160, 161]
21 |
22 | Input:
23 | array: [1, 3, 7, 6, 2, -1]
24 |
25 | Output:
26 | [6, 7]
27 |
28 | */
29 |
30 | function solution(array) {
31 | let sortedArr = array.sort((a, b) => a - b);
32 | return sortedArr.slice(array.length - 2);
33 | }
34 |
--------------------------------------------------------------------------------
/AlgoMockedInterview/Basics_Self_Practice/Recursion/fib.js:
--------------------------------------------------------------------------------
1 | /*
2 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
3 |
4 | F(0) = 0, F(1) = 1
5 | F(n) = F(n - 1) + F(n - 2), for n > 1.
6 | Given n, calculate F(n).
7 | */
8 |
9 |
10 | /**
11 | * @param {number} n
12 | * @return {number}
13 | */
14 | /*
15 |
16 | 3 conditions:
17 | 1) f(n) = f(n-1) + f(n - 2) only when n >= 2
18 | 2) f(1) === 1
19 | 3) f(0) === 0
20 |
21 | fib(2) = fib(1) + fib(0)
22 | = 1 + 0 = 1
23 |
24 |
25 | */
26 | var fib = function(n) {
27 | if (n === 0) return 0;
28 | if (n >= 2) {
29 | return fib(n - 1) + fib(n - 2);
30 | }
31 | return 1;
32 | };
--------------------------------------------------------------------------------
/Independent_Frontend_Practice/DOMTreeTraversak_self-practice.js:
--------------------------------------------------------------------------------
1 | /*
2 | DOM Traversal
3 |
4 |
5 |
6 |
12 |
16 |
17 |
19 |
20 |
21 | a
22 | b b
23 | c d
24 | g
25 |
26 |
27 |
28 | let root = document.getElementById('root')
29 | deepTraversal(root,nodeList=[])
30 |
31 | Methods:
32 |
33 | isTargetClass => boolean
34 | input - the string - class name
35 |
36 | isValidPath => boolean
37 | input - the string - a class name path ie, "a>b>c" => true "a>b>g" => false
38 | */
39 |
40 |
41 |
--------------------------------------------------------------------------------
/1-DailyReflection/README.md:
--------------------------------------------------------------------------------
1 | # Daily Reflection & Takeaways
2 |
3 | Seeing a less frequent update in this repo (since I have noting down learnings in my personal notebook), I have decided to create this to help me to make a quick note on my daily progress and takeaways I have learned from sessions.
4 |
5 |
15 |
16 | ## 10/04/2022
17 |
18 | **Reflection + Takeaways:**
19 | - Did not have any session today at Formation
20 | - Browsed through Hacktoberfest open source projects to reivew through different issues with the label of Hacktoberfest or good first commits
21 | - Submitted 1st simple PR in the first-contributions repo
22 | - Reflected on my progress and reviewed through this repo
23 | - Planned out my Roadmap
24 | - Took a look at the current market (8)
--------------------------------------------------------------------------------
/AlgoMarathon/Strings/isAnagram.js:
--------------------------------------------------------------------------------
1 | var isAnagram = function(s, t) {
2 | let fMap = new Map();
3 | for (let i = 0; i < s.length; i++) {
4 | let count = fMap.get(s[i]) || 0;
5 | count ++;
6 | fMap.set(s[i], count);
7 | }
8 |
9 | for (let j = 0; j < t.length; j++) {
10 | let count = fMap.get(t[j]) || 0;
11 | if (count > 0) {
12 | count--;
13 | fMap.set(t[j], count);
14 | }else {
15 | if (fMap.has(t[j])) {
16 | fMap.delete(t[j]);
17 | }else {
18 | count++;
19 | fMap.set(t[j], count);
20 | }
21 | }
22 |
23 | }
24 |
25 | for (const char of fMap) {
26 | console.log(char[1]);
27 | if (char[1] > 0) {
28 | return false;
29 | }
30 | }
31 |
32 | return true;
33 | };
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/SpeedDrill/path.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Codewriting
4 |
5 | Q. Given an array of integers which represents a path, determine if you reach to the end of the array after following the path. Start with element 0 and move forward x number of steps, can be negative which means move backward.
6 |
7 | Example:
8 | Input: [1, 2, 0, -1]
9 | Output: false // starting at 0, the first path is 1, so take 1 step forward where you get to 2. Then you take 2 more steps forward to get to -1. Then take a step backward where you land at 0. Since 0 does not do anything, you get stuck at that point. Thus this returns false.
10 | */
11 |
12 | function solution(path) {
13 | if (path.length < 1) return false;
14 | let sum = 0;
15 | for (let i = 0; i < path.length; i++) {
16 | sum += path[i];
17 | }
18 | console.log(sum, path.length - 1);
19 | if (sum >= path.length - 1) return true;
20 | return false;
21 | }
22 |
--------------------------------------------------------------------------------
/AlgoMarathon/Strings/GroupAnagrams.js:
--------------------------------------------------------------------------------
1 | /*
2 | Group Anagram (Array of Strings)
3 | */
4 |
5 |
6 | //ATTEMPT #1 (FAILED)
7 |
8 | var groupAnagrams = function(strs) {
9 | let result = [];
10 | for (let i = 0; i < strs.length; i++) {
11 | //not entirely how to work on this problem
12 | // console.log(strs[i].split('').sort());
13 | // let sortedStr = strs[i].split('').sort().join('');
14 | // console.log(sortedStr);
15 | // let group = [];
16 | // if (!group.includes(sortedStr)) group.push(strs[i]);
17 | }
18 | console.log(result);
19 | };
20 |
21 | /*
22 | Progress notes:
23 |
24 | 20m - Trying to go through the problem
25 |
26 | 15m - Reviewed through the solutions in Leetcode and generally understand the two ways to solve the problem
27 |
28 | Future Attempts:
29 | - Work on the same problem on AlgoExpert.io
30 | - Try out the two approaches to solve this problem
31 |
32 | */
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/findTargetInBinaryTree_Template.js:
--------------------------------------------------------------------------------
1 | class Tree {
2 | constructor(val, left=null, right=null) {
3 | this.value = val;
4 | this.left = left;
5 | this.right = right;
6 | }
7 | }
8 |
9 | function dfs(root, target) {
10 | if (!root) return null;
11 | console.log(root);
12 | if (root.value === target) {
13 | return root; //determine what to return
14 | }
15 |
16 | const left = dfs(root.left, target);
17 | const right = dfs(root.right, target);
18 |
19 | // console.log("left", left);
20 | // console.log("right", right);
21 |
22 | return left ? left : right; //once the node is found in the tree either on the left or right, it will be return here.
23 | //if left exist, return left, else return right, if both do not exist, then return null
24 | }
25 |
26 | const tree = new Tree(1, new Tree(2, new Tree(4), new Tree(6)), new Tree(3))
27 | console.log(dfs(tree, 4))
--------------------------------------------------------------------------------
/AlgoMarathon/Backtracking/uniqueCombo.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an array of unique numbers (nums), find all possible unique combinations of those numbers.
3 |
4 | Input: [1, 2, 3]
5 | Output: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
6 |
7 | Be aware of the sort order of the output.
8 |
9 | Backtracking
10 | */
11 |
12 | function uniqueCombo(nums) {
13 | let res = [];
14 | function backtracking(arr, i_posn, curr_res){
15 |
16 | //base case
17 | if (i_posn >= arr.length) {
18 | res.push([...curr_res]);
19 | return;
20 | }
21 |
22 | //recursive case - pick
23 | curr_res.push(arr[i_posn]);
24 | backtracking(arr, i_posn + 1, curr_res);
25 |
26 | //recusive case - not pick
27 | curr_res.pop();
28 | backtracking(arr, i_posn + 1, curr_res);
29 | }
30 |
31 | backtracking(nums, 0, []);
32 | return res.sort();
33 | }
34 |
35 | console.log(uniqueCombo([1, 2, 3]));
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/DiameterBinaryTree.js:
--------------------------------------------------------------------------------
1 | /*
2 | Self-practice Attempt #3
3 |
4 | Given the root of a binary tree, return the length of the diameter of the tree.
5 |
6 | The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
7 |
8 | The length of a path between two nodes is represented by the number of edges between them.
9 |
10 |
11 | */
12 |
13 | var diameterOfBinaryTree = function(root) {
14 | let diameter = 0;
15 |
16 | function dfs(root) {
17 | if (!root) return 0;
18 |
19 | const left = dfs(root.left);
20 | const right = dfs(root.right);
21 | console.log(left, right)
22 |
23 | diameter = Math.max(diameter, left + right);
24 | console.log(diameter);
25 |
26 | return 1 + Math.max(left, right); //<-- making mistake at here!!
27 | }
28 | dfs(root);
29 | return diameter;
30 | }
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/balancedBinaryTree.js:
--------------------------------------------------------------------------------
1 | //Problem: https://leetcode.com/problems/balanced-binary-tree/
2 | /**
3 | * Definition for a binary tree node.
4 | * function TreeNode(val, left, right) {
5 | * this.val = (val===undefined ? 0 : val)
6 | * this.left = (left===undefined ? null : left)
7 | * this.right = (right===undefined ? null : right)
8 | * }
9 | */
10 | /**
11 | * @param {TreeNode} root
12 | * @return {boolean}
13 | */
14 |
15 |
16 |
17 |
18 | //Attempt # 1
19 | //(Failed, but able to identify quickly that this can be solved with Top Down recursive approach, but failed implementing it)
20 |
21 | var isBalanced = function(root) {
22 | if (!root) return true;
23 | function height(root) {
24 | if (!root) return -1;
25 | return 1 + Math.max(height(root.left), height(root.right));
26 | }
27 | if (Math.abs(height(root.left) - height(root.right)) > 1) return false;
28 | return isBalanced(root.left) && isBalanced(root.right);
29 | };
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/ArithmeticSlices.js:
--------------------------------------------------------------------------------
1 | //Attempt #1 (unsure)
2 | //Approach: Better Brute Force
3 | //Time: o(n^2)
4 | //Space: O(1)
5 | var numberOfArithmeticSlices = function(nums) {
6 | let count = 0;
7 | for (let i = 0; i < nums.length - 2; i++) {
8 | let diff = nums[i + 1] - nums[i];
9 | for (let j = i + 2; j < nums.length; j++) {
10 | if (nums[j] - nums[j-1] === diff) {
11 | count++;
12 | }else break;
13 | }
14 | }
15 | return count;
16 | };
17 |
18 | /*
19 | Progress Notes:
20 | 15 mins
21 | - try to solve the problem by myself - and know I want to use O(n^2) approach
22 | - did not find a solution, since the second for loop is done incorrectly
23 |
24 | 15 mins
25 | - review through the 2 brute force solutions (O(n^3) and O(n^2))
26 | - fully understand how the O(n^2) approach works
27 |
28 | Future Attempts:
29 | - Using Recursion --> T: O(n) S: O(n)
30 | - Using Dynamic Programming --> T: O(n) S: O(n)
31 |
32 | */
--------------------------------------------------------------------------------
/Independent_Frontend_Practice/README.md:
--------------------------------------------------------------------------------
1 | # Frontend Practice
2 |
3 | ## Fetching API + Displaying Data on the DOM
4 | - [Draft 1](https://codesandbox.io/s/weatherapi-cindylam-firstdraft-3irmqh) (07-27-22)
5 | I have practiced the Weather API exercise and tried to complete it within the 2 hours time limit.
6 |
7 | Here are some initial takeaways based on my practice:
8 | - using `async function` to fetch data + using `await` method to wait for the fetch data to process completely and then using `then` method to reformat the response into json format.
9 | - Once data is fetched, set the data state within the fetch data function and not outside. Why? - you will get a promise returning instead of the actual data being fetched, if you are setting the state outside of the fetch data function
10 | - Using `isFetched` bool variable to use it as an indicator to fetch and to clear out at the end of the useEffect function
11 | - Set up a `isLoading` state to make sure to display certain elements only once we have received fetched data
12 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/SpeedDrill/indicesAndValues.js:
--------------------------------------------------------------------------------
1 | /*PASSED
2 | Q. Given an array of indices and an array of integer values, return an array of all the values at those indices. Any out of bounds indices should be filled in with a 0. Indices follow a zero-based numbering rule (i.e. The index of the first element is 0 not 1).
3 |
4 | Example:
5 | Input: indicies: [0, 0, 5, 2, 3], values: [7, 6, 5, 4, 3]
6 | Output: [7, 7, 0, 5, 4]
7 |
8 | Input:
9 | indices: []
10 | values: []
11 | Output:
12 | []
13 |
14 |
15 | Input:
16 | indices: [1]
17 | values: []
18 | Output:
19 | [0]
20 |
21 | Input:
22 | indices: []
23 | values: [1]
24 | Output:
25 | []
26 |
27 | */
28 |
29 |
30 | function solution(indices, values) {
31 | if (indices.length < 1) return indices;
32 | if (values.length < 1) return [0];
33 | let res = [];
34 | for (let i = 0; i < values.length; i++) {
35 | if (indices[i] < indices.length) {
36 | res.push(values[indices[i]])
37 | }else res.push(0);
38 | }
39 | return res;
40 | }
41 |
--------------------------------------------------------------------------------
/1-on-1-w-Mentor-Fellow/power-of-two-w-brianzhu.js:
--------------------------------------------------------------------------------
1 | var isPowerOfTwo = function(n) {
2 | //base case
3 | if (n === 1) return true;
4 | if (n % 2 !== 0 || n === 0) return false; //if n is 6, it will keep dividing until it gets to 3, 3 % 2 === 1, so return false
5 |
6 | //recursive case
7 | return isPowerOfTwo(n/2)
8 | };
9 |
10 | //It is interesting to view how n and how recursive case is working behind the scene through console.logging, (I have also tried to test to see if I do not have 'return' for the recursive case, it basically will only return true at the deepest level, and then return undefined in the other level since no values are returned back to the top):
11 |
12 | var isPowerOfTwo = function(n) {
13 | //console.log("1: ", n);
14 | //base case
15 | if (n === 1) return true;
16 | if (n % 2 !== 0 || n === 0) return false;
17 | //console.log("2: ", n);
18 |
19 | //recursive case
20 | let bool = isPowerOfTwo(n/2)
21 | //console.log("3: ", n, bool);
22 | return bool;
23 | };
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/PathSumTree_07-27-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | Path Sum
3 |
4 | Pre-order approach (root left right)
5 | Adding up all the nodes at each path and return the true or false if a path is found
6 |
7 | OR
8 |
9 | post-order approach (left right root)
10 |
11 | */
12 | var hasPathSum = function(root, targetSum) {
13 | //Iterative Approach:
14 |
15 |
16 |
17 | //Recursive Approach:
18 | //Time: O(N) n = number of nodes (visit each node exactly once)
19 | //Space: O(h) h= the height of the tree (the recursive call would occur h times, the storage to keep the call stack would be O(h) for worst case scenario - tree is unbalanced)
20 | //O(logh) - when the tree is completely balanced, the recursive call would occur log h times
21 | // if (!root) {
22 | // return false;
23 | // }
24 |
25 | // targetSum -= root.val;
26 | // if (!root.left && !root.right) {
27 | // return targetSum === 0;
28 | // }
29 | // return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
30 | };
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/SpeedDrill/InsertTargetElem.js:
--------------------------------------------------------------------------------
1 | /* PASSED
2 | Q. Given a sorted array of integers and a target number, insert it after the first number that matches it, if no number matches it, do nothing.
3 |
4 | Examples:
5 | Input1: array = [1, 2, 3, 4, 5, 6], target =3
6 | Output1: [1, 2, 3, 3, 4, 5, 6]
7 |
8 | Input2: array = [1, 5, 7, 8], target = 7
9 | Ouput2: [1, 5, 7, 7, 8]
10 |
11 | Input3: array = [1, 5, 7, 8], target = 9
12 | Output3: [1, 5, 7, 8]
13 |
14 |
15 | Input:
16 | array: []
17 | target: 1
18 | Output:
19 | []
20 |
21 | Input:
22 | array: [1]
23 | target: 1
24 | Output:
25 | [1, 1]
26 | */
27 |
28 | function solution(array, target) {
29 | let foundIndex = -1;
30 | for (let i = 0; i < array.length; i++) {
31 | if (array[i] === target) foundIndex = i;
32 | }
33 | if (foundIndex >= 0) {
34 | let firstHalf = array.slice(0, foundIndex + 1);
35 | let secondHalf = array.slice(foundIndex + 1);
36 | console.log(secondHalf);
37 | return firstHalf.concat(target, secondHalf);
38 | }else return array;
39 | }
40 |
--------------------------------------------------------------------------------
/AlgoMarathon/Strings/Pair Learning/GroupAnagramswArthurDamm.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Given an array of strings strs, group the anagrams together. You can return the answer in any order.
4 |
5 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
6 |
7 |
8 |
9 | Example 1:
10 |
11 | Input: strs = ["eat","tea","tan","ate","nat","bat"]
12 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
13 | Example 2:
14 |
15 | Input: strs = [""]
16 | Output: [[""]]
17 | Example 3:
18 |
19 | Input: strs = ["a"]
20 | Output: [["a"]]
21 |
22 | */
23 |
24 | var groupAnagrams = function(strs) {
25 | let anagramGroups = {};
26 | for (const word of strs) { //eat, tea
27 | const sortedWord = word.split('').sort().join(''); //aet //sort can only use to sort an array but not a string
28 | if (!anagramGroups[sortedWord]){ //if it does not existed, it will return undefined (false), else return a value (true)
29 | anagramGroups[sortedWord] = []; //aet: [eat]
30 | }
31 | anagramGroups[sortedWord].push(word);
32 | }
33 | return Object.values(anagramGroups);
34 | };
--------------------------------------------------------------------------------
/AlgoWorkout/Vinit/04-20-22(2).py:
--------------------------------------------------------------------------------
1 |
2 | # APPROACH 2 (SOLUTION #1 - slice - with extra space):
3 | def removeDuplicates(array):
4 |
5 | sorted_arr = sorted(array)
6 | i = 0
7 | while i < len(sorted_arr) - 1:
8 |
9 | if i < len(sorted_arr) - 1 and sorted_arr[i] == sorted_arr[i + 1]:
10 | del sorted_arr[i]
11 | else:
12 | i += 1
13 |
14 | return sorted_arr
15 |
16 |
17 | # APPROACH 2 (SOLUTION #2 - two pointers - no extra space):
18 | def removeDuplicates(array):
19 |
20 | array.sort()
21 | i = 0 # write ptr
22 | j = 0 # read ptr
23 | while j < len(array):
24 | if j > 0 and array[j] == array[j - 1]: # if dup skip read over
25 | j += 1
26 | else: # else write
27 | array[i] = array[j]
28 | i += 1
29 | j += 1
30 | while i < len(array): # pop off extra elements after write pntr
31 | array.pop()
32 | return array
33 |
34 | print(removeDuplicates([4,2,6,7,4,8,7])) # [4,2,6,7,8]
35 | print(removeDuplicates([4,4,4,4,4])) # [4]
36 | print(removeDuplicates([1,3,2,6,8])) # [1,3,2,6,8]
37 | print(removeDuplicates([])) # []
38 |
39 |
40 |
--------------------------------------------------------------------------------
/AlgoMarathon/LinkedList/frequency.js:
--------------------------------------------------------------------------------
1 | // Singly-linked lists are already defined with this interface:
2 | // function ListNode(x) {
3 | // this.value = x;
4 | // this.next = null;
5 | // }
6 | //
7 | /*
8 | head: [1]
9 | f: 2
10 | target: 1
11 | Expected Output:
12 | [1]
13 |
14 | Input:
15 | head: [4, 1, 2, 1, 3, 2, 2]
16 | f: 1
17 | target: 1
18 | Expected Output:
19 | [4, 2, 1, 3, 2, 2]
20 |
21 |
22 | */
23 | function removeFrequencyTargetLL(head, f, target) {
24 | let sentinel = new ListNode(0);
25 | sentinel.next = head;
26 | let curr = sentinel;
27 | let count = 0; //inc count when removed target elem from list
28 | let LLSize = 0;
29 | let temp = head;
30 | while (temp) {
31 | LLSize++;
32 | temp = temp.next;
33 | }
34 | console.log(LLSize);
35 | while (curr && curr.next) {
36 | if (curr.next.value === target) {
37 | if (count < f && f <= LLSize) {
38 | curr.next = curr.next.next;
39 | count++;
40 | }else {
41 | curr = curr.next;
42 | }
43 | }else {
44 | curr= curr.next;
45 | }
46 | }
47 | return sentinel.next;
48 | }
49 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/PairLearning/pairSkillsLevelwRichard.js:
--------------------------------------------------------------------------------
1 | // Problem
2 |
3 | // Given an input dictionary mapping Fellows (as string names) to skill ratings, return true if you're able to pair up Fellows with matching skill ratings with no Fellows leftover.
4 | // Function Signature:
5 | // function canMatchFellows(input)
6 |
7 | // Examples:
8 |
9 |
10 | // {"oliver": 3, "pixel": 3, "pinky": 5, "tobey": 5} => true
11 | // {"oliver": 3, "pixel": 4, "pinky": 5, "tobey": 5} => false
12 | // {} => false
13 |
14 | function canMatchFellows(input) {
15 | let fellowsMap = new Set();
16 | for (const fellow in input) {
17 | let skills = input[fellow];
18 | if (fellowsMap.has(skills)) { //find matched skill level
19 | fellowsMap.delete(skills);
20 | }else { //do not find any
21 | fellowsMap.add(skills);
22 | }
23 | }
24 | return fellowsMap.size === 0;
25 | }
26 |
27 | let test1 = {"oliver": 3, "pixel": 3, "pinky": 5, "tobey": 5};
28 | let test2 = {"oliver": 3, "pixel": 4, "pinky": 5, "tobey": 5};
29 | let test3 = {};
30 |
31 | console.log(canMatchFellows(test1), true)
32 | console.log(canMatchFellows(test2), false)
33 | console.log(canMatchFellows(test3), true)
--------------------------------------------------------------------------------
/CoreAlgos/Array/Sort/bubble.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an unsorted array, perform bubble sort in ascending order.
3 |
4 | Examples:
5 | • Given an array: [1] // returns [1]
6 | • Given an array: [3, 1, 2, 4] // returns [1, 2, 3, 4]
7 | */
8 |
9 | function bubbleSort(array) {
10 |
11 | }
12 |
13 | // Test Cases
14 | console.log(bubbleSort([])) // []
15 | console.log(bubbleSort([1])) // [1]
16 | console.log(bubbleSort([3, 1, 2, 4])) // [1, 2, 3, 4]
17 | console.log(bubbleSort([-10, 1, 3, 8, -13, 32, 9, 5])) // [-13, -10, 1, 3, 5, 8, 9, 32]
18 |
19 | //----------------------------------------------------------------------------------
20 |
21 | //Approaches: Time: O(N^2)
22 |
23 | function bubbleSort(array) {
24 | //iterate through the entire array
25 | //compare the consecutive items in the second iteration within the subarray
26 | //if the current item is larger than the next item -> swap!!
27 |
28 | for(let i = 0; i < array.length; i++) { //main array
29 | for (let j = 0; j < array.length; j++) {//subarray
30 | const currentValue = array[j], nextValue = array[j + 1];
31 | if (currentValue > nextValue) {
32 | array[j + 1] = currentValue;
33 | array[j] = nextValue;
34 | }
35 | }
36 | }
37 |
38 | return array
39 | }
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/binaryTreePath.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 {string[]}
12 | *
13 | * on 06/13/22 This is my first time working through this tree problem without looking at the solution.
14 | *
15 | * There are 2 approaches (recursive or iterative) to this problem, I choose to use recursion to solve it.
16 |
17 | 1
18 |
19 | 2 3
20 |
21 | 4 5
22 |
23 | pre-order traversal DFS recursion
24 |
25 | */
26 | var binaryTreePaths = function(root) {
27 | let res = [];
28 | function dfs(str, node) {
29 | //base case
30 | if (!node) return null;
31 |
32 | //recursive case
33 | //root
34 | if (!node.left && !node.right) { //leaf node
35 | str += node.val
36 | res.push(str);
37 | }else {
38 | str += node.val + "->"
39 | }
40 | //left
41 | dfs(str, node.left);
42 | //right
43 | dfs(str, node.right);
44 | }
45 | dfs("", root);
46 | return res;
47 | };
--------------------------------------------------------------------------------
/AlgoMockedInterview/Basics_Self_Practice/Recursion/combo.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number} n
3 | * @param {number} k
4 | * @return {number[][]}
5 | */
6 | var combine = function(n, k) {
7 | let res = [];
8 |
9 | function backtrack(start, combo) {
10 | if (combo.length === k) { //know to push the combo found when it reached the height of the decision tree
11 | res.push([...combo]);
12 | return;
13 | }
14 |
15 | for (let i = start; i <= n; i++) { //number of intergers(where we are trying to iterate through each possibilities) //choose the numbers that are greater than the prev/smaller number
16 | console.log(i);
17 | combo.push(i);
18 | backtrack(i+1, combo);
19 | combo.pop();
20 | }
21 | }
22 |
23 | backtrack(1, []);
24 | console.log(res);
25 | return res;
26 | };
27 |
28 | /*
29 |
30 | param n = 4 (1-4 range)
31 | param k = 2 (2 combo)
32 |
33 |
34 | start at 1
35 |
36 | 1
37 | 2 3. 4 = 3 combo
38 |
39 | 2
40 | 1. 3. 4 = 2 combo (1,2 already existed)
41 |
42 | 3
43 | 1. 2. 4 = 1 combo (only 3,4)
44 |
45 | k = height of the decision tree
46 | complexity: n^k
47 | choose the numbers that are greater than the prev/smaller number
48 |
49 |
50 |
51 | */
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/backtrackingRecursionwDaniel_06-10-22.js:
--------------------------------------------------------------------------------
1 | // Backtracking = DFS of a decision tree
2 |
3 |
4 | function genericBacktracking() {
5 | // Are we at a dead
6 | // if we are handle this as a base case
7 | // return
8 |
9 | // for each possible branch (or choice)
10 | // try that choice recursively
11 | // merge results from different choices
12 |
13 | // return the result from this level or position
14 | }
15 |
16 | // [1, 2, 3] => [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
17 |
18 | function powerset(elements) {
19 | const result = [];
20 | const subset = [];
21 |
22 | function helper(i) {
23 | if (i === elements.length) {
24 | result.push([...subset]);
25 | return;
26 | }
27 |
28 | // Branch 1: include element at i
29 | subset.push(elements[i]);
30 | helper(i + 1);
31 |
32 | // Branch 2: do not include element at i
33 | subset.pop();
34 | helper(i + 1);
35 | }
36 |
37 | helper(0);
38 |
39 | return result;
40 | }
41 |
42 | console.log(powerset([1, 2, 3]))
43 |
44 | /*
45 | i _
46 | 0 1 !1
47 | 1 2 !2 2 !2
48 | 2 3 !3 3 !3 3 !3 3 !3
49 | 123 12 13 1 23 2 3 _
50 | */
--------------------------------------------------------------------------------
/CoreAlgos/Array/Find/numOfUnique.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an unsorted array, return the number of unique values. For example, given [1, 1], there are two elements but only one unique value: 1.
3 |
4 | Examples
5 | Input1: []
6 | Output1: 0
7 | Input2: [3, 1, 1, 2, 3, 1, 1, 1, 4]
8 | Output2: 4 // [1, 2, 3, 4]
9 | */
10 |
11 | function numUniques(array) {
12 |
13 | }
14 |
15 | // Test Cases
16 | console.log(numUniques([])) // 0
17 | console.log(numUniques([3, 1, 1, 2, 3, 1, 1, 1, 4])) // 2
18 | console.log(numUniques([1])) // 1
19 |
20 | //----------------------------------------------------------------------------------
21 |
22 | //Approaches:
23 |
24 | function numUniques(array) {
25 | //Better Approach - more cleaner in comparison with the other approach below
26 | let map = new Map();
27 | for (let i = 0; i < array.length; i++) {
28 | const count = (map.get(array[i]) || 0) + 1;
29 | map.set(array[i], count);
30 | }
31 | return Array.from(map.values()).filter((elem) => elem === 1).length;
32 |
33 | //Another Approach - using a set and an object instead of a map
34 | // let set = new Set();
35 | // let output = [];
36 | // for (let i = 0; i < array.length; i++) {
37 | // if (!set.has(array[i])) {
38 | // set.add(array[i]);
39 | // output.push(array[i]);
40 | // }
41 | // }
42 | // return output.length;
43 | }
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/smallestDifference.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Algo: Smallest Difference (must be solved in 20 mins)
4 |
5 | Example:
6 |
7 | input:
8 | arrayOne: [-1, 2, 3]
9 | arrayTwo: [5, 6, 4, 7]
10 |
11 | output:
12 | smallest difference pair: [3, 4]
13 |
14 | */
15 |
16 |
17 |
18 | //Attempt #1 (Failed) - only get to pseudo-coding and trying to think of different approaches
19 |
20 | /*
21 | Time Spent to understand the solution
22 | and generally watched through the video explanation: 15mins
23 | Time Spent : 25mins
24 | Talking through the thought process, how I approach the problem
25 | sorted or not
26 | assume these arrays can have different length
27 |
28 | Math.abs
29 |
30 | potentialMin = []
31 |
32 | -1 2 3 = L3 = arrayOne
33 | i
34 | 4 5 6 7 = L4 = arrayTwo
35 | j
36 |
37 | sorted both arrays
38 | compare the last number in both array
39 | if arrayOne[arrayOne.length -1] < ... arrayTwo
40 | we will only iterate through the arrayTwo and compare with the biggest number in
41 | the arrayOne
42 |
43 | find the min diff
44 |
45 | diff: 0
46 | pair: [3, 4]
47 | */
48 |
49 | function smallestDifference(arrayOne, arrayTwo) {
50 | arrayOne.sort((a, b) => a - b);
51 | arrayTwo.sort((a, b) => a - b);
52 | let i = 0;
53 | let j = 0;
54 | // while (i < arrayOne.length || j < arrayTwo.length) {
55 |
56 | // }
57 | }
58 |
--------------------------------------------------------------------------------
/CoreAlgos/Array/Find/firstRepeated.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an array of positive integers, find the first element that occurs k number of times. If no element occurs k times, return -1, and you may assume k is greater than 0.
3 |
4 | Examples:
5 | • Given an array: [1, 2, 2, 3, 3], k: 2 // returns 2
6 | • Given an array: [], k: 1 // returns -1
7 | */
8 | function firstKTimes(array, k) {
9 |
10 | }
11 |
12 | // Test Cases
13 | console.log(firstKTimes([1, 2, 2, 3, 3], 2)) // 2
14 | console.log(firstKTimes([1, 2, 2, 3, 3], 3)) // -1
15 | console.log(firstKTimes([], 1)) // -1
16 |
17 | //----------------------------------------------------------------------------------
18 |
19 | //Approaches:
20 |
21 | function firstKTimes(array, k) {
22 |
23 | //One way to approach:
24 | let map = new Map();
25 | for (let i = 0; i < array.length; i++) {
26 | const count = (map.get(array[i]) || 0 ) + 1;
27 | // console.log('before: ', map);
28 | // if (count === k) return array[i];
29 | map.set(array[i], count);
30 | // console.log('after: ', map);
31 | if (count === k) return map.get(array[i]);
32 | }
33 | return -1;
34 |
35 | // Another Approach:
36 |
37 | // const counts = new Map();
38 | // for (const el of array) {
39 | // const count = (counts.get(el) || 0) + 1;
40 | // if (count === k) return el;
41 | // counts.set(el, count);
42 | // }
43 | // return -1
44 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # formation_journey 💪🏼
2 | I will be documenting what I have learned being a Frontend Engineering Fellow at [Formation](https://formation.dev/) in this repo and a few in [my DEV blog](https://dev.to/ngl4). Feel free to take a look at my daily progress on Twitter [here](https://twitter.com/BCStory2). 🤓
3 |
4 | ## Overview 📝
5 | * [30+ Core Algos](https://github.com/ngl4/formation_journey/tree/main/CoreAlgos)
6 | * [Take Home](https://github.com/ngl4/formation_journey/tree/main/TakeHome)
7 | * [Algo Marathon](https://github.com/ngl4/formation_journey/tree/main/AlgoMarathon)
8 | * Collections of the [Monday's Words of Wisdom](https://github.com/ngl4/formation_journey/tree/main/WordsOfWisdom) from the Formation Team!
9 | * Small Group [Algo Workout Takeaways & Reflection](https://github.com/ngl4/formation_journey/tree/main/AlgoWorkout)
10 | * [1-on-1 Algo Coffee Hour w Mentors & Fellows](https://github.com/ngl4/formation_journey/tree/main/1-on-1-w-Mentor-Fellow)
11 | * [Weekly Mentor Office Hours Session](https://github.com/ngl4/formation_journey/tree/main/Weekly%20Gather%20Mentor%20Office%20Hours)
12 | * [Small Group Practice Sessions w Fellows](https://github.com/ngl4/formation_journey/tree/main/SmallGroupPractice)
13 | * [Live Coding - Frontend](https://github.com/ngl4/formation_journey/tree/main/LiveCoding)
14 | * [Mocked Behavioral Phone Screen](https://github.com/ngl4/formation_journey/tree/main/MockedBehavioralPhoneScreen)
15 |
16 |
17 |
--------------------------------------------------------------------------------
/SmallGroupPractice/README.md:
--------------------------------------------------------------------------------
1 | # Small Group Practice (outside of Formation Schedule)
2 |
3 |
5 |
6 | ## Jiyoon Koo, Eric Vo, Steven Zhu (06/14/22) - Algo Marathon ~ rotational programming
7 | - Going through different algo marathon problems and rotate around with different fellows solving different problems.
8 | - I started solving a `threeSum` problem. We talked about 2 approaches to the problem:
9 | - using `twoSum` as an example:
10 | - 1. Use two pointers i, j - find difference that match up with the target value by moving the pointers in the same direction
11 | - 2. Sort the array + Use two pointers i, j - place the two pointers each on the opposite end of the array and then move the j to the left when the difference is larger than the target value, and move i to the right when the difference is smaller than the target value.
12 | - Similar approach can be applied to `threeSum`
13 | - Want to try it out and explain how you would approach it?
14 |
15 | - Then we go through `Kadane's Algo`, `Linked List - find Kth elem from the end`, and `backtracking - letterCombination` problems.
16 | - Jiyoon, Eric and Steven are going through more problems since I need to start to wrap up my day and get some rest!!
17 |
18 |
19 |
20 | ...
--------------------------------------------------------------------------------
/AlgoMockedInterview/Basics_Self_Practice/Recursion/subsets.js:
--------------------------------------------------------------------------------
1 | /*Try again 09/08/22
2 |
3 | Given an integer array nums of unique elements, return all possible subsets (the power set).
4 |
5 | The solution set must not contain duplicate subsets. Return the solution in any order.
6 |
7 | Example 1:
8 |
9 | Input: nums = [1,2,3]
10 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
11 | Example 2:
12 |
13 | Input: nums = [0]
14 | Output: [[],[0]]
15 |
16 | */
17 |
18 |
19 |
20 |
21 |
22 |
23 | /** completed in the past
24 | * @param {number[]} nums
25 | * @return {number[][]}
26 | */
27 | /*
28 |
29 | Backtracking
30 | pick or not pick
31 |
32 | result array
33 | Recursive approach (array, index, curr_state)
34 | using index to keep track of our location within the array
35 |
36 | [1,2,3]
37 | ^
38 |
39 | [1,2,3]
40 | ^
41 |
42 | */
43 | var subsets = function(nums) {
44 | let result = [];
45 | function backtracking(arr, i = 0, curr_state = []) {
46 | //base
47 | if (i === arr.length) {
48 | result.push(curr_state);
49 | return;
50 | }
51 |
52 | //recursive
53 | //pick
54 | curr_state.push(arr[i]);
55 | backtracking(arr, i + 1, curr_state);
56 | arr.pop();
57 |
58 | //not pick
59 | // backtracking(arr, i + 1, curr_state);
60 |
61 | }
62 | backtracking(nums);
63 | return result;
64 | };
--------------------------------------------------------------------------------
/AlgoWorkout/Vinit/04-20-22(1).js:
--------------------------------------------------------------------------------
1 | /*
2 | Array Type Problem
3 |
4 | Prompt:
5 |
6 | Given an array of number that may contain duplicates, return a new array without the duplicates.
7 |
8 | Example:
9 | [4, 2, 6, 7, 4, 8, 7] => [4, 2, 6, 7, 8]
10 |
11 | */
12 |
13 | /*
14 | Approaches:
15 |
16 | APPROACH 1:
17 | no constraints on output order or extra space
18 | use a map and construct a de-duped array to return
19 | N space and time
20 |
21 | APPROACH 2:
22 | no extra space allowed, but order does not matter
23 | sort and remove dupes NlogN
24 |
25 | APPROACH 3:
26 | no extra space and order DOES matter
27 | nested loops N^2 solution
28 |
29 | */
30 |
31 | /*
32 | APPROACH 1:
33 | */
34 |
35 | function removeDuplicates(input){ //optimized version + correct function name (before noDuplicates) + params with descriptive name
36 | const seenNumbers = new Set();
37 | for(const item of input){
38 | seenNumbers.add(item)
39 | }
40 |
41 | /* for(let i = 0; i < array.length; i++){ //before optimization
42 | if(!set.has(array[i])){ //when using a set, there is no need to have an extra if statement
43 | set.add(array[i])
44 | }
45 | } */
46 |
47 | return Array.from(seenNumbers);
48 | }
49 |
50 | console.log(removeDuplicates([4,2,6,7,4,8,7])) // [4,2,6,7,8]
51 | console.log(removeDuplicates([4,4,4,4,4])) // [4]
52 | console.log(removeDuplicates([1,3,2,6,8])) // [1,3,2,6,8]
53 | console.log(removeDuplicates([])) // []
--------------------------------------------------------------------------------
/SystemDesign/README.md:
--------------------------------------------------------------------------------
1 | # System Design
2 |
3 | August-September
4 |
5 | ### System Design Bootcamp with Tala
6 | Takeaways:
7 | - Deconstructing System: User Stories, Non-functional requirements, Out-of-Scope features
8 |
9 | ### Pair learning with Rhema - Design a Facebook Event/ Evite App
10 | Takeaways:
11 | - No 2 microservices point to the same Database
12 |
13 | ### Pair Learning with Jeffery - Design a Shazam App
14 | Takeaways:
15 | - Using circle: client/user, vertical rectangular: LB, horizontal rectangular: microservices, diamond: Database, others (in dash rectangular): other services ie, 3rd party API
16 | - Data types should be included in the Output of the API (ie, `{}` or `[]`)
17 | - Don't use too many response code in the API output, make sure to think what you would like to return.
18 |
19 | ### System Design with Jeffery - Design a CraigsList App
20 | Takeways:
21 | - Some system can choose between either a non-relational or relational database
22 | - Normalization in Database (SQL)
23 | - Image Obj Store should be pointing to the "Listing Service" (images can be directly uploaded without going through an upload service)
24 |
25 | ### System Design with Justin Voskuhl - Design a food delivery App
26 | Takeaways:
27 | - Think about how the frontend should be doing to resolve the system failure situation!! - automatic retries! - why cant we retry a ton of time? - really hard to bring the server back up
28 | - REST vs GRPS
29 | - Encrypted Data Flow (HTTPS - why?)
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/height.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a binary tree, find the height of the tree.
3 |
4 | Example:
5 | • Given a binary tree:
6 | 1
7 | / \
8 | 7 3
9 | / \
10 | 4 5
11 | returns 2
12 | */
13 |
14 | class TreeNode {
15 | constructor(value = 0, leftChild = null, rightChild = null) {
16 | this.value = value
17 | this.left = leftChild
18 | this.right = rightChild
19 | }
20 | }
21 |
22 | function findTreeHeight(root) {
23 |
24 | }
25 |
26 | // Test Cases
27 | console.log(findTreeHeight(null), -1)
28 | console.log(findTreeHeight(new TreeNode(1, new TreeNode(2), new TreeNode(3))), 1)
29 | console.log(findTreeHeight(new TreeNode(2, new TreeNode(29, new TreeNode(26)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9))))), 3)
30 |
31 |
32 | //----------------------------------------------------------------------------------
33 |
34 | //Approaches:
35 |
36 |
37 | function findTreeHeight(root) {
38 | // recursive
39 | if (!root) return -1;
40 | // console.log(root);
41 | return 1 + Math.max(findTreeHeight(root.left), findTreeHeight(root.right));
42 | }
43 |
44 | // Test Cases
45 | // console.log(findTreeHeight(null), -1)
46 | // console.log(findTreeHeight(new TreeNode(1, new TreeNode(2), new TreeNode(3))), 1)
47 | // console.log(findTreeHeight(new TreeNode(2, new TreeNode(29, new TreeNode(26)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9))))), 3)
48 |
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/1_Accumulating/sum.js:
--------------------------------------------------------------------------------
1 | // Q. Given a linked list, sum all elements in the list.
2 |
3 | // Examples:
4 | // • Given a linked list: 1 ➞ 4 ➞ 5 // returns 10
5 | // • Given a linked list: 1 // returns 1
6 |
7 | class ListNode {
8 | constructor(value = 0, next = null) {
9 | this.value = value
10 | this.next = next
11 | }
12 | }
13 |
14 | function sum(head) {
15 | // Write your code here.
16 | }
17 |
18 | // Test Cases
19 | const LL1 = new ListNode(1, new ListNode(4, new ListNode(5)))
20 | console.log(sum(null)) // 0
21 | console.log(sum(LL1)) // 10
22 | console.log(sum(new ListNode(1))) // 1
23 |
24 |
25 |
26 | //----------------------------------------------------------------------------------
27 |
28 | //Approaches: (THIS IS REALLY SIMILAR TO COUNT - see count.js)
29 |
30 |
31 | //Iterative Approach (uncomment below and see how it works in the console)
32 |
33 |
34 | //Recursive Approach (uncomment below and see how it works in the console)
35 |
36 | function sumRecursive(head) {
37 | if (!head) return 0;
38 | console.log("head: ", head);
39 | return head.value + sumRecursive(head.next);
40 | }
41 |
42 | //UNCOMMENT BELOW TO TEST:
43 | // const LL2 = new ListNode(1, new ListNode(4, new ListNode(5)))
44 | // console.log(sumRecursive(null)) // 0
45 | // console.log(sumRecursive(LL2)) // 10
46 | // console.log(sumRecursive(new ListNode(1))) // 1
47 |
48 |
49 | /*
50 | Time Complexity (runtime): O(n)
51 |
52 | Space Complexity (memory): O(1)
53 |
54 | */
55 |
--------------------------------------------------------------------------------
/AlgoMockedInterview/Basics_Self_Practice/Array/containsDuplicates.js:
--------------------------------------------------------------------------------
1 | /*
2 | - Should I assume it should not be sorted? or can it be sorted? or does it really matter?
3 |
4 | [] => true or false?
5 | [1] => true
6 |
7 | Approaches:
8 |
9 | 1) Sort then find - if we encounter a num more than once, then it will return false, else keep iterating throu until the end of the array
10 |
11 | Time: O(n log n)
12 | Space: O(1)
13 |
14 | 2) Non-sorted - set a count variable + use a Map to store num item as the key and its frequency as the value (count)
15 |
16 | Time: O(n)
17 | Space: O(n)
18 |
19 | 3) Is there an optimized version?
20 |
21 | Time: O(n)
22 | Space: O(1)
23 |
24 | */
25 | var containsDuplicate = function(nums) {
26 | let freqMap = new Map();
27 | for (let i = 0; i < nums.length; i ++) {
28 | let count = freqMap.get(nums[i]) || 0;
29 | count++;
30 | if (count > 1) {
31 | return true;
32 | }
33 | freqMap.set(nums[i], count);
34 | }
35 | return false;
36 | };
37 |
38 | console.log(containsDuplicate([1,2,3,1]));
39 | console.log(containsDuplicate([1,2,3]));
40 |
41 | /*
42 | nums = [1,2,3,1]
43 |
44 | 1,2,3,1
45 | ^
46 |
47 | count = 2 => true
48 |
49 | {
50 | 1: 1
51 | 2: 1
52 | 3: 1
53 | }
54 |
55 | */
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/findMaxBinaryTree_3Ways.js:
--------------------------------------------------------------------------------
1 | class Tree {
2 | constructor(val, left=null, right=null) {
3 | this.value = val;
4 | this.left = left;
5 | this.right = right;
6 | }
7 | }
8 |
9 | //Find MAX node value in the Tree (3 WAYS TO IMPLEMENT)
10 |
11 | //OPTION #1: Max Value is a parameter of the dfs func (Return Value with parameter)
12 | function dfs(root, max_val) {
13 | if (!root) return null;
14 |
15 | max_val = Math.max(root.value, max_val);
16 |
17 | const leftMax = dfs(root.left, max_val);
18 | const rightMax = dfs(root.right, max_val);
19 |
20 | return Math.max(max_val, leftMax, rightMax);
21 | }
22 |
23 | //OPTION #2: Max Value is returned within the function (Return Value)
24 | function dfs(node) {
25 | if (!node) return -Infinity;
26 |
27 | const left_max_val = dfs(node.left)
28 | const right_max_val = dfs(node.right)
29 | return Math.max(node.value, left_max_val, right_max_val)
30 | }
31 |
32 |
33 | //OPTION #3: Max Value is a global variable (Global Variable)
34 | function findMaxValue(node) {
35 | let maxVal = -Infinity;
36 | function dfs(root) {
37 | if (!root) return null;
38 | maxVal = Math.max(root.value, maxVal);
39 | dfs(root.left);
40 | dfs(root.right);
41 | }
42 | dfs(node);
43 | return maxVal;
44 | }
45 |
46 |
47 | const tree = new Tree(1, new Tree(2, new Tree(4), new Tree(6)), new Tree(3))
48 | console.log(findMaxValue(tree));
49 | console.log(dfs(tree)) //should be 6
--------------------------------------------------------------------------------
/AlgoMockedInterview/1-on-1-with-Mentor /Afeez_08-31-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | Example Question: Write a function that takes form id as input, and returns the DOM form values as an object (map/hash).
3 |
4 |
5 | input:
11 |
12 |
13 | tagStack:
14 | valuesStack:
15 |
16 | output:
17 | Map
18 | {
19 | age:30,
20 | name: bill
21 | }
22 |
23 | - Get the children attribute name and its value
24 | - focus on the name attr and values associate with the tag
25 | - Can be Nested for each child element node
26 | - Only store the used element and its values (based on the name attr)
27 | - All names should be unique
28 | - All name attr should also have values
29 | - Should I assume the input be in the valid format
30 | - Is the input already a tree or is it a string?
31 | - does the order of the elements matters? (ordering should not be matter since the output is a map)
32 |
33 | Approaches:
34 |
35 | #1) DFS
36 | - "name" -> value
37 | - Going through every single element node
38 |
39 | String:
40 | - parseHTMLfunction (keep track of the opening and closing tags and separate tag to keep track of the values) => obj {} nodes
41 | => recursion
42 |
43 | helper func - parse DOM -> create func (DOMElemTree)
44 | - node (label, children: {label, div}, value: null)
45 |
46 |
47 | Form -> get key -> grab all keys
48 |
49 |
50 | stack1: (,(,
51 | stack2: 10
52 |
53 |
54 |
55 |
56 |
57 |
58 | */
59 |
60 |
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/BinarySearchTree/findElem.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a binary search tree and a target integer, check if the tree contains a target.
3 |
4 | Examples:
5 | • Given a binary search tree:
6 | 8
7 | / \
8 | 3 10
9 | / \ \
10 | 1 6 14
11 | /
12 | 13
13 | • For target: 4 // returns False
14 | • For target: 14 // returns True
15 | */
16 |
17 | class TreeNode {
18 | constructor(value = 0, leftChild = null, rightChild = null) {
19 | this.value = value
20 | this.left = leftChild
21 | this.right = rightChild
22 | }
23 | }
24 |
25 | function searchBST(root, target) {
26 | }
27 |
28 | // Test Cases
29 | let tree = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10, null, new TreeNode(14, new TreeNode(13))))
30 | console.log(searchBST(null, 1)) // false
31 | console.log(searchBST(tree, 1)) // true
32 | console.log(searchBST(tree, 14)) // true
33 | console.log(searchBST(tree, 2)) // false
34 | console.log(searchBST(tree, 13)) // true
35 | console.log(searchBST(new TreeNode(), 0)) // true
36 |
37 |
38 | //----------------------------------------------------------------------------------
39 |
40 | //Approaches:
41 |
42 | //Time (worst): O(n)
43 |
44 | //Recursive Approach:
45 | function searchBST(root, target) {
46 | if (!root) return false;
47 | if (root.value === target) return true;
48 | return searchBST(root.left, target) || searchBST(root.right, target);
49 | }
--------------------------------------------------------------------------------
/AlgoMarathon/Dynamic Programming/WaterArea.js:
--------------------------------------------------------------------------------
1 | /*
2 | Learn Strength Algo: Water Area
3 |
4 | Q. Given an array of non-negative integers, where each integer represents the height of a pillar of width 1, the water will be poured over all the pillars. Return the surface area enclosed by these pillars from the front. Spilled water should be ignored.
5 |
6 | Example:
7 | • Given an array: [1, 0, 2, 0, 3]
8 | | -> "*" is water trapped by the pillars
9 | |*| -> "|" is the one unit of the height of a pillar
10 | |*|*|
11 | -----
12 | returns 3
13 |
14 | Hint: This problem requires the left and right transversal on an array.
15 | Hint: Finding max is key
16 |
17 | */
18 |
19 |
20 | //Attempt #1 - Failed - Go over the video explanation on AlgoExpert on this problem
21 |
22 | function waterArea(heights) {
23 | //have not started coding this problem
24 | }
25 |
26 |
27 | /*
28 | Progress Note:
29 | 10 mins: conceptually understand the problem and think of approaches
30 | Thought about iterating through the heights array and then find the highest height in the array
31 | However, I am stuck at how I would be able to look for the second or third largest number on the left side and the right side of the highest pillar
32 |
33 | 15mins: Reviewed through Algo Expert video explanation on the problem as well as the approach that is used
34 |
35 | Future Attempt:
36 | - Make sure to re-explain the concept and record yourself while doing it
37 | - Code up a solution for the problem
38 | - Explain the problem in plain English
39 |
40 | */
--------------------------------------------------------------------------------
/CoreAlgos/FibSequence/fib.js:
--------------------------------------------------------------------------------
1 | /*
2 | Fib Sequence
3 |
4 | Q. Write a function which returns the Kth element of the Fibonacci sequence.
5 | The Fibonacci sequence is defined as a sequence in which each number is the sum of the preceding two numbers in the sequence.
6 | For the purpose of this question, the first two terms of the sequence are both 1, i.e. fib(0) = fib(1) = 1.
7 |
8 | Examples:
9 | Input: k = 2
10 | Output: 2
11 | Explanation:
12 | fib(2) = fib(0) + fib(1) = 1 + 1 = 2
13 | */
14 |
15 | function fib(k) { // number -> number
16 |
17 | }
18 |
19 | // Test Cases
20 | console.log(fib(0)) // 1
21 | console.log(fib(5)) // 8
22 | console.log(fib(11)) // 144
23 |
24 | //----------------------------------------------------------------------------------
25 |
26 | //Approaches:
27 |
28 | /*
29 | Testing the Approach:
30 |
31 | fib(3) = 3
32 | fib(4) = 5
33 | fib(5) = 8
34 |
35 | prev = 5
36 | cur = 8
37 |
38 | i=5; i < 6; i++
39 | */
40 |
41 | //Dynamic Programming Approach
42 | function fib(k) { // number -> number
43 | if (k <= 1) return 1;
44 | let curr = 1;
45 | let prev = 1;
46 | for (let i = 2; i < k + 1; i++) {
47 | // [prev, curr] = [curr, prev + curr];
48 | [curr, prev] = [curr + prev, curr];
49 | }
50 | return curr;
51 | }
52 |
53 | //Recursive Approach
54 | function fib(k) { // number -> number
55 | if (k <= 1) return 1;
56 | return fib(k-2) + fib(k-1)
57 | }
58 |
59 |
60 | //----------------------------------------------------------------------------------
61 |
62 |
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/4_Adding/appendTarget.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a linked list, append an element with a target value to the list.
3 |
4 | Examples:
5 | • Given a linked list: 1 ➞ 4 ➞ 5, target: 7 // returns 1 ➞ 4 ➞ 5 ➞ 7
6 | • Given a linked list: 0, target 7 // returns 0 ➞ 7
7 | */
8 |
9 | class ListNode {
10 | constructor(value = 0, next = null) {
11 | this.value = value
12 | this.next = next
13 | }
14 | }
15 |
16 | function arrayify(head) {
17 | let ptr = head
18 | var array = []
19 | while (ptr != null) {
20 | array.push(ptr.value)
21 | ptr = ptr.next
22 | }
23 | return array
24 | }
25 |
26 | function append(head, target) {
27 |
28 | }
29 |
30 | // Test Cases
31 | var LL1 = new ListNode(1, new ListNode(4, new ListNode(5)))
32 | console.log(arrayify(append(null, 1))) // [1]
33 | console.log(arrayify(append(LL1, 7))) // [1, 4, 5, 7]
34 | console.log(arrayify(append(new ListNode(), 7))) // [0, 7]
35 |
36 | //----------------------------------------------------------------------------------
37 |
38 | //Approaches:
39 |
40 | //Time: O(N)
41 |
42 | //Iterative Approach (uncomment below and see how it works in the console)
43 |
44 | function append(head, target) {
45 | if (!head) return new ListNode(target);
46 | let curr = head; //set a curr pointer
47 | while(curr.next) { //break the loop when curr.next is null
48 | curr = curr.next;
49 | }
50 | curr.next = new ListNode(target); //append the target node to the end of the linked list
51 | return head;
52 | }
53 |
54 | //Recursive Approach (uncomment below and see how it works in the console)
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/max.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a binary tree, find the element with the largest value.
3 |
4 | Example:
5 | • Given a binary tree:
6 | 1
7 | / \
8 | 7 3
9 | / \
10 | 4 5
11 | returns 7
12 | */
13 |
14 | class TreeNode {
15 | constructor(value = 0, leftChild = null, rightChild = null) {
16 | this.value = value
17 | this.left = leftChild
18 | this.right = rightChild
19 | }
20 | }
21 |
22 | function findTreeMax(root) {
23 |
24 | }
25 |
26 | // Test Cases
27 | console.log(findTreeMax(null)) // null
28 | console.log(findTreeMax(new TreeNode(1, new TreeNode(2), new TreeNode(3)))) // 3
29 | console.log(findTreeMax(new TreeNode(2, new TreeNode(29, new TreeNode(26)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9)))))) // 29
30 | console.log(findTreeMax(new TreeNode(1))) // 1
31 |
32 | //----------------------------------------------------------------------------------
33 |
34 | //Approaches:
35 |
36 | function findTreeMax(root) {
37 | //iterative (BFS approach)
38 | if (!root) return null;
39 | let max = root.value;
40 | let queue = [root];
41 | while (queue.length > 0) {
42 | let currentNode = queue.shift();
43 | max = Math.max(max, currentNode.value);
44 | if (currentNode.left) queue.push(currentNode.left);
45 | if (currentNode.right) queue.push(currentNode.right);
46 | }
47 | return max;
48 |
49 | //recursive
50 | // if (!root) return null
51 | // return Math.max(root.value, findTreeMax(root.left) || -Infinity, findTreeMax(root.right) || -Infinity);
52 | }
--------------------------------------------------------------------------------
/AlgoWorkout/Temi/05-18-22.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Given an array of 0s and 1s, what is the minimum number of moves needed to group all 0s on one side and 1s on the other side. A "move" is a swap between any adjacent positions.
4 |
5 | Examples
6 | [0, 1] => 0, no swaps are needed since they are already grouped.
7 | [0, 1, 0] => 1, swap 1 with either 0 to group them.
8 | [1, 0, 1, 1, 0] => 2, swap 0 with 1 then swap it again with the next 1.
9 | --> [1, 1, 1, 0, 0]
10 |
11 | [1, 0, 1, 1, 0]
12 | p
13 |
14 | [0, 1, 1, 1, 0] count = 1
15 | p
16 |
17 | [0, 1, 1, 1, 0] count = 1
18 | p
19 | p
20 | p
21 | p
22 |
23 | [0, 1, 1, 0, 1] count = 2
24 | p
25 |
26 | [0, 1, 0, 1, 1] count = 3
27 | p
28 |
29 | [0, 0, 1, 1, 1] count = 4
30 | p
31 |
32 |
33 | [1, 0, 1, 1, 0]
34 | l
35 | f
36 | work to get 0 at index 1 is: 1 - (-1) - 1 = 1
37 | add this work to total count = 1
38 | increment l by 1
39 |
40 | [1, 0, 1, 1, 0]
41 | l
42 | f
43 |
44 | work to get 0 at index 1 is: 4 - (0) - 1 = 3
45 | add this work to total count = 4
46 | increment l by 1
47 |
48 | [1, 0, 1, 1, 0]
49 | l
50 | f
51 |
52 |
53 | Function Signature
54 | function minSwaps(input: Array): number
55 |
56 | APPROACH
57 | count 1
58 | [0, 0, 1, 0]
59 | p1 p2
60 |
61 | counter:1
62 | [0, 1, 1, 1, 0]
63 | p1 p2
64 | counter:1
65 | [0, 1, 1, 1, 0]
66 | p1 p2
67 |
68 | counter:2
69 | [0, 1, 1, 0, 1]
70 | p1 p2
71 |
72 |
73 | value = 0
74 | swap = 1
75 | [0, 0, 1, 1, 0]
76 | f
77 | c
78 |
79 | p2
80 | [0, 1, 1, 1, 9]
81 |
82 | Compare in either directions:
83 | - 0s on the left
84 | -
85 | - 1s on the left
86 | */
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/5_Removing/removeTarget.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a sorted linked list of unique integers, remove a node with the target value from the list.
3 |
4 | Examples:
5 | • Given a linked list: -1 ➞ 1 ➞ 3 ➞ 4, target: 1 // returns -1 ➞ 3 ➞ 4
6 | • Given a linked list: 5, target: 3 // returns 5
7 | */
8 |
9 |
10 | class ListNode {
11 | constructor(value = 0, next = null) {
12 | this.value = value
13 | this.next = next
14 | }
15 | }
16 |
17 | function arrayify(head) {
18 | let ptr = head
19 | var array = []
20 | while (ptr != null) {
21 | array.push(ptr.value)
22 | ptr = ptr.next
23 | }
24 | return array
25 | }
26 |
27 | function remove(head, target) {
28 |
29 | }
30 |
31 | // Test Cases
32 | var LL1 = new ListNode(-1, new ListNode(1, new ListNode(3, new ListNode(4))))
33 | console.log(arrayify(remove(LL1, 1))) // [-1, 3, 4]
34 | console.log(arrayify(remove(LL1, -1))) // [3, 4]
35 | var LL1 = remove(LL1, -1) // Notice we expect this one to return a new head!
36 | console.log(arrayify(remove(LL1, 4))) // [3]
37 | console.log(arrayify(remove(LL1, 5))) // [3]
38 | console.log(arrayify(remove(new ListNode(1), 1))) // []
39 |
40 | //----------------------------------------------------------------------------------
41 |
42 | //Approaches:
43 |
44 |
45 | //Same approach as the removeAllTarget.js
46 | function removeInterative(node, target) {
47 | let sentinel = new ListNode(0);
48 | sentinel.next = node;
49 | let curr = sentinel;
50 |
51 | while(curr.next) {
52 | if (curr.next.value === target) {
53 | curr.next = curr.next.next;
54 | }else {
55 | curr = curr.next;
56 | }
57 | }
58 | //console.log(sentinel);
59 | return sentinel.next;
60 | }
61 |
--------------------------------------------------------------------------------
/AlgoWorkout/Arnold/binaryTreeInStringDepth.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Problem Statement
4 |
5 | You are given a binary tree that is represented by a string. Nodes have no value. A 0 represents null and a (00) represents a leaf node. ((00)0) would represent a tree where the root has one left node and no right node. ((00)(00)) represents a tree with one left and one right node.
6 | Given this representation of the tree, return an Int representing the depth of the tree.
7 |
8 |
9 | ((00)(00)) => ( defines root
10 |
11 | ( )
12 | (00) 0
13 |
14 | X
15 | /
16 | 00
17 |
18 | ((00)(00))
19 |
20 | Examples
21 | (((00)0)0) represents this tree:
22 | X
23 | /
24 | X
25 | /
26 | 00
27 |
28 | (((00)0)0)
29 | ( )
30 | ( )0
31 | (00)0
32 |
33 |
34 | (((00)(00))(00))
35 | ^
36 | pseudocode - iterative, counting parens
37 | iterate thru string,
38 | depth -> increase for the open parathesis
39 | when we encounter a closing, reduce the depth.
40 | math.max(depth, current_depth)
41 |
42 |
43 | This would return 2.
44 | Function Signature
45 | function depth(tree: String) -> Int
46 |
47 | */
48 |
49 | function depth(tree)
50 | {
51 | let maxDepth = -Infinity;
52 | let current_depth = 0;
53 | for (const t of tree) {
54 | // console.log(t);
55 | if(t === '(') {
56 | current_depth++;
57 | // console.log(current_depth);
58 | } else if (t === ')') {
59 | current_depth--;
60 | }
61 | maxDepth = Math.max(current_depth, maxDepth)
62 | }
63 | return maxDepth - 1;
64 | }
65 | /*
66 |
67 | */
68 | console.log(depth('((00)0)')) // 1
69 | console.log(depth('()')) // 0
70 | console.log(depth('((00)(00))')) // 1
71 | console.log(depth('(((00)(00))(00))')) //2
72 | console.log(depth('(0)')) // 0
--------------------------------------------------------------------------------
/1-on-1-w-Mentor-Fellow/sortedSquaredwMitch.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an integer array nums sotred in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
3 |
4 |
5 | Example 1:
6 | Input: nums = [-4,-1,0,3,10]
7 | Output: [0,1,9,16,100]
8 | Explanation: After squaring, the array becomes [16,1,0,9,100].
9 | After sorting, it becomes [0,1,9,16,100].
10 |
11 | Example 2:
12 | Input: nums = [-7,-3,2,3,11]
13 | Output: [4,9,9,49,121]
14 |
15 | edge case:
16 | - neg nums
17 | - empty cases
18 | - if 1 number array
19 |
20 |
21 | #1
22 | NlogN
23 | [-4,-1,0,3,10] loop and square items
24 | [16,1,0,9,100] loop and sort items
25 | [0,1,9,16,100] return this array
26 | output: [0,1,9,16,100]
27 |
28 | #2
29 | N
30 | input: [-7,-3,2,3,11]
31 | [49,9,4,9,121]
32 | [4,9,9,49,121]
33 | output: [4,9,9,49,121]
34 |
35 | N
36 | input => []
37 | output => []
38 |
39 | input => [3]
40 | input => [9]
41 |
42 |
43 | Time complexity
44 | nlogn
45 |
46 | Space complexity
47 | 1
48 |
49 |
50 |
51 | input: [-4,-1,0,3,10]
52 | [-4, -1] [0, 3, 10] spilt
53 | [16, 1] [0, 9, 100] sqaure both arrays
54 |
55 | [16, 1] [0, 9, 100]
56 | i
57 | j
58 | [0, 1, 9, 16, 100]
59 | T O(N)
60 | S O(N)
61 |
62 |
63 | */
64 |
65 | function sortedSquares(arr) {
66 | if (!arr.length) return arr;
67 | if (arr.length === 1) {
68 | arr[0] = arr[0] * arr[0];
69 | return arr;
70 | }
71 |
72 | for (let i = 0; i < arr.length; i++) {
73 | arr[i] = arr[i] * arr[i];
74 | }
75 |
76 | return arr.sort((a, b) => a - b);
77 | }
78 |
79 | console.log(sortedSquares([]), [])
80 | console.log(sortedSquares([3]), [9])
81 | console.log(sortedSquares([-4,-1,0,3,10]), [0,1,9,16,100])
82 | console.log(sortedSquares([-7,-3,2,3,11]), [4,9,9,49,121])
--------------------------------------------------------------------------------
/AlgoMarathon/Strings/Pair Learning/implementStrstrwCarlos.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given a string and a target search string, return the index of
3 | the first occurrence of the targetstring in the given string.
4 | If the target is not in the given, return -1
5 |
6 | Examples
7 | "hello", target: "l" => 2
8 | "hello", target: "ello" => 1
9 |
10 | hell
11 | ello
12 |
13 | i
14 | hello ello
15 | 5 4
16 |
17 | slice(start index, items)
18 | slice(0, 4) -> hell
19 | slice(1, 5) -> ello
20 |
21 | psedocode:
22 | 1. iterate through the given string
23 | 2. find the target string length
24 | 3. create a substring based on the length of the target string (using slice method)
25 | 4. compare the substring with the target string:
26 | if match, return index
27 | 5. if not match or once the iteration ends (substring.length > target.length), return -1
28 |
29 | */
30 |
31 | "kadfkgja hello"
32 | // Time: O(gt) | Space: O(t)
33 |
34 | // function strStr(given, target) {
35 | // for (let i = 0; i <= given.length - target.length; i++) {
36 | // let substring = given.slice(i, i + target.length);
37 | // if (substring === target) return i;
38 | // }
39 | // return -1;
40 | // }
41 |
42 | /*
43 | Time: O(gt) | Space: O(1)
44 | i = 1, j = 1
45 | "hello", target: "ello"
46 | i
47 |
48 | given[i + j] = l
49 | target[j] = l
50 |
51 | */
52 |
53 | function strStr(given, target) {
54 | for (let i = 0; i <= given.length - target.length; i++) {
55 | for (let j = 0; j <= target.length; j++) {
56 | if (given[i+j] !== target[j]) break;
57 | if (j === target.length - 1) return i;
58 | }
59 | }
60 | return -1;
61 | }
62 |
63 |
64 | console.log(strStr("hello", "l"), 2)
65 | console.log(strStr("hello", "ello"), 1)
66 | console.log(strStr("hello world", " "), 5)
67 | console.log(strStr(" hello world", " "), 0)
68 | console.log(strStr("hello world", "hi"), -1)
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/PairLearning/repeatedXElemswStoney.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an array and a target count X, return the number of elements that is repeated exactly X times.
3 | Function Signature:
4 | function numElementsRepeatedX(input, target)
5 |
6 | Examples:
7 | [1, 2, 3, 1, 2, 3], 2 => 3
8 | [1, 2, 3, 1, 2, 3], 3 => 0
9 |
10 | [1, 3, 3, 5, 5, 5, 5, 5, 3], 3 => 1
11 | 1: 1
12 | 3: 3
13 | 5: 5
14 | numOfRep = 1
15 |
16 | if currRep === target + 1
17 | numRep = numRep - 1
18 |
19 |
20 | [1, 2, 3, 1, 2, 3], 2 => 3
21 | 1: 2
22 | 2: 2
23 | 3: 2
24 | count === target (2=2)
25 | numOfRepeatedElems = 3
26 |
27 | [1, 2, 3, 1, 2, 3], 3 => 0
28 | 1: 2
29 | 2: 2
30 | 3: 2
31 | count !== target
32 | numOfRepeatedElems = 0
33 |
34 | assume the array.length > 1
35 | Exactly the same as target
36 |
37 |
38 | [1, 2, 3, 1, 2, 3], 2 => 3
39 |
40 | create the numOfRep variable = 0;
41 | create a map
42 | iterate through the input array
43 | set up a count(currRep) variable (to see if the arr[i] existed in the map, OR 0 if not in map) + 1
44 |
45 | store the arr[i] key, and count into the map
46 |
47 | if count === target
48 | numOfRep++
49 | if count === target + 1
50 | numOfRep--;
51 |
52 | reutrn numOfRep;
53 |
54 | Time: O(n)
55 | Space: O(n)
56 | */
57 |
58 | function numElementsRepeatedX(input, target) {
59 | let numOfRep = 0;
60 | let numMap = new Map();
61 | for (let i = 0; i < input.length; i++) {
62 | const count = (numMap.get(input[i]) || 0) + 1;
63 | numMap.set(input[i], count);
64 | if (count === target) numOfRep++;
65 | if (count === target + 1) numOfRep--;
66 | }
67 | return numOfRep;
68 | }
69 |
70 | console.log(numElementsRepeatedX([1, 2, 3, 1, 2, 3], 2), 3);
71 | console.log(numElementsRepeatedX([1, 2, 3, 1, 2, 3], 3), 0);
72 | console.log(numElementsRepeatedX([1, 3, 3, 5, 5, 5, 5, 5, 3], 3), 1);
73 |
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/count.js:
--------------------------------------------------------------------------------
1 | /*
2 | # Q. Given a binary tree, count the number of elements in the tree. (RECURSION)
3 |
4 | # Example:
5 | # • Given a binary tree:
6 | # 1
7 | # / \
8 | # 7 3
9 | # / \
10 | # 4 5
11 | # // returns 5
12 | */
13 |
14 | class TreeNode {
15 | constructor(value = 0, leftChild = null, rightChild = null) {
16 | this.value = value
17 | this.left = leftChild
18 | this.right = rightChild
19 | }
20 | }
21 |
22 | function countTree(root) {
23 | }
24 |
25 | // Test Cases
26 | console.log(countTree(null)) // 0
27 | console.log(countTree(new TreeNode(1, new TreeNode(2), new TreeNode(3)))) // 3
28 | console.log(countTree(new TreeNode(2, new TreeNode(29, new TreeNode(26)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9)))))) // 6
29 | console.log(countTree(new TreeNode())) // 1
30 |
31 |
32 | //----------------------------------------------------------------------------------
33 |
34 | //Approaches:
35 |
36 | function countTree(root) {
37 | //iterative (DFS approach)
38 | if (!root) return 0;
39 | let stack = root ? [root] : [];
40 | let counter = 0;
41 | while (stack.length) {
42 | counter++;
43 | let node = stack.pop(); //remove the most recent entered node
44 | if (node.left) stack.push(node.left);
45 | if (node.right) stack.push(node.right);
46 | }
47 | return counter;
48 | // recursive
49 | // if (!root) return 0;
50 | // return 1 + countTree(root.right) + countTree(root.left);
51 | }
52 |
53 | // Test Cases
54 | // console.log(countTree(null)) // 0
55 | // console.log(countTree(new TreeNode(1, new TreeNode(2), new TreeNode(3)))) // 3
56 | // console.log(countTree(new TreeNode(2, new TreeNode(29, new TreeNode(26)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9)))))) // 6
57 | // console.log(countTree(new TreeNode())) // 1
--------------------------------------------------------------------------------
/AlgoMarathon/Trie/PairLearning/TriewShauray.py:
--------------------------------------------------------------------------------
1 |
2 | # Build a trie class. Add/Insert new strings and Lookup/Search if strings exist.
3 |
4 | # class Trie {
5 |
6 | # add(word) {
7 |
8 | # }
9 |
10 | # lookup(word) {
11 |
12 | # }
13 | # }
14 |
15 | # const trie = new Trie()
16 | # trie.add("cat")
17 | # trie.lookup("cat") == true
18 | # trie.lookup("dog") == false
19 | # trie.add("dog")
20 | # trie.lookup("dog") == true
21 |
22 | # console.log(trie);
23 |
24 | class TrieNode:
25 | def __init__(self):
26 | self.children = {}
27 | self.endOfWord = False
28 |
29 |
30 | class Trie:
31 |
32 | def __init__(self):
33 | self.root = TrieNode()
34 |
35 | def add(self, word: str) -> None:
36 | cur = self.root
37 | for c in word:
38 | if c not in cur.children:
39 | cur.children[c] = TrieNode()
40 | cur = cur.children[c]
41 | cur.endOfWord = True
42 |
43 |
44 | def lookup(self, word: str) -> bool:
45 | cur = self.root
46 | for c in word:
47 | if c not in cur.children:
48 | return False
49 | cur = cur.children[c]
50 | return cur.endOfWord
51 |
52 |
53 |
54 | '''
55 | root
56 | [{c: __, a: ___, b: ___}]
57 | /
58 | [{o:__, a:__}]
59 | / \
60 | [{t:__}]. [ {t:__}]
61 | |. \
62 | [{s:___}, endOfWord: True]
63 | [{s:___}, endOfWord: True ]
64 | |
65 | [{}, endOfWord: True]
66 | '''
67 | # const trie = new Trie()
68 | # trie.add("cat")
69 | # trie.lookup("cat") == true
70 | # trie.lookup("dog") == false
71 | # trie.add("dog")
72 | # trie.lookup("dog") == true
73 |
74 | # console.log(trie);
75 |
76 | t = Trie()
77 | t.add('cat')
78 | print(t.lookup('cat'))
79 | print(t.lookup('dog'))
80 | t.add('dogs')
81 | print(t.lookup('dog'))
82 | print(t.lookup('hello'))
--------------------------------------------------------------------------------
/CoreAlgos/Array/Sort/selection.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an unsorted array, perform selection sort in ascending order.
3 |
4 | Examples:
5 | • Given an array: [1] // returns [1]
6 | • Given an array: [3, 1, 2, 4] // returns [1, 2, 3, 4]
7 | */
8 | function selectionSort(array) {
9 |
10 | }
11 |
12 | // Test Cases
13 | console.log(selectionSort([])) // []
14 | console.log(selectionSort([1])) // [1]
15 | console.log(selectionSort([3, 1, 2, 4])) // [1, 2, 3, 4]
16 | console.log(selectionSort([-10, 1, 3, 8, -13, 32, 9, 5])) // [-13, -10, 1, 3, 5, 8, 9, 32]
17 |
18 | //----------------------------------------------------------------------------------
19 |
20 | //Approaches: Time: O(N^2)
21 |
22 | /*
23 | Testing the Approach:
24 |
25 | -current item
26 | -current minimum
27 |
28 | 1 2 3 4
29 | i
30 | j
31 | m
32 | */
33 |
34 |
35 | //Better Approach:
36 | function selectionSort(array) {
37 | for (let i = 0; i < array.length; i++) {
38 | let min = i;
39 | for (let j = i + 1; j < array.length; j++) {
40 | if (array[min] > array[j]) {
41 | min = j;
42 | }
43 | }
44 | if (min !== i) {
45 | [array[i], array[min]] = [array[min], array[i]];
46 | }
47 | }
48 | return array;
49 | }
50 |
51 |
52 | //Another Approach:
53 | // function selectionSort(array) {
54 | // const length = array.length;
55 | // let minIndex, temp;
56 |
57 | // for (let i = 0; i < length; i++) {
58 | // minIndex = i;
59 | // for (let j = i + 1; j < length; j++) {
60 | // if (array[minIndex] < array[j]) continue; //DIFF: use continue
61 | // minIndex = j;
62 | // }
63 |
64 | // if (i != minIndex) {
65 | // temp = array[minIndex]; //DIFF: use temp variable instead of destructing
66 | // array[minIndex] = array[i];
67 | // array[i] = temp;
68 | // }
69 | // }
70 |
71 | // return array;
72 | // }
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/PairLearning/KandaneAlgowKengYu_07-15-22.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Given an array of integers, return maximum subarray sum. A subarray is any contiguous set of numbers
4 |
5 |
6 | can inputArray be empty? []
7 | what are the possible numbers in the inputArray
8 | [1,2,3,4] => 1 + 2 + 3 + 4 = 10
9 | [1,2,3,4,-20,2,3,4,5] => 10 => 0 => [2,3,4,5] => 14,13 => 14
10 | [] => 0
11 | [-3, -1, -2] => 0
12 | [1,2,3,4,-20] => 10
13 |
14 | max => the returned answer
15 | 14
16 | currSum, represents the current subarray we are considering
17 | 14 (current num is larger than currSum -> we reset the currSum to num)
18 |
19 | 1, 2, 3, 4, -20, 2, 3, 4, 5
20 | ^
21 | max = 14
22 | currSum = 14
23 |
24 |
25 | max = 10
26 | -10, 2 => if the current sum is smaller than the current number at index i
27 | reset our max counter
28 | only the max if the counter is greator than max
29 | keep summing up the numbers as we go
30 | keeps a max for record (current maximum subarray sum)
31 | */
32 |
33 | // time complexity
34 | // O(N) where N is number of the elements in the input array
35 | // space complexity
36 | // O(1) constant, we are not adding extra space other than the input
37 | function getMaximumSubArraySum(input) {
38 | let max = 0;
39 | let currSum = 0;
40 | for (const num of input) {
41 | currSum = Math.max(currSum + num, num);
42 | max = Math.max(max, currSum);
43 | }
44 | return max;
45 | }
46 |
47 |
48 |
49 | console.log(getMaximumSubArraySum([1,2,3,4])) //=> 1 + 2 + 3 + 4 = 10
50 | console.log(getMaximumSubArraySum([1,2,3,4,-20,2,3,4,5])) //=> 10 => 0 => [2,3,4,5] => 14,13 => 14
51 | console.log(getMaximumSubArraySum([])) //=> 0
52 | console.log(getMaximumSubArraySum([-3, -1, -2])) //=> 0
53 | console.log(getMaximumSubArraySum([1,2,3,4,-20])) //=> 10
54 |
55 |
56 | /*
57 | 3
58 | 2 5
59 | 2 5 3 2
60 |
61 |
62 |
63 | 1, 2, -10, 2, 3
64 | */
--------------------------------------------------------------------------------
/CoreAlgos/Array/Sort/merge.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an unsorted array, perform merge sort in ascending order.
3 |
4 | Examples:
5 | • Given an array: [1] // returns [1]
6 | • Given an array: [3, 1, 2, 4] // returns [1, 2, 3, 4]
7 |
8 | https://www.youtube.com/watch?v=jlHkDBEumP0
9 | https://www.youtube.com/watch?v=4VqmGXwpLqc
10 | */
11 | function mergeSort(array) {
12 |
13 | }
14 |
15 | // Test Cases
16 | console.log(mergeSort([])) // []
17 | console.log(mergeSort([1])) // [1]
18 | console.log(mergeSort([3, 1, 2, 4])) // [1, 2, 3, 4]
19 | console.log(mergeSort([-10, 1, 3, 8, -13, 32, 9, 5])) // [-13, -10, 1, 3, 5, 8, 9, 32]
20 |
21 | //----------------------------------------------------------------------------------
22 |
23 | //Approaches: Time: O(n log n)
24 |
25 | function mergeSort(array) {
26 | //split array - find the mid point and then split up the array
27 | if (array.length < 2) {
28 | return array;
29 | }
30 | let mid = Math.floor((array.length/2));
31 | let left = array.slice(0, mid);
32 | let right = array.slice(mid); //mid -> last
33 | // console.log(mid, left, right);
34 |
35 | return merge(mergeSort(left), mergeSort(right));
36 | }
37 |
38 | function merge(left, right) {
39 | //result array
40 | let result = [];
41 |
42 | //based left right length - loop
43 | //comparison left vs right - smaller value push first to result array, push larger value next
44 | while (left.length && right.length) {
45 | if (left[0] < right[0]) { //push left
46 | result.push(left.shift());
47 | }else {//push right
48 | result.push(right.shift());
49 | }
50 | }
51 | //create two new variables (clone of the left and right)
52 | let cloneLeft = left.slice(); //[3]
53 | let cloneRight = right.slice(); //[]
54 | // console.log(cloneLeft, cloneRight);
55 |
56 | //return
57 | return result.concat(cloneLeft, cloneRight);
58 | }
59 |
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/binaryTreeLeftView.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given a binary tree t, return its left view. To understand what the left view of the tree means, imagine yourself standing on the left side of the tree: The left view will be all the vertices that you can see. For example, imagine the following tree:
3 |
4 | ---> 1
5 | ---> / \
6 | ---> 2 3
7 | ---> \ \
8 | ---> 5 4
9 | ---> /
10 | ---> 6
11 | In this case, you can see vertices 1, 2, 5, and 6.
12 |
13 | Given binary tree t, return the values of the vertices in the left view, ordered from top to bottom.
14 |
15 | Input:
16 | root:
17 | {
18 | "value": 1,
19 | "left": null,
20 | "right": null
21 | }
22 | Expected Output:
23 | [1]
24 |
25 | Input:
26 | root:
27 | {
28 | "value": 1,
29 | "left": {
30 | "value": 2,
31 | "left": null,
32 | "right": null
33 | },
34 | "right": null
35 | }
36 | Expected Output:
37 | [1, 2]
38 |
39 |
40 | Input:
41 | root:
42 | {
43 | "value": 1,
44 | "left": null,
45 | "right": {
46 | "value": 2,
47 | "left": null,
48 | "right": null
49 | }
50 | }
51 | Expected Output:
52 | [1, 2]
53 |
54 |
55 | */
56 |
57 |
58 | //ATTEMPT#1: FAILED
59 | // Binary trees are already defined with this interface:
60 | // function Tree(x) {
61 | // this.value = x;
62 | // this.left = null;
63 | // this.right = null;
64 | // }
65 | function solution(root) {
66 | let output = [];
67 | let maxDepth = -Infinity;
68 | let depth = 1;
69 | function DFS(node) {
70 | if (!node) return null;
71 | if (node && depth === 1) output.push(node.value);
72 | if (node && depth > output.length) {
73 | output.push(node.value);
74 | depth++;
75 | }
76 | solution(node.left)
77 | solution(node.right)
78 | }
79 | DFS(root);
80 | console.log(output);
81 | return output;
82 | }
83 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/verticalZigzag2DMatrix.js:
--------------------------------------------------------------------------------
1 | /*##############################################################
2 | Q. Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in vertical zigzag order (see examples below) starting from the top left element
3 |
4 | Examples:
5 | Input1:
6 | [
7 | [1, 2, 3],
8 | [4, 5, 6],
9 | [7, 8, 9]
10 | ]
11 |
12 | Output1:
13 | [1, 4, 7, 8, 5, 2, 3, 6, 9]
14 |
15 | Input2:
16 | [
17 | [1, 2, 3],
18 | [4, 5, 6]
19 | ]
20 |
21 | Output2: [1, 4, 5, 2, 3, 6]
22 | ##############################################################*/
23 |
24 | function verticalZigzag(m) {
25 | const newArr = [];
26 |
27 | for (let j = 0; j < m[0].length; j++) {//columns
28 | if (j % 2 === 0) {//even
29 | for (let i = 0; i < m.length; i++) { //row //going forward down the column
30 | newArr.push(m[i][j]);
31 | }
32 | }else {//odd
33 | for (let i = m.length - 1; i >= 0; i--) { //row //going backward up the column
34 | newArr.push(m[i][j]);
35 | }
36 | }
37 | }
38 |
39 | // Why the following is generating incorrectly?
40 |
41 | // for (let j = 0; j < m[0].length; j++) {
42 | // forwards
43 | // for (let i = 0; i < m.length; i++) {
44 | // let num = m[i][j];
45 | // if (j % 2 === 0) {
46 | // newArr.push(num)
47 | // } else {
48 | // backwards
49 | // for (let k = m[j].length - 1; k >= 0; k--) {
50 | // newArr.push(num[k])
51 | // }
52 | // }
53 | // }
54 | // }
55 | return newArr;
56 | };
57 |
58 | // test cases
59 | const testCase1 = [
60 | [1, 2, 3],
61 | [4, 5, 6],
62 | [7, 8, 9]
63 | ]
64 | // [1, 4, 7, 8, 5, 2, 3, 6, 9]
65 |
66 | const testCase2 = [
67 | [1, 2, 3],
68 | [4, 5, 6]
69 | ]
70 | // [1, 4, 5, 2, 3, 6]
71 |
72 | console.log(verticalZigzag(testCase1));
73 | console.log(verticalZigzag(testCase2));
74 |
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/bt_BFS.js:
--------------------------------------------------------------------------------
1 | /*
2 | Find Element in a Binary Tree using BFS
3 |
4 | Q. Given a binary tree and a target element's value, determine if the tree contains the target using breadth first search (BFS).
5 |
6 | Examples:
7 | • Given a binary tree:
8 | 3
9 | / \
10 | 29 4
11 | / \
12 | 2 2
13 | /
14 | 9
15 | • For target: 1 // returns False
16 | • For target: 2 // returns True
17 | */
18 |
19 | class TreeNode {
20 | constructor(value = 0, leftChild = null, rightChild = null) {
21 | this.value = value
22 | this.left = leftChild
23 | this.right = rightChild
24 | }
25 | }
26 |
27 | function BFSTree(root, target) {
28 |
29 | }
30 |
31 | // Test Cases
32 | const tree1 = new TreeNode(3, new TreeNode(29, new TreeNode(5)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9))))
33 | console.log(BFSTree(null, 1)) // false
34 | console.log(BFSTree(tree1, 9)) // true
35 | console.log(BFSTree(tree1, 1)) // false
36 | console.log(BFSTree(tree1, 2)) // true
37 | console.log(BFSTree(new TreeNode(1), 2)) // false
38 |
39 | //----------------------------------------------------------------------------------
40 |
41 | //Approaches:
42 |
43 | /*
44 | Using Queue (FIFO) - First in First out
45 |
46 |
47 | Queue
48 | ________
49 | <- <- <-
50 | ________
51 |
52 | */
53 |
54 | //Time: O(n)
55 |
56 | function BFSTree(root, target) {
57 | // console.log(root, target);
58 | let queue = root ? [root] : [];
59 | while (queue.length > 0) {
60 | // console.log("BEFORE QUEUE: ", queue);
61 | let curr = queue.shift(); //remove whatever comes first in the queue
62 | // console.log(curr);
63 | // console.log("AFTER QUEUE: ", queue);
64 | if (curr.value === target) return true;
65 | if (curr.left) queue.push(curr.left);
66 | if (curr.right) queue.push(curr.right);
67 | }
68 | return false
69 | }
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/3_Finding_TwoPointers/findMiddle.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Q. Given a linked list, find the middle element in one pass. If the length of the list is even, return the first of the two middle nodes.
4 | Follow-up: What if we want to return the second of the two middle nodes in lists with even numbers of nodes?
5 |
6 | Examples:
7 | • Given a linked list: 1 ➞ 3 ➞ 5 // returns 3
8 | • Given a linked list: 1 ➞ 2 ➞ 3 ➞ 4 // returns 2
9 |
10 | */
11 |
12 | class ListNode {
13 | constructor(value = 0, next = null) {
14 | this.value = value
15 | this.next = next
16 | }
17 | }
18 |
19 | function findMiddle(head) {
20 |
21 | }
22 |
23 | // Test Cases
24 | const LL1 = new ListNode(1, new ListNode(3, new ListNode(5)))
25 | const LL2 = new ListNode(1, new ListNode(3, new ListNode(-13, new ListNode(-3, new ListNode(1)))))
26 | const LL3 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))))
27 | console.log(findMiddle(null)) // null
28 | console.log(findMiddle(LL1)) // 3
29 | console.log(findMiddle(LL2)) // -13
30 | console.log(findMiddle(LL3)) // 2
31 | console.log(findMiddle(new ListNode(1))) // 1
32 |
33 | //----------------------------------------------------------------------------------
34 |
35 | //Approaches:
36 |
37 | //Time: O(n)
38 |
39 | function findMiddle(head) {
40 | //Better Approach:
41 | if (!head) return null;
42 | let slow = head, fast = head.next;
43 |
44 | while (fast.next && fast.next.next) {
45 | slow = slow.next;
46 | fast = fast.next.next;
47 | }
48 | return slow.value;
49 |
50 | //Another Approach:
51 | // let fast = head, slow = head, curr = head;
52 | // while (curr) {
53 | // if (!fast.next || !fast.next.next) return slow.value; //we need !fast.next.next to avoid scenario with "even number" Linked List. !fast.next is used to avoid "odd number" LL.
54 | // fast = fast.next.next;
55 | // slow = slow.next;
56 | // curr = curr.next;
57 | // }
58 | // return null;
59 | }
60 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/ConvertArrToZigzag.js:
--------------------------------------------------------------------------------
1 | /*
2 | Prompt:
3 | Given an array of DISTINCT elements,
4 | rearrange the elements of array in zig-zag fashion in O(n) time.
5 | The converted array should be in form a < b > c < d > e < f.
6 |
7 | Example:
8 |
9 | Input: arr[] = {4, 3, 7, 8, 6, 2, 1}
10 | Output: arr[] = {3, 7, 4, 8, 2, 6, 1}
11 |
12 | Input: arr[] = {1, 4, 3, 2}
13 | Output: arr[] = {1, 4, 2, 3}
14 |
15 | */
16 |
17 | //Attempt #1 - unsure
18 |
19 | const createZigzag = (arr) => {
20 |
21 | //ATTEMPT1: BUBBLE SORT AND SWAPPING - O(N^2)
22 | // for (let i = 0; i < arr.length; i++) {
23 | // for (let j = 0; j < arr.length; j++) {
24 | // let currVal = arr[j]
25 | // let nextVal = arr[j+1];
26 | // if (arr[j+1] < arr[j]){
27 | // arr[j+1] = currVal;
28 | // arr[j] = nextVal;
29 | // }
30 | // }
31 | // }
32 | // for (let i = 1; i < arr.length - 1; i+=2) {
33 | // [arr[i], arr[i+1]] = [arr[i+1], arr[i]];
34 | // }
35 | // return arr;
36 | }
37 |
38 | const test1 = createZigzag([1, 4, 3, 2]);
39 | const test2 = createZigzag([4, 3, 7, 8, 6, 2, 1]);
40 | console.log(test1); //[1, 4, 2, 3] or [1, 3, 2, 4]
41 | console.log(test2); //[3, 7, 4, 8, 2, 6, 1] or [1,3,2,6,4,8,7]
42 |
43 |
44 | /*
45 | 22 mins:
46 | - Read and understand the prompt
47 | - Spend 10 mins to think of an approach (blank out and not sure), write test cases
48 | - So check the first hint - simple solution: sort first then swap items after the first index
49 | - did visualizations on simple solution and start writing up the solution
50 | - since I have used bubble sort to sort through the array, the time complexity is O(n^2)
51 |
52 | 15 mins:
53 | - Document my progress note
54 | - Reading through the efficient approach with the time complexity of O(n)
55 | - Watching the Youtube video
56 |
57 | Questions:
58 | - Why is the simple solution time complexity is O(N log N)?
59 |
60 | Future Attempts:
61 | - Try to use the O(n) approach
62 |
63 | */
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/TwoNumSum.js:
--------------------------------------------------------------------------------
1 | /*
2 | 07-03-22
3 | */
4 | var twoSum = function(nums, target) {
5 | //one pass hashtable Time: O(n) Space: O(n) - Optimized (increase space to reduce time)
6 | let indexMap = new Map(); //key: 'item value' value: 'index number'
7 | for (let i = 0; i < nums.length; i++) {
8 | let remaining = target - nums[i];
9 | if (indexMap.has(remaining)) {
10 | return [indexMap.get(remaining), i];
11 | }
12 | indexMap.set(nums[i], i);
13 | }
14 |
15 | //brute force Time: O(n^2) Space: O(1)
16 | // for (let i = 0; i < nums.length; i++) {
17 | // let currVal = nums[i];
18 | // for (let j = i + 1; j < nums.length; j++) {
19 | // let sum = currVal + nums[j];
20 | // if (sum === target) {
21 | // return [i, j];
22 | // }
23 | // }
24 | // }
25 | };
26 |
27 |
28 | /**
29 | * @param {number[]} numbers
30 | * @param {number} target
31 | * @return {number[]}
32 | */
33 | var twoSum = function(numbers, target) {
34 | //Two pointers: Time: O(n) Space: O(1) - more optimized space solution
35 | let low = 0;
36 | let high = numbers.length - 1;
37 |
38 | while (low < high) {
39 | let sum = numbers[low] + numbers[high];
40 | if (sum === target) {
41 | return [low + 1, high + 1];
42 | }else if (sum < target) {
43 | low++;
44 | }else {
45 | high--;
46 | }
47 | }
48 | return [-1, -1];
49 |
50 |
51 | //one pass hashtable: Time: O(n) Space: O(n)
52 | // let indexMap = new Map();
53 | // for (let i = 0; i < numbers.length; i++) {
54 | // let remaining = target - numbers[i];
55 | // if (indexMap.has(remaining)) {
56 | // return [indexMap.get(remaining) + 1, i + 1];
57 | // }
58 | // indexMap.set(numbers[i], i);
59 | // }
60 | };
--------------------------------------------------------------------------------
/CoreAlgos/README.md:
--------------------------------------------------------------------------------
1 | # 30+ Core Algos ⏳
2 |
3 | Core Algos are only on these basic data structures:
4 | - Linked List
5 | - Binary Tree
6 | - Binary Search Tree
7 | - Array
8 |
9 | ### Linked List ⛓
10 |
11 | #### Group #1: Accumulating elements
12 |
13 | - Count Elements in a Linked List
14 | - Sum Element Values in a Linked List
15 |
16 | #### Group #2: Finding without a Pointer
17 |
18 | - Find a Highest/Max Element Value in a Linked List
19 | - Find an Element in a sorted Linked List
20 |
21 | #### Group #3: Finding with 2 pointers
22 |
23 | - Find a Middle Element in a Linked List in One Pass
24 | - Find Kth Element from the End of a Linked List in One Pass
25 |
26 | #### Group #4: Adding an element to a Linked List
27 |
28 | - Append an element with a target value to the Linked List
29 | - Insert a target element in a sorted Linked List ⭐️
30 |
31 | #### Group #5: Removing element(s) from a Linked List
32 |
33 | - Remove a target element in a sorted Linked List ⭐️
34 | - Remove all elements with a target value in a Linked List ⭐️
35 |
36 | #### Group #6: Reversing elements
37 |
38 | - Reverse a Linked List
39 |
40 | #### Group #7: Summing Linked Lists
41 |
42 | - Sum Two Linked Lists of Equal Length ⭐️
43 |
44 | ⭐️ _Sentinel node can be used to solve these problems_
45 | ___
46 |
47 | ### Binary Tree 🌳
48 |
49 | - **BFS** (Breadth First Search) and/or **DFS** (Depth First Search)
50 | - Count elements
51 | - Sum elements
52 | - Find max
53 | - Find height
54 |
55 | #### Binary Search Tree (BST)
56 | - Find element
57 | - Insert element
58 | - Validate BST
59 |
60 | ___
61 |
62 | ### Array 🍫
63 |
64 | #### Array: Find Elements
65 | - Find first element repeated k times
66 | - Find number of unique elements
67 | - Find number of duplicated elements
68 | - Find index of a target element using Binary Search
69 |
70 | #### Array: Sort Elements
71 | - Bubble Sort
72 | - Selection Sort
73 | - Insertion Sort
74 | - Merge Sort
75 |
76 | ___
77 |
78 | ### Fib Sequence 🐚
79 | - Dynamic programming
80 | - Iterative & Recursive approaches
--------------------------------------------------------------------------------
/AlgoSprint/README.md:
--------------------------------------------------------------------------------
1 | # Algo Sprint
2 |
3 | ## Nam (05/27/22) on Reduce, Map, Fitler, Some, Every Functions - Scratch in Linked List
4 |
5 | There are only 2 fellows in this session, but I feel like I am able to participate more and learn more when the session is smaller, especially on Algo Sprint.
6 |
7 | **Reflection**
8 | - I still need to keep practicing the basics and make sure I can explain my thought process and higher level approach well. Most importantly, I need to work on implementation.
9 | - Through this session, I know that I need to start `recording` or video recording (either way works) myself more often and listen back to how I communciate. This helps me to know if I am able to fully understand what I am talking about. I want to know if I am an interviewer, would I be able to follow through what I say.
10 | - Thanks to Nam who has been guiding and giving hints to help me to understand the problem and the implementation. I really like his mentoring style. He is able to explain the problem using `visualization` really well. It is really helpful to me to learn from my mistakes and know `why` it is a mistake. He is also really good at giving feedback on `how we communicate`, I have not put a lot of thought in this and I think being aware of this through this session helps me to know how I change my learning style.
11 | - Nam is really good at manually testing the code, I have not seen how it was done before and it is the first time seeing a mentor walking through how manual testing can be done.
12 | - I need to learn to identify based on the implementation - if it is working or not.
13 |
14 | **Takeaways**
15 | - Make sure to practice to understand all the fundamental Js methods well, know what they are returning (array, object, booleans, string, etc.)
16 | - Make sure I can implement these methods in `different data structures` besides array
17 | - Make sure to be able to build out these methods `from scratch`
18 | - `Verbalize` what I think
19 | - `Manual testing` the code is a key skill to have
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/AlgoWorkout/Stanley /autocomplete.js:
--------------------------------------------------------------------------------
1 | /**
2 | The programming interface for a legacy motor controller accepts commands as binary strings of variable length. The console has a very primitive autocomplete autocorrect feature: given an incomplete command, it will display possible commands that has the incomplete command as a prefix. For example, if '1010' is a possible command and the user enters '10', the interface should return '1010' as a possible autocomplete result.
3 | Implement a data structure that will allow us to efficiently query possible autocomplete results given an incomplete input.
4 |
5 |
6 |
7 | Possible commands = ['000', '1110', '01', '001', '110', '11']
8 | Input -> Output
9 | '0' → ['000', '01', '001']
10 | '1' → ['1110', '110', '11']
11 | '00' → ['000', '001']
12 |
13 | 0 -> [..]
14 | 1 -> [..]
15 | 01
16 | 10
17 | 11
18 | 001
19 |
20 | possible: '00', '00
21 | root
22 | 0 1
23 | 0 1
24 | 0 1
25 | 0 1 0
26 |
27 | TreeNode:
28 | - value
29 | - left (TreeNode)
30 | - right (TreeNode)
31 | - isCommand
32 |
33 | build_tree_function:
34 | - initialize our root tree node
35 | - traverse each possible command
36 | - traverse the tree and insert the command node, setting the node command flag to true
37 |
38 |
39 | -traverse based on input
40 | check node command flag at each node after the input
41 | if it's true add it to an array of possible comands.
42 |
43 | input: 00
44 |
45 | output:
46 | 00001, 000
47 |
48 | **/
49 |
50 | // INCOMPLETE ATTEMPT TO THE PROBLEM
51 |
52 | class TreeNode {
53 | constructor(value = 0, left = null, right = null, isCommand = false) {
54 | this.value = value;
55 | this.left = left;
56 | this.right = right;
57 | this.isCommand = isCommand;
58 | }
59 | }
60 | //'000'
61 | function buildTree(commands) {
62 | let root = new TreeNode(0);
63 | for (let i = 0; i < commands.length; i++) {
64 | let single_command = command[i];
65 | }
66 | // return new TreeNode();
67 | }
68 |
69 | // new TreeNode()
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/1_Accumulating/countQ2.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q2. Count the odd elements in a linked list (iterative & recursive)
3 |
4 | Given a linked list of positive integers, count the elements with odd values from the list.
5 |
6 | Note 0 is an even number.
7 |
8 | Examples
9 | Input1: 1 → 1 → 1 → 1
10 | Output1: 4
11 | Input2: 1 → 2 → 3 → 4
12 | Output2: 2
13 | */
14 |
15 | class ListNode {
16 | constructor (value, next = null) {
17 | this.value = value;
18 | this.next = next;
19 | }
20 | }
21 |
22 | const countOddElemLL = (head) => {
23 | // Write your code here.
24 | }
25 |
26 | // Test Cases
27 | const LL1 = new ListNode(1, new ListNode(1, new ListNode(1, new ListNode(1))));
28 | const LL2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
29 | console.log(countOddElemLL(LL1)) // 4
30 | console.log(countOddElemLL(LL2)) // 2
31 |
32 |
33 |
34 |
35 | //----------------------------------------------------------------------------------
36 |
37 | //Approaches:
38 |
39 | //iterative
40 | const countOddElemIterative = (head) => {
41 | let count = 0;
42 | while (head) {
43 | if (head.value % 2 !== 0) {
44 | count++;
45 | }
46 | head = head.next;
47 | }
48 | console.log("head :", head);
49 | return count;
50 | }
51 |
52 | // const LL3 = new ListNode(0, new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))));
53 | // console.log(countOddElemIterative(LL3)); //3
54 |
55 | //recursive
56 | const countOddElemRecursive = (head) => {
57 | if (!head) return 0;
58 | let count = 0;
59 | if (head.value % 2 !== 0) {
60 | count++;
61 | }
62 | console.log("head :", head);
63 | return count + countOddElemRecursive(head.next);
64 | }
65 |
66 | // const LL4 = new ListNode(0, new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))));
67 | // console.log(countOddElemRecursive(LL4)); //3
68 |
69 | /*
70 | Time Complexity (runtime): O(n)
71 |
72 | Space Complexity (memory): O(1)
73 |
74 | */
75 |
76 |
--------------------------------------------------------------------------------
/AlgoMarathon/Backtracking/Permutations_practice.js:
--------------------------------------------------------------------------------
1 | function permutations(letters) {
2 | function dfs(path, used, res) {
3 | if (path.length == letters.length) {
4 | const strPath = path.join('');
5 | res.push(strPath);
6 | return;
7 | }
8 | for (let i = 0; i < letters.length; i++) {
9 | // skip used letters
10 | if (used[i]) continue; //skip
11 | // add letter to permutation, mark letter as used
12 | path.push(letters[i]);
13 | used[i] = true;
14 | dfs(path, used, res);
15 | // remove letter from permutation, mark letter as unused
16 | path.pop();
17 | used[i] = false;
18 | }
19 | }
20 | const res = [];
21 | letters = [...letters];
22 | dfs([], new Array(letters.length).fill(false), res);
23 | return res;
24 | }
25 |
26 | // console.log(permutations("abc"));
27 |
28 | const KEYBOARD = {
29 | '2': 'abc',
30 | '3': 'def',
31 | '4': 'ghi',
32 | '5': 'jkl',
33 | '6': 'mno',
34 | '7': 'pqrs',
35 | '8': 'tuv',
36 | '9': 'wxyz',
37 | };
38 |
39 | function letterCombinationsOfPhoneNumber(digits) {
40 | let res = [];
41 | function dfs(digits, path, res) {
42 | if (path.length === digits.length) {
43 | console.log("path (push to res):", path);
44 | res.push(path.join(''));
45 | console.log(res);
46 | return;
47 | }
48 | console.log("path(begining of recursion):", path);
49 | let next_number = digits.charAt(path.length);
50 | console.log(next_number); //6
51 | for (let letter of KEYBOARD[next_number]) { //l
52 | console.log(letter);
53 | path.push(letter);
54 | dfs(digits, path, res);
55 | path.pop();
56 | console.log("path(right after pop):", path);
57 | }
58 | }
59 | dfs(digits, [], res);
60 | return res;
61 | }
62 |
63 | console.log(letterCombinationsOfPhoneNumber('56'))
64 |
65 |
66 |
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/bt_DFS.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a binary tree and a target element's value, determine if the tree contains the target using depth first search (DFS).
3 |
4 | Examples:
5 | • Given a binary tree:
6 | 3
7 | / \
8 | 29 4
9 | / \
10 | 2 2
11 | /
12 | 9
13 | • For target: 1 // returns False
14 | • For target: 2 // returns True
15 | */
16 |
17 | class TreeNode {
18 | constructor(value = 0, leftChild = null, rightChild = null) {
19 | this.value = value
20 | this.left = leftChild
21 | this.right = rightChild
22 | }
23 | }
24 |
25 | function DFSTree(root, target) {
26 |
27 | }
28 |
29 | // Test Cases
30 | const tree1 = new TreeNode(3, new TreeNode(29, new TreeNode(2)), new TreeNode(4, null, new TreeNode(2, new TreeNode(9))))
31 | console.log(DFSTree(null, 1)) // false
32 | console.log(DFSTree(tree1, 9)) // true
33 | console.log(DFSTree(tree1, 1)) // false
34 | console.log(DFSTree(tree1, 2)) // true
35 | console.log(DFSTree(new TreeNode(1), 2)) // false
36 |
37 |
38 | //----------------------------------------------------------------------------------
39 |
40 | //Approaches:
41 |
42 | /*
43 |
44 | Stack - LIFO (Last In First Out)
45 |
46 | | 3 | entered as 1 2 3 | exited as 3 2 1 (1 is first in last out)
47 | | 2 |
48 | |___1___|
49 |
50 | */
51 |
52 | //Recursive Approaches:
53 |
54 | function DFSTree(root, target) {
55 | if (!root) {
56 | // console.log("NO ROOT --> ROOT === NULL --> THE CHILD IS NULL");
57 | return false;
58 | }
59 | if (root.value === target) return true;
60 | // console.log(root);
61 | return DFSTree(root.left, target) || DFSTree(root.right, target);
62 | }
63 |
64 | //Another Approach:
65 |
66 | // function DFSTree(root, target) {
67 | // if (!root) return null;
68 |
69 | // if (root.value === target) return true;
70 |
71 | // let left = DFSTree(root.left, target),
72 | // right = DFSTree(root.right, target);
73 |
74 | // return !left && !right ? false : true;
75 | //}
76 |
77 |
78 |
--------------------------------------------------------------------------------
/CoreAlgos/Array/Find/binarySearch.js:
--------------------------------------------------------------------------------
1 | /*
2 | Using Binary Search to find the index of the target value in an array
3 | */
4 |
5 | function binarySearch(array, target, left = 0, right = array.length-1) {
6 | }
7 |
8 | // Test Cases
9 | var array = [1, 2, 3, 6, 8, 13, 113, 153, 200]
10 | console.log(binarySearch(array, 1)) // 0
11 | console.log(binarySearch(array, 200)) // 8
12 | console.log(binarySearch(array, 8)) // 4
13 | console.log(binarySearch(array, 154)) // -1
14 |
15 | //----------------------------------------------------------------------------------
16 |
17 | //Approaches:
18 |
19 |
20 | function binarySearch(array, target, left = 0, right = array.length-1) {
21 | //INTERATIVE BINARY SEARCH
22 | let targetIndex = -1;
23 | while (targetIndex < 0 && left <= right) {
24 | let mid = Math.floor((left + right) / 2);
25 |
26 | if (array[mid] === target){
27 | targetIndex = mid;
28 | }
29 | else if (target < array[mid]) {
30 | right = mid - 1;
31 | }
32 | else {
33 | left = mid + 1;
34 | }
35 | }
36 | return targetIndex;
37 |
38 | //Another Iterative Approach:
39 | // let firstIndex = 0;
40 | // let lastIndex = array.length - 1;
41 | // let mid;
42 | // while(firstIndex <= lastIndex) {
43 | // mid = Math.floor((firstIndex + lastIndex)/2);
44 | // if(array[mid] === target) return mid;
45 | // if(target > array[mid]) {
46 | // firstIndex = mid + 1;
47 | // }else {
48 | // lastIndex = mid - 1;
49 | // }
50 | // }
51 | // return -1;
52 |
53 | //RECURSIVE BINARY SEARCH (UNCOMMENT BELOW TO SEE HOW IT WORKS!!)
54 | // console.log(array, target, left, right);
55 | // if (left > right) return -1;
56 | // let mid = Math.floor((left + right) / 2);
57 | // console.log(left, right, mid);
58 | // if (array[mid] === target) return mid;
59 | // else if (target < array[mid]) return binarySearch(array, target, left, mid - 1);
60 | // else if (target > array[mid]) return binarySearch(array, target, mid + 1, right);
61 | }
62 |
63 |
--------------------------------------------------------------------------------
/AlgoWorkout/Temi/05-09-22.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Given an array of chronological prices for a stock, find the maximum profit to be made per stock. You can make at most one trade and there are no trading fees.
4 |
5 | Examples
6 | [2, 5] -> 3 (buy at 2, sell at 5)
7 | [6, 10, 2, 3, 8] -> 6 (buy at 2, sell at 8)
8 | Function Signature
9 | function maximizeProfit(prices: Array): number
10 |
11 | create bestProfit variable to -Infinity
12 | loop through input array ----> i
13 | loop through input array from i+1 ------> j
14 | if num[j] - num[i] > bestProfit
15 | update bestProfit
16 | currDiff =
17 | maxDiff = 2
18 | l c
19 | [8, 10, 15, 2, 4]
20 |
21 | [6, 8, 10, 2, 3]
22 |
23 | */
24 |
25 | function maxProfit(arr){
26 | let bestProfit = -Infinity;
27 | for(let i = 0; i < arr.length; i++) {
28 | for(let j = i + 1; j < arr.length; j++) {
29 | if(arr[j] - arr[i] > bestProfit){
30 | bestProfit = arr[j] - arr[i];
31 | }
32 | }
33 | }
34 | return bestProfit
35 | }
36 | //[3, 10, 2, 3, 8]
37 | //
38 |
39 | // console.log(maxProfit([2, 5])) // 3
40 | // console.log(maxProfit([6, 10, 2, 3, 8])) // 6
41 |
42 | /*
43 | current_difference = 1
44 | max_difference = 4
45 | current_min
46 | [6, 8, 10, 2, 3]
47 |
48 | i
49 | m
50 |
51 | create currDiff, maxDiff, currMin = array[0]
52 | loop through array, i + 1 -> arrayLength
53 | currDiff = currElement - currMin
54 | if currElement < currMin
55 | currMin = currElement
56 | if currDiff > maxDiff
57 | maxDiff = currDiff
58 | return maxDiff
59 | */
60 |
61 | function maxProfitv2(arr) {
62 | let min = arr[0];
63 | let bestProfit = -Infinity;
64 | for (let i = 1; i < arr.length; i++) {
65 | const cur = arr[i];
66 | const curProfit = cur - min;
67 | if (cur < min) {
68 | min = cur;
69 | }
70 | if (curProfit > bestProfit) {
71 | bestProfit = curProfit;
72 | }
73 | }
74 | return bestProfit;
75 | }
76 |
77 | console.log(maxProfitv2([2, 5])) // 3
78 | console.log(maxProfitv2([6, 10, 2, 3, 8])) // 6
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/repeatedXtimes.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an array and a target count X, return the number of elements that is repeated exactly X times.
3 |
4 | Function Signature:
5 | function numElementsRepeatedX(input, target)
6 |
7 | */
8 |
9 | //ATTEMPT #1 (Passed)
10 |
11 | /*
12 | Test Cases:
13 |
14 | input:
15 | array: [2, 3, 4, 3, 6, 3, 8, 8, 3]
16 | targetCount: 2
17 |
18 | output: 1 ===> (8)
19 |
20 | Same array
21 | repeatedTime: 1
22 |
23 | output: 3 ===> (2, 4, 6)
24 |
25 |
26 | Approach:
27 | - iterate through the array 1 time
28 | - create a Map to store the array item (as key) and count (as value)
29 | - if the count is equal to the targetCount, break from the loop
30 | - return the number of elements by finding out how many keys have the values (equal to targetCount)
31 |
32 | T: O(n) - only have 1 iteration
33 | S: O(n) - since extra space is created (Map) and it will be changing proportionally to the input array size
34 |
35 | */
36 |
37 | const findRepeatedElements = (input, targetCount) => {
38 | const allElems = new Map();
39 | for (let i = 0; i < input.length; i++) {
40 | const count = (allElems.get(input[i])|| 0) + 1;
41 | allElems.set(input[i], count);
42 | }
43 | return Array.from(allElems).filter(elem => elem[1] === targetCount).length; //OPTION#1 Array.from(allElems) = [[2, 1], [3, 4], [4, 1], [6, 1], [8, 2]]
44 | // return Array.from(allElems.values()).filter(elem => elem === targetCount).length; //OPTION#2 Array.from(allElems.values()) = [1, 4, 1, 1, 2]
45 | }
46 |
47 | console.log(findRepeatedElements([2, 3, 4, 3, 6, 3, 8, 8, 3], 1)); //output: 3
48 | console.log(findRepeatedElements([2, 3, 4, 3, 6, 3, 8, 8, 3], 2)); //output: 1
49 |
50 |
51 | /*
52 | PROGRESS NOTE:
53 |
54 | 10m: writing up the test cases, approaches, time & space complexities
55 |
56 | 20m: coding up the function + test cases
57 |
58 | Reflection:
59 | - Still need to make sure I am familiarize with Map and Set and all the related methods
60 |
61 | Future Attempts:
62 | - Make sure I will work through this problem under 10 mins with visualization, approach, and coding out the solution
63 | */
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/mergeThreeLists.js:
--------------------------------------------------------------------------------
1 | /*
2 | Algo: Merge 3 sorted lists (Easy)
3 |
4 | Given three sorted arrays of integers, merge them into a single sorted list.
5 | Examples
6 |
7 | Input1: array1: [1, 2], array2: [3, 4], array3: [5, 6]
8 | Output1: [1, 2, 3, 4, 5, 6]
9 |
10 | Input2: array1: [1, 2, 10], array2: [2, 9], array3: [11]
11 | Output2: [1, 2, 2, 9, 10, 11]
12 |
13 | */
14 |
15 |
16 | function mergeThreeLists(array1, array2, array3) {
17 | //APPROACH #1: T: O(nlogn) S: O(1)
18 | // return array1.concat(array2, array3).sort((a, b) => a - b);
19 |
20 | //APPROACH #2: T: O(n) S: O(n)
21 | let i1 = 0, i2 = 0, i3 = 0;
22 | let output = [];
23 | while (i1 < array1.length || i2 < array2.length || i3 < array3.length) {
24 |
25 | let v1 = i1 < array1.length ? array1[i1] : Infinity; //only set to infinity when arr has no more items
26 | let v2 = i2 < array2.length ? array2[i2] : Infinity;
27 | let v3 = i3 < array3.length ? array3[i3] : Infinity;
28 |
29 | // console.log(v1, v2, v3); //1, 2, 11
30 |
31 | let min = Math.min(v1, v2, v3);
32 |
33 | // console.log(min); //1
34 |
35 | if (min == v1) {
36 | // console.log(i1); //0
37 | output.push(array1[i1++]); //pushing i1 first to the output array and then increment
38 | // console.log(output); //[1]
39 | // console.log(i1); //1
40 | } else if (min == v2) {
41 | output.push(array2[i2++]);
42 | } else {
43 | output.push(array3[i3++]);
44 | }
45 | }
46 | return output;
47 | }
48 |
49 | console.log(mergeThreeLists([1, 2, 10], [2, 9], [11]), [1, 2, 2, 9, 10, 11]);
50 |
51 |
52 | /*
53 | Progress Notes:
54 |
55 | Approach#1: took me 4 mins to write out the solution
56 |
57 | Approach#2: I spent around 10 mins on the problem and did not get anywhere.
58 | I have looked up the solution and learn how it is solved and worked on understanding the problem.
59 | And the pattern used. I am slightly close because I have thought of using a while loop and Math.min(),
60 | but I have not been able to successfully write out the approach to the problem
61 |
62 | */
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/PairLearning/BSTtoDoublyLLwAngel.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as in-order of the given Binary Tree. The first node of in-order traversal (leftmost node in BT) must be the head node of the DLL.
3 | *
4 | * Example
5 | * 3
6 | * 1. 5
7 | * 2. 4
8 | *
9 | *
10 | * null <- 1 <-> 2 <-> 3 <-> 4 <-> 5 -> null
11 | *
12 | *
13 |
14 | Approach: DFS Recursive In-order
15 |
16 | In order: left -> self -> right
17 |
18 | head = 1
19 | tail = 3
20 |
21 | #Left
22 | dfs(node.left)
23 |
24 | #Self
25 | if tail exists:
26 | tail.right = node // 1 -> 2 -> 3
27 | node.left = tail. // 1 <-> 2 <-> 3
28 |
29 | update tail = node
30 |
31 | #Right
32 | dfs(node.right)
33 |
34 | */
35 |
36 |
37 | class TreeNode {
38 | constructor(value, left = null, right = null) {
39 | this.value = value;
40 | this.left = left;
41 | this.right = right;
42 | }
43 | }
44 |
45 | function bst2dll(root) {
46 | let head = null, tail = null;
47 | //helper dfs function
48 | function dfs(node) {
49 | //base case
50 | if (!node) return;
51 | dfs(node.left);
52 | //self
53 | if (tail) {
54 | tail.right = node;
55 | node.left = tail;
56 | } else {
57 | head = node;
58 | }
59 | tail = node;
60 | dfs(node.right);
61 | }
62 | //call the dfs helper function
63 | dfs(root);
64 | return head;
65 | }
66 |
67 | console.log(bst2dll(new TreeNode(3,
68 | new TreeNode(1,
69 | null,
70 | new TreeNode(2)
71 | ),
72 | new TreeNode(5,
73 | new TreeNode(4),
74 | null)
75 | )))
76 | // null <- 1 <-> 2 <-> 3 <-> 4 <-> 5 -> null
77 |
78 | console.log(bst2dll(
79 | new TreeNode(3,
80 | new TreeNode(1,
81 | new TreeNode(2,
82 | new TreeNode(5,
83 | new TreeNode(4)
84 | )
85 | )
86 | )
87 | )
88 | )
89 | )
--------------------------------------------------------------------------------
/LiveCoding/LiveCodingwChinedu.js:
--------------------------------------------------------------------------------
1 | /*
2 | Display number (font color - white)
3 | Display buttons
4 | - same circle shape except zero
5 | - with different colors
6 | - orange in the last column (font color - white)
7 | - light grey in the right row (font color - black)
8 | - dark grey for the rest (font color - white)
9 | -
10 |
11 | Circle component (map)
12 | - border-radius 50
13 |
14 | - map, classname
15 |
16 | for the zero circle, add specific class for sizing
17 |
18 | -flexbox
19 |
20 | */
21 |
22 | /*
23 | const Circle = ({className, text}) => {
24 | return (
25 | {text}
26 | )
27 | }
28 |
29 | const NUMBER_OF_CALCULATOR_DARKGRAY_BUTTONS =[...Array(11).keys()];
30 |
31 | const App = () => {
32 | React.useEffect(() => {
33 | console.log(NUMBER_OF_CALCULATOR_DARKGRAY_BUTTONS);
34 | }, [])
35 | return (
36 |
37 |
40 |
41 | {NUMBER_OF_CALCULATOR_DARKGRAY_BUTTONS.map((elem) =>
42 | {
43 | return (
44 |
48 | )
49 | })}
50 |
51 |
52 | )
53 | }
54 |
55 | ReactDOM.render(, document.getElementById('root'))
56 |
57 | */
58 |
59 | /*
60 | .App {
61 | font-family: monospace;
62 | display: flex;
63 | flex-direction: column;
64 | background-color: black;
65 | width: 300px;
66 | height: 400px;
67 | box-sizing: border-box;
68 | }
69 |
70 | .numberDisplay {
71 | height: 100px;
72 | }
73 |
74 | .buttonsDisplay {
75 | display: flex;
76 | flex-direction: row;
77 | flex-wrap: wrap;
78 | justify-content: space-around;
79 | width: 150px;
80 | }
81 |
82 | .circle {
83 | border-radius: 50%;
84 | width: 3em;
85 | height: 3em;
86 | }
87 |
88 |
89 | .orangebg {
90 | background-color: orange;
91 | }
92 |
93 | .darkGreyBg {
94 | background-color: darkgrey;
95 | color: white;
96 | text-align: center;
97 | padding-top: 1em;
98 | }
99 | */
--------------------------------------------------------------------------------
/AlgoMarathon/Strings/BackSpaceStringCompare.js:
--------------------------------------------------------------------------------
1 | /*
2 | Algo: Backspace String Compare
3 |
4 | Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
5 |
6 | Note that after backspacing an empty text, the text will continue empty.
7 |
8 | Example 1:
9 |
10 | Input: s = "ab#c", t = "ad#c"
11 | Output: true
12 | Explanation: Both s and t become "ac".
13 | Example 2:
14 |
15 | Input: s = "ab##", t = "c#d#"
16 | Output: true
17 | Explanation: Both s and t become "".
18 | Example 3:
19 |
20 | Input: s = "a#c", t = "b"
21 | Output: false
22 | Explanation: s becomes "c" while t becomes "b".
23 |
24 | */
25 |
26 | //Attempt 1 (failed) - the following is the brute force approach from other submission on Leetcode
27 |
28 | var backspaceCompare = function(s, t) {
29 | let firstString = '';
30 | let secondString = '';
31 |
32 | for(let i = 0; i < s.length; i++) {
33 | const char = s[i];
34 | if(char !== '#') {
35 | firstString += char;
36 | } else {
37 | firstString = firstString.slice(0, -1);
38 | }
39 | }
40 |
41 | for(let i = 0; i < t.length; i++) {
42 | const char = t[i];
43 | if(char !== '#') {
44 | secondString += char;
45 | } else {
46 | secondString = secondString.slice(0, -1);
47 | }
48 | }
49 |
50 | return firstString === secondString;
51 | };
52 |
53 | /*
54 | Progress Notes:
55 |
56 | Time: O(s^2 + t^2) Space: O(1)
57 | There is an iteration of the entire string (O(n) time) and the nested js ".slice" method is considered a O(n) time complexity
58 |
59 | 25mins: I have used the time to try to code out the O(s + t) time and O(1) space approach but with no success.
60 | Then, I try to see if I can just solve the problem, but I think I am not progressing at all.
61 |
62 | 5mins: reviewed through the solution generally and review through one of the submission that I find a little easier to understand
63 | But the time complexity is not good.
64 |
65 | Future attempts:
66 | - solve the problem with O(s + t) time and O(1) space
67 | - review the solution in Leetcode to fully understand the pattern
68 |
69 | */
--------------------------------------------------------------------------------
/CoreAlgos/Array/Sort/insertion.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given an unsorted array, perform insertion sort in ascending order.
3 |
4 | Examples:
5 | • Given an array: [1] // returns [1]
6 | • Given an array: [3, 1, 2, 4] // returns [1, 2, 3, 4]
7 |
8 | */
9 |
10 | function insertionSort(array) {
11 |
12 | }
13 |
14 | // Test Cases
15 | console.log(insertionSort([])) // []
16 | console.log(insertionSort([1])) // [1]
17 | console.log(insertionSort([3, 1, 2, 4])) // [1, 2, 3, 4]
18 | // console.log(insertionSort([-10, 1, 3, 8, -13, 32, 9, 5])) // [-13, -10, 1, 3, 5, 8, 9, 32]
19 |
20 |
21 | //----------------------------------------------------------------------------------
22 |
23 | //Approaches:
24 |
25 | /*
26 |
27 | 3 1 2 4 0
28 | i
29 | k
30 | j
31 | 0 1 2 3 4
32 |
33 | 1 2 3 4
34 |
35 | 0 1 2 3 4 5
36 |
37 | Time: O(N^2)
38 |
39 | */
40 |
41 | function insertionSort(array) {
42 | for (let i = 1; i < array.length; i++) {
43 | let key = array[i];
44 | // console.log("Key: ", key);
45 | let j = i - 1;
46 | // console.log("i:", i);
47 | // console.log("j:", j);
48 | while (j >= 0 && array[j] > key) {
49 | array[j + 1] = array[j];
50 | // console.log("array[j]:", array[j]);
51 | // console.log("array[j + 1]:", array[j + 1]);
52 | j = j - 1;
53 | // console.log("j:", j);
54 | }
55 | array[j + 1] = key;
56 | // console.log("j:", j);
57 | // console.log("array[j + 1]:", array[j + 1]);
58 | }
59 | // console.log("array:", array);
60 | return array;
61 | }
62 |
63 |
64 | /* Another Approach learned from Pair Programmer */
65 |
66 | /* Pair Learning Solution from Kedir using Java*/
67 | /*
68 | class Solution {
69 | public static void main(String[] args) {
70 | int[]input = new int[] {};
71 | insertionSort(input);
72 | System.out.println(Arrays.toString(input));
73 |
74 | }
75 |
76 | public static void insertionSort(int[]arr){
77 | if(arr.length<=1){
78 | return;
79 | }
80 | for(int i=0 ; i0 && arr[j] cannot begin with negative num
89 | negative num should not exist
90 |
91 |
92 |
93 |
94 | 1
95 | () = 1
96 |
97 | 1-1
98 |
99 | 2
100 | ()(), (()) = 2
101 | 1-1+1-1. 1+1-1-1
102 |
103 | 3
104 | ((())),()()(),(()()),(())(),()(()) = 5
105 |
106 |
107 |
108 |
109 |
110 | */
111 |
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/LowestCommonAncestor.js:
--------------------------------------------------------------------------------
1 | /* 07-03-22
2 | Q. Given a binary tree, find the lowest common ancestor of two given nodes in the tree and return its value.
3 |
4 | A node can be its own ancestor.
5 | Examples:
6 |
7 | Given a binary tree:
8 | 10
9 | / \
10 | 5 12
11 | / \ /
12 | 3 6 11
13 | For node1: 3, node2: 6 // returns 5
14 | For node1: 11, node2: 6 // returns 10
15 | [execution time limit] 4 seconds (js)
16 |
17 | [input] tree.integer root
18 |
19 | [input] integer val1
20 |
21 | [input] integer val2
22 |
23 | [output] integer
24 |
25 | lowest common ancestor
26 |
27 | post order tree traversal
28 |
29 | */
30 |
31 |
32 | //
33 | // Binary trees are already defined with this interface:
34 | class TreeNode {
35 | constructor(value, left = null, right = null) {
36 | this.value = value;
37 | this.left = left;
38 | this.right = right;
39 | }
40 | }
41 | function solution(root, val1, val2) {
42 |
43 | function dfs(node) {
44 | // console.log("node: ", node);
45 | //base case
46 | if (!node) {
47 | return null;
48 | }
49 | if (node.value === val1 || node.value === val2) {
50 | return node;
51 | }
52 | //recursive case
53 | let left = dfs(node.left); //5
54 | let right = dfs(node.right);
55 | // console.log("LEFT: ", left);
56 | // console.log("RIGHT: ", right);
57 |
58 | //merge case
59 | if (!left && !right) {//no val1 or val2 match found
60 | return null;
61 | }
62 | if (left && right) { //lowest common ancestor is found
63 | // console.log('common ancestor here: ', node);
64 | return node;
65 | }
66 | return left || right; //if one of them is found, return the one with the match
67 | //if left is null, return right, else return left
68 | }
69 | return dfs(root).value;
70 | }
71 |
72 | const tree1 = new TreeNode(10,
73 | new TreeNode(5,
74 | new TreeNode(3),
75 | new TreeNode(6)),
76 | new TreeNode(12,
77 | new TreeNode(11),
78 | null))
79 | console.log(solution(tree1, 3, 6)); //5
80 |
--------------------------------------------------------------------------------
/AlgoWorkout/Temi/05-10-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given a binary tree, return the deepest node (furthest away child).
3 |
4 | Examples
5 | . a
6 | . / \
7 | . b c
8 | . /
9 | .d.
10 | returns d
11 |
12 | equal depth in both right and left - return one of them
13 |
14 |
15 | Depth (global variable)
16 |
17 |
18 | Approach#1 (Better than Approach#2): DFS + Natural Stack (Depth = height of the stack) (top to down)
19 | Time: O(n) n = num of nodes in the tree
20 | Space: O(h) h = height of the tree (worst case) | best case: O(logh) for balanced tree
21 |
22 | DFS Approach
23 | create a Stack, greatestLength, deepestNode
24 | currentNode = root
25 | push the root into the stack
26 | loop while stack != null
27 | if there is a left node, push to the stack, currentNode = LeftNode
28 | stack.length > greatestLength ,
29 | greatestLength = stack.length
30 | update deepestNode to currentNode value
31 | else if there is a right, push to the stack, currentNode = RightNode
32 |
33 |
34 |
35 | Approach#2 (as the number of nodes increase, will quickly run out of memory): DFS + Recursive Stack (Depth = passed from function to function) callstacks
36 | Time: O(n)
37 | Space: O(h)
38 |
39 |
40 |
41 | Alternative Solution:
42 |
43 | Approach #3: BFS (width - Left to right)
44 | Queue (FIFO)
45 | The deepest node is the last node
46 | Time: O(n) n = num of nodes in the tree
47 | Space: O(w)
48 |
49 | /*
50 | BFS Approach
51 |
52 | 1. initialize a queue
53 | 2. loop while queue.length > 0
54 | 3. push left & right nodes into queue if they exist
55 | 4. return the last node queue[queue.length - 1]
56 |
57 | */
58 |
59 |
60 | // Function Signature
61 | class TreeNode {
62 | constructor(value = 0, leftChild = null, rightChild = null) {
63 | this.value = value;
64 | this.left = leftChild;
65 | this.right = rightChild;
66 | }
67 | }
68 |
69 |
70 | // function deepestNode(root)
71 |
72 |
73 |
74 | function BFS(root){
75 | const q = root ? [root] : []
76 |
77 | let deepest = null
78 | while(q.length > 0){
79 | let node = q.shift()
80 |
81 | node.left && q.push(node.left)
82 | node.right && q.push(node.right)
83 | }
84 | return deepest
85 | }
86 |
87 | let tree1 = new TreeNode('a', new TreeNode('b', new TreeNode('c', new TreeNode('d'))))
88 | console.log(BFS(tree1))
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/1_Accumulating/count.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q1. Given an unsorted linked list, count the number of elements (iteratively or recursively).
3 |
4 | Examples:
5 | • Given a linked list: 1 ➞ 4 ➞ 5 // returns 3
6 | • Given a linked list: 0 // returns 1
7 | */
8 |
9 | class ListNode {
10 | constructor(value = 0, next = null) {
11 | this.value = value
12 | this.next = next
13 | }
14 | }
15 |
16 | function count(head) {
17 | // Write your code here.
18 | }
19 |
20 | // Test Cases
21 | const LL1 = new ListNode(1, new ListNode(4, new ListNode(5)))
22 | console.log(count(null)) // 0
23 | console.log(count(LL1)) // 3
24 | console.log(count(new ListNode())) // 1
25 |
26 |
27 |
28 | //----------------------------------------------------------------------------------
29 |
30 | //Approaches:
31 |
32 | /*
33 | Higher Order Overview:
34 |
35 | Iterative:
36 | Declared a curr pointer and assigned it to the head of the linked list.
37 | While iterating through the linked list, increment the count until
38 | the pointer reaches the end of the linked list.
39 |
40 | */
41 |
42 | //Iterative Approach (uncomment below and see how it works in the console)
43 |
44 | function countIterative(head) {
45 | let curr = head;
46 | let count = 0;
47 | while (curr) {
48 | count++;
49 | curr = curr.next;
50 | }
51 | console.log("curr :", curr); // null
52 | console.log("head :", head); // the entire linked list
53 | return count;
54 | }
55 |
56 | //UNCOMMENT BELOW TO TEST:
57 | // const LL2 = new ListNode(1, new ListNode(4, new ListNode(5)))
58 | // console.log(countIterative(null)) // 0
59 | // console.log(countIterative(LL2)) // 3
60 | // console.log(countIterative(new ListNode())) // 1
61 |
62 |
63 | //Recursive Approach (uncomment below and see how it works in the console)
64 |
65 | function countRecursive(head) {
66 | if (!head) return 0;
67 | console.log("head :", head); //going through each node
68 | return 1 + countRecursive(head.next);
69 | }
70 |
71 | //UNCOMMENT BELOW:
72 | // const LL3 = new ListNode(1, new ListNode(4, new ListNode(5)))
73 | // console.log(countRecursive(null)) // 0
74 | // console.log(countRecursive(LL3)) // 3
75 | // console.log(countRecursive(new ListNode())) // 1
76 |
77 |
78 |
79 | /*
80 | Time Complexity (runtime): O(n)
81 |
82 | Space Complexity (memory): O(1)
83 |
84 | */
85 |
86 |
87 |
--------------------------------------------------------------------------------
/AlgoWorkout/Vinit/06-29-22.py:
--------------------------------------------------------------------------------
1 | '''
2 |
3 | Define a subsequence of a string s to be a list of characters from s such that the characters appear in the same order in the list and in s.
4 |
5 | For instance, for the string abcd, a, ab, and acd are valid subsequences, whereas db is not, since b comes before d in the original string.
6 |
7 | Given an input string, return all subsequences of the string.
8 |
9 | Example:
10 |
11 | getAllSubsequences("abc") == [
12 | "a",
13 | "b",
14 | "c",
15 | "ab",
16 | "ac",
17 | "bc",
18 | "abc",
19 | ]
20 |
21 | - imagine you have a magic function that sovles your problem for the N-1
22 | - what would you do with the output of said magic function to get to the answer for your N input
23 |
24 | magicFunction("bc") =>
25 |
26 | ['b', 'c', 'bc']
27 | ['ab', 'ac', 'abc']
28 | concat both together
29 |
30 | call self with 1, str.length
31 |
32 | the result from that call we want to append each el
33 | to the char we're on and concatenate the two arrays
34 |
35 | output size => 2^n
36 |
37 | time complexity: 2^N
38 | space complexity: N
39 | where N is the length of the input string
40 |
41 | all subsequences []
42 |
43 | getAllSubsequences('abc')
44 | getAllSubsequences('bc')
45 | getAllSubsequences('c')
46 |
47 | function(n)
48 | var = function(n-1)
49 | return var + 1
50 |
51 | include a
52 | include b
53 | include c => abc
54 | exclude c => ab
55 | exclude b
56 | include c => ac
57 | exclude c => a
58 |
59 | exclude a
60 | include b
61 | include c => bc
62 | exclude c => b
63 | exclude b
64 | include c => c
65 | exclude c => ''
66 |
67 | root
68 | yes a no a
69 | yes b no b yes b no b
70 | yes c no c yes c no c yes c no c yes c no c
71 |
72 |
73 |
74 | '''
75 |
76 | def getAllSubsequences(input):
77 | if len(input) == 1:
78 | return [input]
79 |
80 | result = [input[0]]
81 |
82 | for element in getAllSubsequences(input[1:]):
83 | result.append(element)
84 | result.append(input[0] + element)
85 |
86 | return result
87 |
88 | print(len(getAllSubsequences("abcdef")))
--------------------------------------------------------------------------------
/AlgoMockedInterview/AdvancedArray/numberOfIslands_practice.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
3 |
4 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
5 |
6 | Input: grid = [
7 | ["1","1","1","1","0"],
8 | ["1","1","0","1","0"],
9 | ["1","1","0","0","0"],
10 | ["0","0","0","0","0"]
11 | ]
12 | Output: 1
13 |
14 |
15 | Input: grid = [
16 | ["1","1","0","0","0"],
17 | ["1","1","0","0","0"],
18 | ["0","0","1","0","0"],
19 | ["0","0","0","1","1"]
20 | ]
21 | Output: 3
22 |
23 | */
24 |
25 | /*
26 | High level Understanding and Breaking down the problem in English USING DFS RECURSIVE APPROACH:
27 | - Iterate through the entire grid
28 | - If we encounter '1', we increment the counter by 1 since it is the first island we found
29 | - Then you want to explore how big this island is
30 | - You will then use DFS recursion method to search in four different directions for all the lands assoicated with the island (top, down, left, and right)
31 | - Make a mark once we have visited the land (instead of creating a separate visited variable, you can use flip it to '0' as an indicator that the land is already visited - based on this problem, we do not need to keep track of how how visited land)
32 | - return the number of islands (based on the counter)
33 | ___
34 |
35 | Time: O(r * c) number of elements on each row and each column of the input array
36 | Space: O(r * c) Using recursive call stack will take linear space for both visited rows and columns
37 |
38 | */
39 |
40 | var numIslands = function(grid) {
41 | let count = 0;
42 | let rowLen = grid.length;
43 | let colLen = grid[0].length;
44 |
45 | function dfs(row, col, grid) {
46 | if (row < 0 || col < 0 || row >= rowLen || col >= colLen || grid[row][col] === '0') {
47 | return;
48 | }
49 | grid[row][col] = '0'
50 | dfs(row, col + 1, grid);
51 | dfs(row + 1, col, grid);
52 | dfs(row, col - 1, grid);
53 | dfs(row - 1, col, grid);
54 | }
55 | for (let i = 0; i < rowLen; i++) {
56 | for (let j = 0; j < colLen; j++) {
57 | if (grid[i][j] === '1') {
58 | count++;
59 | dfs(i, j, grid);
60 | }
61 |
62 | }
63 | }
64 | return count;
65 | };
--------------------------------------------------------------------------------
/AlgoWorkout/Vinit/05-04-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | Stack Type Problem (looks like easy but actually really hard!!)
3 |
4 | Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature.
5 |
6 | Example:
7 |
8 | Given the list of temperatures T = [73, 74, 75, 71, 69, 72], your output should be [1, 1, 0, 2, 1, 0].
9 |
10 |
11 | outer loop goes through each temperature
12 | inner loop counts while there isnt a greater temperature
13 | increments a counter
14 |
15 |
16 | [74, 72, 69, 68, 70]
17 | 2 1 0
18 |
19 |
20 | Create a stack of array indices. Iterate through the array.
21 | At each position, compare two values: the value at current index we are processing in the array, and the value at the index at the top of the stack. If the current element is larger, set the value in the answers array as the difference between the current index in the last index of the stack. Repeat this until the current value is larger than the value at last index of the stack. Append the current index to the stack and move on to the next element in the array.
22 |
23 | [73, 74, 75, 71, 69, 72]
24 | */
25 |
26 | // stack: [2, 5]
27 | // result: [1, 1, _, 2, 1]
28 | // i: 6
29 | // curItem: 72
30 |
31 | // while(stack.length > 0 && 75 < 72)
32 | // stackTop: 3
33 | // result[1] => 2 - 1
34 |
35 | function findWarmerV2(temps) {
36 | const stack = [];
37 | const result = new Array(temps.length).fill(0);
38 |
39 | for (let i = 0; i < temps.length; i++) {
40 | const curItem = temps[i];
41 |
42 | while(stack.length > 0 && temps[stack[stack.length - 1]] < curItem) {
43 | const stackTop = stack[stack.length - 1];
44 | result[stackTop] = i - stackTop;
45 | stack.pop();
46 | }
47 | stack.push(i);
48 | }
49 |
50 | return result;
51 | }
52 |
53 |
54 | function findWarmer(temps){
55 | let result = [];
56 |
57 | for (let i = 0; i < temps.length; i++){
58 | const curTemp = temps[i];
59 | let j = i+1;
60 |
61 | while (curTemp >= temps[j] && j < temps.length){
62 | j++
63 | }
64 |
65 | result.push(j >= temps.length ? 0 : j-i);
66 | }
67 |
68 | return result;
69 | }
70 |
71 | // i: 2
72 | // curTemp: 75
73 | // j: 6
74 |
75 | // while (75 >= 72 && j < 6)
76 |
77 |
78 | // result: [1, 1, 0]
79 |
80 | console.log(findWarmerV2([73, 74, 75, 71, 69, 72])); // [1, 1, 0, 2, 1, 0]
--------------------------------------------------------------------------------
/1-on-1-w-Mentor-Fellow/TriePerspective_w_Mitch.js:
--------------------------------------------------------------------------------
1 | /*
2 | This is a super great session to look at how Mitch visualize the Trie data structure
3 |
4 | It is always great to listen to a different perspective on the problem. It can be hard to see it clearly when doing it by myself
5 |
6 | But once I hear others speaking through the problem, it helps me to be able to see things in their perspectives as well as in a second-person perspective
7 |
8 |
9 | Build a Trie class. Insert new strings and Search if strings exist.
10 | */
11 |
12 | // const map = new Map();
13 | // map.set('c', new Map());
14 | // console.log({map})
15 | // let children = map.get('c');
16 | // // console.log({children})
17 | // children.set('a', new Map());
18 | // children = children.get('a')
19 | // console.log({map})
20 | // children.set('t', new Map());
21 | // console.log({children})
22 |
23 |
24 |
25 | class Trie {
26 | constructor() {
27 | map = new Map();
28 | }
29 |
30 | add(word) {
31 | // for each char we will
32 | // first you have to check if the chars exist map
33 | // no:
34 | // assign the map to chars children
35 | // yes:
36 | // we will add char to our to curr map
37 | // assign the map to curr chars children
38 | }
39 |
40 | lookup(word) {
41 | //do something
42 | }
43 | }
44 |
45 |
46 | // const trie = new Trie()
47 | // trie.add("cat")
48 | // trie.lookup("cat") == true
49 | // trie.lookup("dog") == false
50 | // trie.add("dog")
51 | // trie.lookup("dog") == true
52 |
53 |
54 | /*
55 | input: cat
56 | add(cat)
57 | cat
58 | ^
59 |
60 | lookup(cat)
61 | cat
62 | ^
63 | return true
64 |
65 | add(cats)
66 | cats
67 | ^
68 |
69 | add(tats)
70 | tats
71 | ^
72 |
73 | add(tap)
74 | tap
75 | ^
76 |
77 | search(tap)
78 | tap
79 | ^
80 |
81 | tree: {
82 | t: {
83 | a : {
84 | t: {
85 | s: {}
86 | }
87 | p: {endWord: true}
88 | }
89 | }
90 | c: {
91 | a: {
92 | t: {
93 | s: {endWord: true}
94 | }
95 | }
96 | }
97 | }
98 |
99 |
100 | c t
101 | / \
102 | a a
103 | / / \
104 | t p t
105 | / \
106 | s s
107 | */
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/PairLearning/KadaneAlgowMaggie.js:
--------------------------------------------------------------------------------
1 | // PROBLEM
2 | // Given an array of integers, return maximum subarray sum.
3 | // A subarray is any contiguous set of numbers
4 |
5 | // Function Signature:
6 | // func maxSubarraySum(input: [Int]) -> Int
7 |
8 | // Examples:
9 | // [2, 2, -3, 6, -10, 4] => 7 //[2, 2, -3, 6]
10 | // [] => 0
11 | // [1] => 1
12 | // [-2, 1] => 1
13 | // [-1, -2, -3] => 0 // -1
14 |
15 | /*
16 | Approaches:
17 | #1:
18 | maxSum = -Infinity
19 | nested loop
20 | iterate through the input and adds the values as it iterates through each index
21 | sum = 2 + 2 + (-3)
22 | if (sum > maxSum) maxSum = sum;
23 | Time: O(N^2) => N = numbers of elements of the input array
24 | Space: O(1)
25 |
26 | #2: Kadane's Algo
27 |
28 | [2, 2, -3, 6, -10, 4]
29 | ^
30 | iterate through the input array once
31 | max end sum = max(num, max end sum + num). -3, 1
32 | max so far = max (max end sum, max so far)
33 |
34 | return max so far
35 |
36 | Time: O(N) => N = numbers of elements of the input array
37 | Space: O(1)
38 |
39 | */
40 |
41 | function maxSubarraySum(input) {
42 | let maxSum = input.length < 1 ? 0 : -Infinity;
43 | for (let i = 0; i < input.length - 1; i++) {
44 | let sum = input[i];
45 | for (let j = i + 1; j < input.length; j++) {
46 | sum += input[j];
47 | if (sum > maxSum) maxSum = Math.max(input[j], maxSum);
48 | }
49 | }
50 | return maxSum > 0 ? maxSum : input.length === 1 ? input[0] : 0;
51 | }
52 |
53 | //FORMATION SOLUTION
54 | // const maxSubarraySum = (nums) => {
55 | // let currentSum = 0;
56 | // let globalSum = nums[0];
57 |
58 | // for (const num of nums) {
59 | // currentSum = Math.max(num, currentSum + num);
60 | // globalSum = Math.max(globalSum, currentSum);
61 | // }
62 |
63 | // return globalSum;
64 | // };
65 |
66 | //my attempt failed for 2 elements array or 1 element array
67 |
68 | console.log(maxSubarraySum([]), 0); //edge case (empty case)
69 | console.log(maxSubarraySum([2, 2, -3, 6, -10, 4]), 7);
70 | console.log(maxSubarraySum([1, 2, 3] ), 6);
71 | console.log(maxSubarraySum([-1, -2, -3]), -1); //edge case (all negative numbers)
72 |
73 | console.log("Don't pass yet")
74 | console.log(maxSubarraySum([1]), 1); //edge case (empty case);
75 | console.log(maxSubarraySum([3, 4, -6, 7, 8, -18, 100]), 100); //edge case (empty case)
76 | console.log(maxSubarraySum([-2, 1]), 1); //edge case (empty case);
77 | console.log(maxSubarraySum([-10]), -10); //edge case (empty case);
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/2_Finding_NoPointerNeeded/findElem.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a sorted linked list of unique integers, check if the list contains an element with a target value.
3 |
4 | Examples:
5 | • Given a linked list: 2 ➞ 3 ➞ 5, target: 2 // returns True
6 | • Given a linked list: 2 ➞ 3 ➞ 5, target: 4 // returns False
7 |
8 | */
9 |
10 | class ListNode {
11 | constructor(value = 0, next = null) {
12 | this.value = value
13 | this.next = next
14 | }
15 | }
16 |
17 | function search(head, target) {
18 |
19 | }
20 |
21 | // Test Cases
22 | const LL1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(5, new ListNode(6, new ListNode(7, new ListNode(10)))))))
23 | console.log(search(null, 1)) // false
24 | console.log(search(LL1, 2)) // true
25 | console.log(search(LL1, 4)) // false
26 | console.log(search(LL1, -1)) // false
27 | console.log(search(LL1, 10)) // true
28 | console.log(search(LL1, 11)) // false
29 |
30 | //----------------------------------------------------------------------------------
31 |
32 | //Approaches:
33 |
34 | /*
35 | Higher Order Overview:
36 | 1. Create a curr pointer -> let curr = head;
37 | 2. iterate through the entire curr linked list
38 | 3. if any of the curr.value is found to equal to the target value, return true
39 | 4. keep moving to the next node
40 | 5. return false when no matching curr.value found
41 |
42 | Time: O(n)
43 | Space: O(1)
44 |
45 | */
46 |
47 |
48 | function searchIterative(head, target) {
49 |
50 | //Better Approach - no pointer is needed and if(!head) condition is redundant and can be removed
51 | while (head) { //break the loop when head is null
52 | if (head.value === target) return true;
53 | head = head.next; //move to the next node
54 | }
55 | return false;
56 |
57 | //Another Approach - use a curr pointer
58 | // if (!head) return false;
59 | // let curr = head;
60 | // while (curr) {
61 | // if (curr.value === target) return true;
62 | // curr = curr.next;
63 | // }
64 | // return false;
65 | }
66 |
67 | // Test Cases
68 | const LL2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(5, new ListNode(6, new ListNode(7, new ListNode(10)))))))
69 | console.log(searchIterative(null, 1)) // false
70 | console.log(searchIterative(LL2, 2)) // true
71 | console.log(searchIterative(LL2, 4)) // false
72 | console.log(searchIterative(LL2, -1)) // false
73 | console.log(searchIterative(LL2, 10)) // true
74 | console.log(searchIterative(LL2, 11)) // false
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/Searching/ShiftedBinarySearch.js:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | Learn Strength Algo: Shifted Binary Search
4 |
5 | Q: What is Binary Search?
6 | Q: How to detect which side is ordered?
7 |
8 | */
9 |
10 | /*
11 | Visualization
12 | 3 4 5 1 2
13 | m
14 | l h
15 |
16 | m: 5
17 | l: 3
18 | h: 2
19 |
20 | target 1
21 |
22 | T: O(logn)
23 | S: O(1)
24 | */
25 |
26 | //Attempt # 1
27 |
28 | function shiftedBinarySearch(array, target) {
29 | let low = 0; //index
30 | let high = array.length - 1; //inclusive index
31 | while (low <= high){
32 | let mid = Math.floor((high+low)/2);
33 | if (array[mid] === target) return mid;
34 | if (array[low] <= array[mid]) {// on the LEFT SIDE
35 | if (array[low] <= target && target < array[mid]) { //found on the left
36 | high = mid - 1;
37 | }else { //found on the right
38 | low = mid + 1;
39 | }
40 | }else { // on the RIGHT SIDE
41 | if (array[mid] < target && target <= array[high]) { //on the right
42 | low = mid + 1;
43 | }else { //on the left
44 | high = mid - 1;
45 | }
46 | }
47 | }
48 | return -1;
49 | }
50 |
51 |
52 | /*
53 | Progress Notes:
54 |
55 | 10min: watch Formation video and understand the problem
56 |
57 | 15min: coding the problem (issues ~ not entirely how to solve ~ since I have failed some test cases)
58 | (specifically in Algo Expert I failed the test cases#6 and other 3 more cases)
59 |
60 | 15min: watch Algo Expert video, review hints, understand the recursive approach on the problem and rewatched the Formation video
61 |
62 | 10min: resolve the issue from my first 15 mins approach and successfully pass all the test cases
63 |
64 |
65 | Plain English:
66 | The shifted binary search is basically helping us to find the specific item
67 | by dividing up the data depends on if the target item is locating in the smaller or larger area
68 | of the middle point.
69 | Divide the playground into half.
70 | Lets take a look when the low pointer value (left pointer value) is less than or equal to the middle pointer value.
71 | In this situation, it means that potentially the left side is ordered, and the right side is not ordered
72 |
73 | If the target is smaller than or equal to the middle pointer value, and it is larger than the low pointer value, adjust the high pointer
74 | else adjust the low pointer
75 |
76 | If the lower pointer value is larger than or equal to the middle pointer value:
77 | this means potentially the left side is not ordered and the right side is ordered
78 |
79 | (similar situation on this end)
80 | */
81 |
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/5_Removing/removeAllTarget.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a linked list and a target integer, remove all nodes with the value target.
3 |
4 | Examples:
5 | • Given a linked list: 4 ➞ 2 ➞ 3 ➞ 2 ➞ 2, target: 2 // returns 4 ➞ 3
6 | • Given a linked list: 4, target: 4 // returns an empty list
7 | */
8 |
9 | class ListNode {
10 | constructor(value = 0, next = null) {
11 | this.value = value
12 | this.next = next
13 | }
14 | }
15 |
16 | function arrayify(head) {
17 | let ptr = head
18 | var array = []
19 | while (ptr != null) {
20 | array.push(ptr.value)
21 | ptr = ptr.next
22 | }
23 | return array
24 | }
25 |
26 | function remove(node, target) {
27 |
28 | }
29 |
30 | // Test Cases
31 | let LL1 = new ListNode(4, new ListNode(2, new ListNode(1, new ListNode(1, new ListNode(3, new ListNode(2, new ListNode(2)))))))
32 | let LL2 = remove(null, 1);
33 | console.log(arrayify(LL2)) // []
34 | LL1 = remove(LL1, 1);
35 | console.log(arrayify(LL1)) // [4, 2, 3, 2, 2]
36 | LL1 = remove(LL1, 2);
37 | console.log(arrayify(LL1)) // [4, 3]
38 | LL1 = remove(LL1, 3);
39 | console.log(arrayify(LL1)) // [4]
40 | LL1 = remove(LL1, 4);
41 | console.log(arrayify(LL1)) // []
42 |
43 | //----------------------------------------------------------------------------------
44 |
45 | //Approaches:
46 |
47 | //Iterative Approach (uncomment below and see how it works in the console)
48 |
49 | function removeInterative(node, target) {
50 | let sentinel = new ListNode(0);
51 | sentinel.next = node;
52 | let curr = sentinel;
53 |
54 | while(curr.next) {
55 | if (curr.next.value === target) { //if the next node value is equal to the target
56 | curr.next = curr.next.next; //remove the next node value, and move the next.next node value up
57 | }else { //QUESTION: it is crucial to have 'else' here, why it can be an issue if this else is removed??
58 | curr = curr.next;
59 | }
60 | }
61 | //console.log(sentinel);
62 | return sentinel.next;
63 | }
64 |
65 | // Test Cases
66 | let LL3 = new ListNode(4, new ListNode(2, new ListNode(1, new ListNode(1, new ListNode(3, new ListNode(2, new ListNode(2)))))))
67 | let LL4 = removeInterative(null, 1);
68 | console.log(arrayify(LL4)) // []
69 | LL3 = removeInterative(LL3, 1);
70 | console.log(arrayify(LL3)) // [4, 2, 3, 2, 2]
71 | LL3 = removeInterative(LL3, 2);
72 | console.log(arrayify(LL3)) // [4, 3]
73 | LL3 = removeInterative(LL3, 3);
74 | console.log(arrayify(LL3)) // [4]
75 | LL3 = removeInterative(LL3, 4);
76 | console.log(arrayify(LL3)) // []
--------------------------------------------------------------------------------
/AlgoMarathon/BinaryTree/PairLearning/README.md:
--------------------------------------------------------------------------------
1 | # Pair Learning in Algo Marathon
2 |
3 | ## Binh Hua (05/12/22)
4 |
5 | First time working with Binh to go through this pair learning session.
6 |
7 | We went over the [Level Order Traversal]() problem. A medium Leetcode problem.
8 |
9 | **Reflection**
10 | - Really like the enthusiam of Binh when going through this problem. She learns new approach and applies immediately and this is what I think I learn the most from her.
11 |
12 |
13 | ## Angel (05/23/22)
14 |
15 | We already had several sessions together and I really like to pair learning Angel since she is always able to pinpoint what I missed in my implementation on a problem. And we always have different perspectives. That is why it is interesting to work with her!
16 |
17 | We went over the [BST to Doubly Linked List In-Order Traversal]() problem using recursive. A medium leetcode problem.
18 |
19 | Angel shared with me this resouce on Doubly Linked List: https://www.geeksforgeeks.org/doubly-linked-list/
20 |
21 | I have found the similar problem on Leetcode [here](https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/)
22 |
23 | Great video walkthrough of this problem [here](https://www.youtube.com/watch?v=zy7I5wcwfh4)
24 |
25 | **Reflection**
26 | - Angel is a great host since she is able to ask questions to guide me to go over the part that I may have missed during my implementation. I totally forgot to set head to the first node, which I quickly mentioned during the pseudocode but did not write it down so I missed it entirely until Angel asked me questions and made me realize the problem I made. I like the fact that she did not give me an answer and just ask me questions to let me solve them by myself.
27 |
28 | An additional possible approach to the problem: try to solve it iteratively… (:
29 |
30 | ## Jiyoon (06/10/22) - outside of Formation schedule
31 |
32 | **Reflection & Takeaways**
33 | - Learning backtracking on powerset is really fun! I have learned a ton especially how Jiyoon explained the problem and visualized it step-by step - especially how she would use a tree structure to help her to visualize the backtracking array problem.
34 | - Biggest suggestion from Jiyoon on my performance and understanding on the problem is I still need to practice more to know how to fit `DFS on Array structure`, how to create a base case for a backtracking array problem.
35 | - Biggest take away on backtracking problem is asking `add/take or not add/take to the result`.
36 |
37 |
38 |
39 | ...
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/isMonotonicArray.js:
--------------------------------------------------------------------------------
1 | /*
2 | An array is monotonic if it is either monotone increasing or monotone decreasing.
3 |
4 | An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
5 |
6 | Given an integer array nums, return true if the given array is monotonic, or false otherwise.
7 |
8 |
9 |
10 | Example 1:
11 |
12 | Input: nums = [1,2,2,3]
13 | Output: true
14 | Example 2:
15 |
16 | Input: nums = [6,5,4,4]
17 | Output: true
18 | Example 3:
19 |
20 | Input: nums = [1,3,2]
21 | Output: false
22 |
23 | */
24 |
25 |
26 | //ATTEMPT #1: 05/13/22
27 |
28 | /*
29 | [1,2,2,3]
30 | i
31 |
32 | increasing: true
33 | decreasing: false
34 |
35 | output: true || false ===> true
36 |
37 |
38 | [6,5,4,4]
39 | i
40 |
41 | increasing: false
42 | decreasing: true
43 |
44 | output: false || true ===> true
45 |
46 |
47 | [1,3,2]
48 | i
49 |
50 | increasing: false
51 | decreasing: false
52 |
53 | output: false || false ===> false
54 |
55 | */
56 | var isMonotonic = function(nums) {
57 | //FORMATION SOLUTION:
58 | //bitwise AND assignment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment
59 | let dec = true;
60 | let inc = true; //1
61 |
62 | for (let i = 1; i < nums.length; i++) {
63 | dec &= nums[i-1] >= nums[i]; //0
64 | inc &= nums[i-1] <= nums[i]; //1
65 | console.log(dec, inc)
66 | }
67 | console.log("out: ", dec, inc)
68 | return dec || inc; //0 = false, 1 = true
69 |
70 | //LEETCODE SOLUTION: easier to understand + cleaner solution - using one pass only
71 | // let increasing = true, decreasing = true;
72 | // for (let i = 0; i < nums.length - 1; ++i) {
73 | // if (nums[i] > nums[i+1]) increasing = false;
74 | // if (nums[i] < nums[i+1]) decreasing = false;
75 | // console.log("inside loop: ", increasing, decreasing);
76 | // }
77 | // console.log("outside loop: ", increasing, decreasing);
78 | // return increasing || decreasing;
79 |
80 | //My first approach: repetitive when doing it in two pass
81 | // if (nums.length < 2) return true; //removed in optimal solution
82 | // if (nums[0] <= nums[1]) {
83 | // for (let i = 0; i < nums.length - 1; i++) {
84 | // if (nums[i] > nums[i + 1] ) return false;
85 | // }
86 | // }
87 | // if (nums[0] >= nums[1]) {
88 | // for (let i = 0; i < nums.length - 1; i++) {
89 | // if (nums[i] < nums[i + 1]) return false;
90 | // }
91 | // }
92 | // return true;
93 | };
94 |
--------------------------------------------------------------------------------
/MockedBehavioralPhoneScreen/README.md:
--------------------------------------------------------------------------------
1 | # Mocked Phone Screen Takeaways
2 |
3 | ## Mock Interview w Lakisha (06-17-22)
4 |
5 | Takeaways:
6 | - Question on "Tell me about yourself"
7 | - quickly summarize your resume and highlight pieces of experience
8 | - highlight your technical and non-technical skillsets
9 | - highlight your area of interests
10 | - summarize your work experience so it is transferrable to your new job
11 |
12 | - Thinking of the "word" you use and say in an interview:
13 | - ie, work-life balance can be rephrased to "life-work" balance
14 | - it shows what you value most from the way you phrase
15 |
16 | - When describing the project you are proud of - make sure to highlight why?
17 | - Why you are proud of the project?
18 | - What does this accomplishment teels you as an exployee?
19 | - What do you want them to know about you?
20 |
21 | - Question on "Value"
22 | - what does the company value most <- highlight this in your answer
23 | - Talk about your values and how it is in relation to or align with the employer
24 |
25 | - Question on "Failure"
26 | - What are your `specific` takeaways
27 | - Be mindful and Know your audience:
28 | - Find out more about your interviewer if you can
29 | - If they have no coding background, it is crucial to not be using too many technical jargons
30 |
31 | - Question on "Deadline"
32 | - Quick summary of the step by step key points on how to handle the scenario
33 | - There is no need to be too detailed and description (since it is cruical to be mindful of the time spent on each question)
34 |
35 |
36 | - Question on "Weakness"
37 | - Describe the challenge and show what you have done to overcome the weakness
38 | - The weakness might still be there, but you have found a way for you to handle that weakness everytime it comes up!
39 |
40 | - You can find out more about the company culture through different platforms ie, `levels.fyi` or `Blind`
41 |
42 | - Even though you may have successfully gone through all interviews, there are still scenarios that you will not get the job, and it can be due to headcount, etc. There is no guarantee. As a result, it is crucial to remember to always `do your best each time` and have an `optimistic mindset` to keep moving forward until you finally find the ONE role.
43 |
44 | ## Mock Interview w Susan (06-19-22)
45 |
46 | Takeaways:
47 | - Amazon behavior questions can pretty intensive (can be unexpected)
48 | - Prepare approaches to multiple questions (which can prepare you to navigate through harder problems)
49 | - Time management is key -- Always keep track of the time on how long it took you to answer the question. You want to get through as many questions as possible. Try not to spend too long on a problem.
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/sum.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a binary tree, sum all elements in the tree.
3 |
4 | Example:
5 | • Given a binary tree:
6 | 1
7 | / \
8 | 7 3
9 | / \
10 | 4 5
11 | returns 20
12 | */
13 |
14 | class TreeNode {
15 | constructor(value = 0, leftChild = null, rightChild = null) {
16 | this.value = value
17 | this.left = leftChild
18 | this.right = rightChild
19 | }
20 | }
21 |
22 | function sumBT(root) {
23 |
24 | }
25 |
26 | // Test Cases
27 | console.log(sumBT(null)) // 0
28 | console.log(sumBT(new TreeNode(1, new TreeNode(2), new TreeNode(3)))) // 6
29 | console.log(sumBT(new TreeNode(1))) // 1
30 |
31 | //----------------------------------------------------------------------------------
32 |
33 | //Approaches:
34 |
35 |
36 | function sumBT(root) {
37 | //iterative (DFS Approach)
38 | if (!root) return 0;
39 | let sum = 0;
40 | let stack = root ? [root] : [];
41 | while (stack.length > 0) {
42 | let node = stack.pop();
43 | sum += node.value;
44 | if (node.left) stack.push(node.left);
45 | if (node.right) stack.push(node.right);
46 | }
47 | return sum;
48 |
49 | //Recursive
50 | // if (!root) return 0;
51 | // let sum = 0;
52 | // sum += root.value;
53 | // return sum + sumBT(root.left) + sumBT(root.right);
54 | }
55 |
56 |
57 | //----------------------------------------------------------------------------------
58 |
59 | //OTHER SIMILAR PROBLEMS:
60 |
61 | /*
62 | Algo: Sum all even elements in a binary tree (iterative & Recursive)
63 | */
64 |
65 | const sumEvenTree = (root) => {
66 | //Iterative Approach
67 | if (!root) return null;
68 | let queue = [root];
69 | let sum = 0;
70 | while (queue.length > 0) {
71 | let node = queue.pop();
72 | if (node.value % 2 === 0) sum += node.value;
73 | if (node.left) queue.push(node.left);
74 | if (node.right) queue.push(node.right);
75 | }
76 | return sum;
77 |
78 | //Recursive Approach
79 | // if (!root) return 0;
80 | // let sum = 0;
81 | // if (root.value % 2 === 0) sum += root.value;
82 | // return sum + sumEvenTree(root.left) + sumEvenTree(root.right);
83 | }
84 |
85 | const tree1 = new TreeNode(2, new TreeNode(3, new TreeNode(6)), new TreeNode(4));
86 | const tree2 = new TreeNode();
87 | const tree3 = new TreeNode(1);
88 | const tree4 = new TreeNode(null);
89 | const tree5 = new TreeNode(2, new TreeNode(6));
90 | const tree6 = new TreeNode(1, new TreeNode(3), new TreeNode(5));
91 | console.log(sumEvenTree(tree1), 12);
92 | console.log(sumEvenTree(tree2), 0);
93 | console.log(sumEvenTree(tree3), 0);
94 | console.log(sumEvenTree(tree4), 0);
95 | console.log(sumEvenTree(tree5), 8);
96 | console.log(sumEvenTree(tree6), 0);
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/RobotCleanRoomwDanielTomko_06-29-22.js:
--------------------------------------------------------------------------------
1 | /**
2 | * // This is the robot's control interface.
3 | * // You should not implement it, or speculate about its implementation
4 | * function Robot() {
5 | * // Returns true if the cell in front is open and robot moves into the cell.
6 | * // Returns false if the cell in front is blocked and robot stays in the current cell.
7 | * @return {boolean}
8 | * this.move = function() {
9 | * ...
10 | * };
11 | *
12 | * // Robot will stay in the same cell after calling turnLeft/turnRight.
13 | * // Each turn will be 90 degrees.
14 | * @return {void}
15 | * this.turnLeft = function() {
16 | * ...
17 | * };
18 | *
19 | * // Robot will stay in the same cell after calling turnLeft/turnRight.
20 | * // Each turn will be 90 degrees.
21 | * @return {void}
22 | * this.turnRight = function() {
23 | * ...
24 | * };
25 | *
26 | * // Clean the current cell.
27 | * @return {void}
28 | * this.clean = function() {
29 | * ...
30 | * };
31 | * };
32 | */
33 |
34 | /*
35 | ooooo
36 | xxoxx
37 | ooooo
38 | */
39 |
40 | function cleanRoom(robot) {
41 | const key = (x, y) => [x, y].join(',');
42 | const visited = {};
43 | let direction = 0; // 0 up, 1 right, 2 down, 3 left
44 | const deltas = [
45 | [0, 1] // up
46 | [1, 0], // right
47 | [0, -1], // down
48 | [-1, 0], // left
49 | ];
50 |
51 | function changeDirection(newDir) {
52 | newDir = newDir % 4;
53 | while (direction !== newDir) {
54 | robot.turnRight();
55 | direction = (direction + 1) % 4;
56 | }
57 | }
58 |
59 |
60 | function cleanPosition(x, y) {
61 | // base case (gonna deal with this below)
62 | robot.clean();
63 | visited[key(x, y)] = true;
64 |
65 | // loop through possible adjacent positions that are not yet visited
66 | for (let i = 0; i < deltas.length; i++) {
67 | // compute new possible position
68 | const [dx, dy] = deltas[i];
69 | const newX = x + dx;
70 | const newY = y + dy;
71 |
72 | // if the new position is visited, continue (don't visit)
73 | if (visited[key(newX, newY)]) continue;
74 | // try and move to the new position (turn?)
75 | changeDirection(i);
76 |
77 | // if move was successful
78 | if (robot.move()) {
79 | cleanPosition(newX, newY);
80 | // move back
81 | changeDirection((i + 2) % 4);
82 | robot.move();
83 | } else {
84 | // mark this spot as visited
85 | visited[key(newX, newY)] = true;
86 | }
87 | }
88 | }
89 |
90 | cleanPosition(0, 0);
91 | }
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/TreetoLL&BacktrackingwDaniel_06-23-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | Password Generator
3 | abc, 2
4 | aa
5 | ab
6 | ba
7 | bb
8 | bc
9 | cc
10 | ca
11 | cb
12 | */
13 |
14 | function passwordGenerator(letters, length) {
15 | const stack = [];
16 | const passwords = [];
17 |
18 | function addOneLetter() {
19 | // base case
20 | if (stack.length === length) {
21 | passwords.push(stack.join(''));
22 | return;
23 | }
24 |
25 | // traverse all branches
26 | for (let i = 0; i < letters.length; i++) {
27 | stack.push(letters[i]); // O(1)
28 | addOneLetter();
29 | stack.pop(); // O(1)
30 | }
31 | }
32 |
33 | addOneLetter();
34 |
35 | return passwords;
36 | }
37 |
38 | console.log(passwordGenerator("abc", 2));
39 | console.log(passwordGenerator("abc", 7));
40 |
41 |
42 | function heightOfTree(root) {
43 | if (!root) return 0;
44 |
45 | const leftHeight = heightOfTree(root.left);
46 | const rightHeight = heightOfTree(root.right);
47 |
48 | const heightAtThisNode = Math.max(leftHeight, rightHeight) + 1;
49 |
50 | return heightAtThisNode;
51 | }
52 |
53 | function sumOfTreeValues(root) {
54 | if (!root) return 0;
55 |
56 | const leftSum = sumOfTreeValues(root.left);
57 | const rightSum = sumOfTreeValues(root.right);
58 |
59 | return leftSum + rightSum + root.value;
60 | }
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | /*
73 |
74 | Convert Binary Tree to Sorted Doubly Linked List
75 |
76 | 5
77 | 3 9
78 | 1 4 13
79 | 10 15
80 |
81 | LeftSubTreeAsList 5 RightSubTreeAsList
82 | 1 3 4 9 10 13 15
83 | */
84 |
85 | class Node {
86 | constructor(value, left = null, right = null) {
87 | this.value = value;
88 | this.left = left;
89 | this.right = right;
90 | }
91 | }
92 |
93 | function tree2list(root, listTail = null) {
94 | if (!root) return listTail;
95 |
96 | // First, we're looking for the last node, so we're going
97 | // as far right as we can.
98 | if (root.right) {
99 | listTail = tree2list(root.right, listTail);
100 | }
101 |
102 | // If there is no right node, then this is the last one
103 | // in the in-order traversal, so prepend that to the tail
104 | // of the list and that node is now the head.
105 | let listHead = root;
106 | listHead.right = listTail;
107 | if (listTail) {
108 | listTail.left = listHead;
109 | }
110 |
111 | // Now look at the left subtree and pass in the list
112 | // we've created so far.
113 | if (root.left) {
114 | listHead = tree2list(root.left, listHead);
115 | }
116 |
117 | // Return the list as we've built it up to this point.
118 | return listHead;
119 | }
120 |
121 |
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/AlgoMarathonwDaniel_06-02-22.js:
--------------------------------------------------------------------------------
1 |
2 | const array = [2, 7, 1, 45, 23, 84, 65];
3 |
4 | function findMaxRecursive(array) {
5 |
6 | function helper(array, start) {
7 | // base case
8 | if (start === array.length - 1) {
9 | return array[start];
10 | }
11 |
12 | // do some work?
13 |
14 | // recursive call
15 | const theMaxOfTheRest = helper(array, start + 1);
16 |
17 | // do some work?
18 |
19 | // merge step
20 | return Math.max(array[start], theMaxOfTheRest);
21 | }
22 |
23 | if (array.length === 0) {
24 | return NaN; // Do something reasonable
25 | }
26 |
27 | return helper(array, 0);
28 | }
29 |
30 |
31 | // 1
32 | // 2 3
33 | // 4 5 6 7
34 |
35 | // 1
36 | // 3 2
37 | // 7 6 5 4
38 |
39 | // 1
40 | // 2 3
41 |
42 |
43 | function treeFlip(root) {
44 | // base case
45 | if (root === null) {
46 | return null;
47 | }
48 |
49 | // do some work
50 | const temp = root.right;
51 | root.right = root.left;
52 | root.left = temp;
53 |
54 | // recursive calls
55 | treeFlip(root.left);
56 | treeFlip(root.right);
57 |
58 | // merge? Nope
59 |
60 | return root;
61 | }
62 |
63 | /*
64 | Q. Given a non-empty binary tree, find the maximum path sum.
65 |
66 | A path is any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
67 |
68 | Given a tree:
69 | 1
70 | / \
71 | 2 3
72 | /
73 | -1
74 | // returns 6 (1 + 2 + 3)
75 | */
76 |
77 | // find max path from root to any leaf node
78 | function maxPathSum(root) {
79 | // base case
80 | if (!root) {
81 | return 0;
82 | }
83 | // recursive calls
84 | const left = maxPathSum(root.left);
85 | const right = maxPathSum(root.right);
86 |
87 | // merge
88 | const maxSubTreePath = Math.max(left, right);
89 |
90 | // return something
91 | return maxSubTreePath + root.value;
92 | }
93 |
94 | /**
95 | *
96 |
97 | Original intervals:
98 | --------
99 | ---------
100 | ----------
101 | Want to insert:
102 | --
103 | ---
104 | ---
105 | ----------
106 | ---------------------
107 | */
108 |
109 | function mergeIntervals(original, newInterval) {
110 | const result = [];
111 |
112 | for (let i = 0; i < original; i++) {
113 | const interval = original[i];
114 |
115 | // Do we want to merge interval and newInterval?
116 | // if so, update newInterval
117 | // else
118 | // result.push(interval);
119 | }
120 |
121 | return result;
122 | }
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/BinarySearchTree/insertElem.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a binary search tree and a target element's value, insert the target in the appropriate position.
3 |
4 | Examples:
5 | • Given a binary search tree:
6 | 6
7 | / \
8 | 3 8
9 | / \
10 | 2 4
11 |
12 | • For target: 7 // returns:
13 | 6
14 | / \
15 | 3 8
16 | / \ /
17 | 2 4 7
18 | / \
19 | 1 5
20 |
21 | */
22 | class TreeNode {
23 | constructor(value = 0, leftChild = null, rightChild = null) {
24 | this.value = value
25 | this.left = leftChild
26 | this.right = rightChild
27 | }
28 | }
29 |
30 | function arrayifyTree(root) {
31 | if (!root) { return [] }
32 | var queue = []
33 | var array = []
34 | queue.push(root)
35 | while (queue.length !== 0) {
36 | var node = queue.shift()
37 | array.push(node.value)
38 | if (node.left) { queue.push(node.left) }
39 | if (node.right) { queue.push(node.right) }
40 | }
41 | return array
42 | }
43 |
44 | function insertBST(root, target) {
45 | }
46 |
47 | // Test Cases
48 | var tree = new TreeNode(6, new TreeNode(3, new TreeNode(2), new TreeNode(4)), new TreeNode(8))
49 |
50 | insertBST(tree, 7)
51 | console.log(arrayifyTree(tree), [6, 3, 8, 2, 4, 7])
52 | insertBST(tree, 5)
53 | console.log(arrayifyTree(tree), [6, 3, 8, 2, 4, 7, 5])
54 | insertBST(tree, 1)
55 | console.log(arrayifyTree(tree), [6, 3, 8, 2, 4, 7, 1, 5])
56 | var tree2 = insertBST(null, 1)
57 | console.log(tree2.value, 1)
58 |
59 | //----------------------------------------------------------------------------------
60 |
61 | //Approaches:
62 |
63 | //Time: O(logN) time
64 |
65 | function insertBST(root, target) {
66 | if(!root) return new TreeNode(target);
67 | let curr = root;
68 | while(curr) {
69 | if (target < curr.value) { //if the target is less than the parent node
70 | if (curr.left) { //Go to the left side, if there is a left node
71 | curr = curr.left; //Go to the next left node
72 | }else {
73 | curr.left = new TreeNode(target); //if no left node, add the new treenode with the target value
74 | break; //break out of the loop, there is no point to keep interating through the tree once the target value node is inserted
75 | }
76 | }
77 | else { //if the target is larger than the parent node
78 | if (curr.right) { //Go to the right side, if there is a right node
79 | curr = curr.right; //Go to the next right node
80 | }else {
81 | curr.right = new TreeNode(target); //if no right node, add the new treenode with the target value
82 | break; //break out of the loop, there is no point to keep interating through the tree once the target value node is inserted
83 | }
84 | }
85 | }
86 | return root;
87 | }
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/LongestPalidromicSubstring.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Given a string, find the longest palindromic substring. You may assume there is only one longest substring.
3 |
4 | Examples:
5 |
6 | Given a string: "babe" // returns"bab"
7 | Given a string: "aefez" // returns "efe"
8 | [execution time limit] 4 seconds (js)
9 |
10 | [input] string string
11 |
12 | [output] string
13 |
14 | longest palindromic substring
15 |
16 |
17 | Input:
18 | string: ""
19 | Expected Output:
20 | ""
21 |
22 | Input:
23 | string: "it's afternoon"
24 | Expected Output:
25 | "noon"
26 |
27 | Input:
28 | string: "kb12365456321bb"
29 | Expected Output:
30 | "b12365456321b"
31 | */
32 |
33 |
34 | function longestPalidromicSubstring(str) {
35 | let res = "";
36 | let resLength = res.length;
37 |
38 | for (let i = 0; i < str.length; i++) {
39 | let left = i;
40 | let right = i;
41 | // console.log(i, str[left], str[right]);
42 | //odd
43 | while (left >= 0 && right < str.length && str[left] === str[right]) {
44 | console.log("hey")
45 | let curr_length = (right - left) + 1;
46 | if (curr_length > resLength) {
47 | resLength = curr_length;
48 | res = str.substring(left, right + 1);
49 | console.log(res);
50 | }
51 | left--;
52 | right++;
53 | }
54 | //even
55 | left = i;
56 | right = i + 1;
57 | while (left >= 0 && right < str.length && str[left] === str[right]) {
58 | console.log(left, right);
59 | let curr_length = (right - left) + 1;
60 | if (curr_length > resLength) {
61 | resLength = curr_length;
62 | res = str.substring(left, right + 1);
63 | }
64 | left--;
65 | right++;
66 | }
67 | }
68 | return res;
69 | }
70 |
71 |
72 |
73 |
74 | //MY APPROACH - FAILED!! - TRYING TO DO THIS recursively
75 | // function solution(string) {
76 | // let res = "";
77 | // let maxSubstr = 0;
78 | // let isPalidromic = false;
79 |
80 | // function helper(left, right) {
81 | //base case
82 | // if (left > right || isPalidromic === true) {
83 | // if (maxSubstr < (right - left)) {
84 | // maxSubstr = right - left;
85 | // res = string
86 | // }
87 | // return;
88 | // }
89 | //isPalidromic check
90 | // if (string[left])
91 |
92 | //recursive case
93 | // helper(left + 1, right);
94 | // helper(left, right - 1);
95 | // }
96 |
97 | // helper(0, string.length - 1);
98 |
99 | // return res;
100 | // }
101 |
102 | // console.log(longestPalidromicSubstring("babe"));
103 | console.log(longestPalidromicSubstring("cbbe"));
--------------------------------------------------------------------------------
/AlgoSprint/frequencyElem.js:
--------------------------------------------------------------------------------
1 | // Your previous Plain Text content is preserved below:
2 |
3 | // Algo Sprints Number of Unique Elements Variations
4 |
5 | // 1. Most frequent element in array*
6 | // 2. Least frequent element in array ****
7 | // 3. Number of elements with exactly 2 occurrences ([1, 2, 1, 3, 2, 4] returns 2) ***
8 |
9 |
10 | /*
11 |
12 | Approach
13 | - iterate array
14 | - map
15 | - min
16 |
17 | 1, 1, 3, 2, 6
18 | i
19 |
20 | {
21 | 1: 2
22 | 3: 1
23 | 2: 1
24 | 6: 1
25 | }
26 |
27 | Object.keys(map)
28 | */
29 |
30 | // function findLeastElem(input) {
31 | // let frequencyMap = new Map();
32 | // let min = Infinity;
33 | // let minKey = null;
34 | // for (let i = 0; i < input.length; i++) {
35 | // const count = (frequencyMap.get(input[i]) || 0) + 1;
36 | // frequencyMap.set(input[i], count);
37 | // }
38 | // // let frequencies = frequencyMap.entries();
39 |
40 | // for (const [key, value] of frequencyMap.entries()) {
41 | // if (value < min) {
42 | // min = value;
43 | // minKey = key;
44 | // }
45 | // }
46 |
47 | // return minKey;
48 | // console.log(frequencies);
49 | // }
50 |
51 | // // Test Cases
52 | // console.log(findLeastElem([]), null);
53 | // console.log(findLeastElem([9, 8, 7]), 9);
54 | // console.log(findLeastElem([1, 1, 3, 2, 6]), 3);
55 | // console.log(findLeastElem([1, 1, 1, 3, 5, 3, 2, 2, 5, 6]), 6);
56 | // console.log(findLeastElem([2, 4, 2, 1, 2, 1, 4, 5, 4, 5]), 1);
57 |
58 | // 3. Number of elements with exactly 2 occurrences ([1, 2, 1, 3, 2, 4] returns 2) ***
59 |
60 | // function exactlyTwoOccurances(input) {
61 |
62 | // let frequencyMap = new Map();
63 | // let min = Infinity;
64 | // let minKey = null;
65 | // for (let i = 0; i < input.length; i++) {
66 | // const count = (frequencyMap.get(input[i]) || 0) + 1;
67 | // frequencyMap.set(input[i], count);
68 | // }
69 |
70 | // let listOfTwo = [];
71 | // frequencyMap.forEach( (value, key)=>
72 | // {
73 | // if(value === 2) {
74 | // listOfTwo.push(key);
75 | // }
76 | // });
77 |
78 | // return listOfTwo.length;
79 |
80 | // }
81 |
82 | function findMaxElem(input) {
83 | let frequencyMap = new Map();
84 | let max = 0;
85 | let maxKey = null;
86 | for (let i = 0; i < input.length; i++) {
87 | const count = (frequencyMap.get(input[i]) || 0) + 1;
88 | frequencyMap.set(input[i], count);
89 | }
90 | // let frequencies = frequencyMap.entries();
91 |
92 | for (const [key, value] of frequencyMap.entries()) {
93 | if (value > max) {
94 | max = value;
95 | maxKey = key;
96 | }
97 | }
98 |
99 | return maxKey;
100 | // console.log(frequencies);
101 | }
102 |
103 | // Test Cases
104 |
105 | console.log(exactlyTwoOccurances([1, 1, 3, 2, 6]), 1);
--------------------------------------------------------------------------------
/Independent_Frontend_Practice/sample_react_app_sort-filter-practice.js:
--------------------------------------------------------------------------------
1 | import React, {useState} from "react";
2 |
3 | function TransactionTable({txns}) {
4 | const [date, setDate] = useState(null);
5 | const [transactionTable, setTransactionTable] = useState(txns);
6 |
7 | const sort = (e) => {
8 | e.preventDefault();
9 | let tempTable = [...transactionTable];
10 | for (let i = 0; i < tempTable.length; i++){ //bubble sort
11 | for (let j = 0; j + 1 < tempTable.length; j++) {
12 | let curAmt = tempTable[j].amount;
13 | let nextAmt = tempTable[j+1].amount;
14 | let currItem = tempTable[j];
15 | let nextItem = tempTable[j+1];
16 | if (curAmt > nextAmt) {
17 | tempTable[j] = nextItem;
18 | tempTable[j+1] = currItem;
19 | }
20 | }
21 | }
22 | setTransactionTable(tempTable);
23 | };
24 |
25 | const filter = (e) => {
26 | e.preventDefault();
27 | let fileteredTable = [];
28 | for (let item of txns) {
29 | if (item.date === date) {
30 | fileteredTable.push(item);
31 | }
32 | }
33 | setTransactionTable(fileteredTable);
34 | }
35 |
36 | const handleDateChange = (e) => {
37 | setDate(e.target.value);
38 | }
39 |
40 | return (
41 |
42 |
47 |
48 |
49 |
50 |
51 |
52 | | Date |
53 | Description |
54 | Type |
55 |
56 | Amount ($)
57 | |
58 | Available Balance |
59 |
60 |
61 |
62 | {transactionTable.map((data) => {
63 | return (
64 |
65 | | {data.date} |
66 | {data.description} |
67 | {data.type === 1 ? "Debit" : "Credit"} |
68 | {data.amount} |
69 | {data.balance} |
70 |
71 | )
72 | })}
73 |
74 |
75 |
76 |
77 | );
78 | }
79 |
80 | export default TransactionTable;
81 |
--------------------------------------------------------------------------------
/AlgoMarathon/LinkedList/PairLearning/DeleteKNodesAfterMiddle_wGigi_07-23-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | Given a linked list, delete (k) nodes after the middle.
3 | If (n) is the length of the list, the middle node is [n / 2] using zero-based indexing.
4 | Return the head of the modified list.
5 | Function Signature:
6 | function deleteKNodesAfterMiddle(head)
7 |
8 | (BE AWARE CINDY: IT is not related to delete every kth node after the middle,
9 | but it is regarding to delete K nodes after the middle )
10 |
11 | Questions:
12 | - input head is null or 1 node, should we just return the head? return head
13 | - even or odd number elements in a linked list - what is the mid point for even number of elements in a linked list? (for this problem, we will consider smaller mid point for even)
14 | - if k > number of nodes after the middle, what should we return (modified or not modified)? - need to remove all nodes after the middle when k > mid
15 |
16 |
17 | Approaches: K >= 0
18 | h 1 2 3 4 k: 2 k = 0 mid != nulll
19 | i = 2
20 | d 0 1 2 3 4 middle = 2 3 4
21 | / /
22 | f
23 | s
24 | - Find the middle node (fast and slow pointers)
25 | - traverse middle node as long as k > 0
26 | k--
27 |
28 |
29 | Time: O(2n) => 0(n)
30 | Space: O(n) => 0(n)
31 |
32 | */
33 |
34 | class ListNode {
35 | constructor(value, next = null) {
36 | this.value = value;
37 | this.next = next;
38 | }
39 | }
40 |
41 | const deleteKthNodeAfterMiddleNode = (head, k) => {
42 |
43 | if(!head) {
44 | return head;
45 | }
46 |
47 | let fast = new ListNode(0, head);
48 | let slow = new ListNode(0, head);
49 |
50 | while(fast !== null && fast.next !== null) {
51 | fast = fast.next.next;
52 | slow = slow.next;
53 | }
54 |
55 | let middle = slow;
56 |
57 | while (middle !== null && k >= 0) {
58 | middle = middle.next;
59 | k--;
60 | }
61 |
62 | slow.next = middle;
63 |
64 | return head;
65 | }
66 |
67 |
68 |
69 |
70 |
71 | /*
72 |
73 | 1, 2, null k = 3
74 | ^
75 |
76 |
77 |
78 |
79 | Test Cases:
80 | list = [1, 2, 3, 4], k = 2 => [1, 2]
81 | list = [1], k = 0 => `[1]`
82 | list = [2, 9, 4, 1, 7], k = 3 => [2, 9, 4]
83 | */
84 |
85 | const list1 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
86 | const list2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
87 | const list3 = new ListNode(1);
88 | const list4 = new ListNode(2, new ListNode(9, new ListNode(4, new ListNode(1, new ListNode(7)))));
89 |
90 | console.log(deleteKthNodeAfterMiddleNode(list1, 1)); //[1, 2, 4]
91 | // console.log(deleteKthNodeAfterMiddleNode(list2, 5)); //[1, 2]
92 | // console.log(deleteKthNodeAfterMiddleNode(list3, 0)); //[1]
93 | // console.log(deleteKthNodeAfterMiddleNode(list4, 3)); //[2, 9, 4]
94 |
95 |
96 |
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/BacktrackingwSophie_06-16-22.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
4 |
5 | The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
6 |
7 | It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
8 |
9 |
10 | [1, 2, 3] target: 4
11 | [[1, 3], [2, 2], [1, 1, 1, 1], [1, 1, 2], [-1, 2, 3]]
12 |
13 | Relevant?
14 | - powerset
15 | - 2^n
16 |
17 | target: 8
18 | + 1 +2 +3
19 | target: 7, target: 6, target: 5
20 | x y z
21 |
22 | return x+y+z
23 |
24 | [1, 3], target: 4
25 |
26 | +3 +1
27 | target:1 target: 3
28 | [1] [1,1,1], [3]
29 |
30 | [1, 3], [1, 1, 1, 1], [1, 3]
31 |
32 | Coin change: how many ways to add to target with set of coins?, minimum coins needed to target the target
33 | 1 2 3 4
34 | 1
35 | 2
36 | 3
37 | x
38 | go through dp
39 | code up backtracking xxxxxxx
40 | next question x xxxXxx
41 |
42 | [1, 2, 3], 4
43 | ^
44 | 1, [1, 2, 3], 3 // pick
45 | ^
46 | 1 [1, 2, 3] 2
47 | ^
48 | _ [1, 2, 3] 3
49 | ^
50 |
51 | _, [1, 2, 3], 4 // dontpick (no duplicate going forward)
52 | ^
53 |
54 |
55 | [1, 2, 3], 8
56 | ^
57 |
58 | 1 [1, 2, 3], 7 /// pick
59 | ^
60 | , [1, 2, 3], 8 /// dontp ick
61 | ^
62 |
63 |
64 | [1, 2, 3] 4
65 |
66 | 1 2 3
67 | 1 2 3 2
68 | 1 1
69 | 1
70 | results = [[1, 1, 1, 1], [1, 1, 2]
71 | pick 1
72 | pick 1
73 | pick 1 pick 2
74 | pick 1 [1, 1, 2]
75 | [1, 1, 1, 1]
76 |
77 | 3
78 | 2 1
79 | 0 4 2 5
80 |
81 |
82 | */
83 |
84 | function uniqueCombos(input, target) {
85 | let results = []
86 | uniqueCombosHelper(input, target, 0, [], results)
87 | return results
88 | }
89 |
90 | function uniqueCombosHelper(input, target, i, combo, results) {
91 | if (target == 0) { // base case - we've found a valid combo!
92 | results.push([...combo])
93 | return
94 | }
95 |
96 | if (input[i] <= target) {
97 | combo.push(input[i])
98 | uniqueCombosHelper(input, target - input[i], i, combo, results) // jiyoon
99 | combo.pop()
100 | }
101 | if (i < input.length - 1) {
102 | uniqueCombosHelper(input, target, i+1, combo, results) // zaneh
103 | }
104 | }
105 |
106 | // console.log(uniqueCombos([1, 2, 3], 4))
107 | // console.log(uniqueCombos([1, 2, 3], 8))
108 | // console.log(uniqueCombos([3, 4], 5))
109 | // console.log(uniqueCombos([], 3))
110 | console.log(uniqueCombos([-1], 3))
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/7_Summing_LinkedLists/sumTwoEqualLL.js:
--------------------------------------------------------------------------------
1 | // Q. Given two linked lists of "equal" length, sum elements' value at the same position.
2 |
3 | // Examples:
4 | // Given two linked lists:
5 | //head1: 1 ➞ 3 ➞ 5
6 | //head2: -1 ➞ 3 ➞ -10 // returns 0 ➞ 6 ➞ -5
7 |
8 | // Given two linked lists:
9 | //head1: 0
10 | //head2: 0 // returns 0
11 |
12 |
13 | class ListNode {
14 | constructor(value = 0, next = null) {
15 | this.value = value
16 | this.next = next
17 | }
18 | }
19 |
20 | function arrayify(head) { //convert a Linked List output into an Array output
21 | let ptr = head
22 | var array = []
23 | while (ptr != null) {
24 | array.push(ptr.value)
25 | ptr = ptr.next
26 | }
27 | return array
28 | }
29 |
30 | function sumTwoLL(head1, head2) {
31 | // Write your code here.
32 | }
33 |
34 | // Test Cases
35 | const LL1 = new ListNode(1, new ListNode(3, new ListNode(5)))
36 | const LL2 = new ListNode(-1, new ListNode(3, new ListNode(-10)))
37 | const LL3 = new ListNode(1, new ListNode(3, new ListNode(5)))
38 | const LL4 = new ListNode(-1, new ListNode(3))
39 | console.log(arrayify(sumTwoLL(LL1, LL2))) // [0, 6, -5]
40 | console.log(arrayify(sumTwoLL(LL3, LL4))) // [0, 6]
41 | console.log(arrayify(sumTwoLL(new ListNode(0), new ListNode(0)))) //[0]
42 |
43 |
44 | //----------------------------------------------------------------------------------
45 |
46 | //Approaches:
47 |
48 | //Iterative Approach (uncomment below and see how it works in the console)
49 |
50 | /*Question: Why will the following function errors out
51 | when we only set to iterate through h1 like 'while (h1)'??? */
52 |
53 | function sumTwoLLIterative(head1, head2) {
54 | let sumHeads = new ListNode(0);
55 | let curr = sumHeads, h1 = head1, h2 = head2; //<-- variables can be declared and assigned in one line
56 |
57 | while (h1 && h2) { //break the loop when h1 or h2 is null (the loop only continue when both h1 and h2 are both NOT null, if one is null, it will break the loop)
58 | curr.next = new ListNode(h1.value + h2.value);
59 | curr = curr.next;
60 | h1 = h1.next;
61 | h2 = h2.next;
62 | }
63 | console.log("h1: ", h1);
64 | console.log("h2: ", h2);
65 | console.log("sumHeads: ", sumHeads);
66 | console.log("sumHeads.next: ", sumHeads.next);
67 | return sumHeads.next;
68 | }
69 |
70 | //UNCOMMENT BELOW TO TEST:
71 | // const LL6 = new ListNode(1, new ListNode(3, new ListNode(5)))
72 | // const LL7 = new ListNode(-1, new ListNode(3, new ListNode(-10)))
73 | // const LL8 = new ListNode(1, new ListNode(3, new ListNode(5)))
74 | // const LL9 = new ListNode(-1, new ListNode(3))
75 | // console.log(arrayify(sumTwoLLIterative(LL6, LL7))) // [0, 6, -5]
76 | // console.log(arrayify(sumTwoLLIterative(LL8, LL9))) // [0, 6]
77 | // console.log(arrayify(sumTwoLLIterative(new ListNode(0), new ListNode(0)))) //[0]
78 |
79 |
80 | /*
81 | Time Complexity (runtime): O(n)
82 |
83 | Space Complexity (memory): O(1)
84 |
85 | */
86 |
--------------------------------------------------------------------------------
/AlgoMockedInterview/DynamicProgramming/ConceptDrillwSumeet_09-27-22.js:
--------------------------------------------------------------------------------
1 | // Dynamic Programming PDF: https://www.byte-by-byte.com/wp-content/uploads/2019/04/Dynamic-Programming-for-Interviews.pdf
2 | //
3 | //
4 | // 1. First solution (NO CACHE)
5 | // Naive
6 | // Recursive
7 | // 2. Analyze the first solution
8 | // See if it works, and see its runtime complexity
9 | // 3. Identify the Subproblems
10 | // See what you could memoize (cache)
11 | // Saving the results of work you did before (pure function)
12 | //
13 | // "Top down" DP solution
14 | // 4. Turn the solution around
15 | // Bottom-up iterative solution without recursion, using a "DP Matrix"
16 | //
17 | //
18 | // Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
19 | //
20 | // A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
21 | //
22 | // For example, "ace" is a subsequence of "abcde".
23 | // A common subsequence of two strings is a subsequence that is common to both strings.
24 |
25 | // // ++..+
26 | // t1 = "ababcd"
27 | // // ++v
28 | // t2 = "abc"
29 | // r = 3
30 | // /*
31 | // "abeeeeeebcd"
32 | // "abbcdeeeeee"
33 | // */
34 | // t1 = "ace"
35 | // t2 = "abc"
36 | // r = 2
37 |
38 | // t1 = "abc"
39 | // t2 = "def"
40 | // r = 0
41 |
42 | // t1 = "aaa"
43 | // t2 = "abb"
44 | // r = 1
45 |
46 | // t1 =""
47 | // t2 = "abb"
48 | // r = 0
49 |
50 | /* v
51 | str1 = 'azc'
52 | str2 = 'ab'
53 |
54 | i = 0
55 | j = 0
56 |
57 | str1[i]==0] == "a"
58 | str2[j]==0] == "a"
59 | match, so count: 1
60 |
61 | i++
62 | j++
63 |
64 | str1[i]==1] == "z"
65 | str2[j]==1] == "b"
66 |
67 | two branches:
68 | - j++ and not i
69 | - i++ and not j
70 |
71 | - pick the bigger branch (max)
72 | */
73 |
74 | function lcs(t1, t2) {
75 | let counts = [0];
76 | let cache = {};
77 |
78 | function dfs(i, j) {
79 | const key = `${i}-${j}`;
80 | if (cache[key] !== undefined) {
81 | return cache[key];
82 | }
83 |
84 | counts[0] += 1;
85 | if (i >= t1.length) return 0;
86 | if (j >= t2.length) return 0;
87 |
88 | if (t1[i] === t2[j]) {
89 | cache[key] = 1 + dfs(i + 1, j + 1);
90 | } else {
91 | cache[key] = Math.max(dfs(i, j + 1), dfs(i + 1, j));
92 | }
93 | return cache[key];
94 | }
95 | const ret = dfs(0, 0);
96 | console.log("this took", counts, "comparisons");
97 | return ret;
98 | }
99 |
100 | console.log(lcs("abc", "abcdefabc"), 3);
101 | console.log(lcs("aaa", "abb"), 1);
102 | console.log(lcs("abc", ""), 0);
103 | console.log(
104 | lcs("abc", "ajiojwoiefjiowejfioewjfiobwjieofjoiewjfiewjfoicjiweofjoiwef"),
105 | 3
106 | );
107 | console.log(
108 | lcs(
109 | "abcjiofjawofiejawoeifjaowef",
110 | "ajiojwoiefjiowejfioewjfiobwjieofjoiewjfiewjfoicjiweofjoiwef"
111 | ),
112 | 3
113 | );
114 |
--------------------------------------------------------------------------------
/CoreAlgos/BinaryTree/BinarySearchTree/validateBST.js:
--------------------------------------------------------------------------------
1 | /*
2 | Validate a Binary Search Tree
3 |
4 | Binary Search Tree - all the left (+ child) nodes should be smaller than the root node,
5 | and all the right (+ child) nodes should be larger than the root node
6 |
7 | 6
8 | / \
9 | 3 8
10 | / \
11 | 2 4
12 |
13 |
14 | */
15 |
16 | class TreeNode {
17 | constructor(value = 0, leftChild = null, rightChild = null) {
18 | this.value = value
19 | this.left = leftChild
20 | this.right = rightChild
21 | }
22 | }
23 |
24 | function validateBST(tree) {
25 |
26 | }
27 |
28 | // Test Cases
29 | var tree1 = new TreeNode(2, new TreeNode(1), new TreeNode(3))
30 | var tree2 = new TreeNode(1, new TreeNode(2), new TreeNode(3))
31 | var tree3 = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10, null, new TreeNode(14, new TreeNode(13))))
32 | console.log(validateBST(null)) // true
33 | console.log(validateBST(tree1)) // true
34 | console.log(validateBST(tree2)) // false
35 | console.log(validateBST(tree3)) // true
36 | console.log(validateBST(new TreeNode())) // true
37 |
38 | //----------------------------------------------------------------------------------
39 |
40 | //Approaches:
41 |
42 | //Recursive Approach:
43 |
44 | function validateBST(tree, min = -Infinity, max = Infinity) {
45 | if (!tree) return true;
46 | // console.log(tree);
47 | // console.log("Minimum: ", min);
48 | // console.log("Maximum: ", max);
49 | if (tree.value <= min || tree.value > max) return false;
50 | return validateBST(tree.left, min, tree.value) && validateBST(tree.right, tree.value, max);
51 | }
52 |
53 | //Another approach (but pretty confusing in the last line in the function)
54 | // function solution(root, min = -Infinity, max = Infinity) {
55 | // if (!root) return null;
56 | // if (root.value <= min || root.value > max) return false;
57 | // let left = solution(root.left, min, root.value),
58 | // right = solution(root.right, root.value, max);
59 | // return typeof left === 'undefined' && typeof right === 'undefined' ? true : left === false || right === false ? false : true;
60 | // }
61 |
62 |
63 | /*
64 | Another Approach - based on a fellow asked in Mattermost
65 | Creating a header function.
66 | */
67 | function validate_bst(node) {
68 | return helper(node, -Infinity, Infinity);
69 | }
70 |
71 | function helper(node, min, max) {
72 | if (!node) return 1;
73 | if (node.value <= min || node.value > max) return 2;
74 |
75 | const left = helper(node.left, min, node.value);
76 | const right = helper(node.right, node.value, max);
77 |
78 | if (left === 2) {
79 | return left;
80 | }else {
81 | return right;
82 | }
83 | // Same expression as the above if statement, but in the ternary expression (below):
84 | // return left === 2 ? left : right === 2 ? right : left;
85 | }
86 |
87 | const tree2 = new TreeNode(1, new TreeNode(2), new TreeNode(3))
88 | console.log(validate_bst(tree2));
--------------------------------------------------------------------------------
/CoreAlgos/LinkedList/6_Reversing/reverse.js:
--------------------------------------------------------------------------------
1 | /*
2 | Q. Reverse a given linked list.
3 |
4 | Examples:
5 | • Given a linked list: 13 ➞ 1 ➞ 5 ➞ 3 ➞ 7 ➞ 10 // returns 10 ➞ 7 ➞ 3 ➞ 5 ➞ 1 ➞ 13
6 | • Given a linked list: 1 // returns 1
7 | */
8 |
9 | class ListNode {
10 | constructor(value = 0, next = null) {
11 | this.value = value
12 | this.next = next
13 | }
14 | }
15 |
16 | function arrayify(head) {
17 | let ptr = head
18 | var array = []
19 | while (ptr != null) {
20 | array.push(ptr.value)
21 | ptr = ptr.next
22 | }
23 | return array
24 | }
25 |
26 | function reverse(head) {
27 | }
28 |
29 |
30 | // Test Cases
31 | const LL1 = new ListNode(13, new ListNode(1, new ListNode(5, new ListNode(3, new ListNode(7, new ListNode(10))))))
32 | console.log(arrayify(reverse(new ListNode(1)))) // [1]
33 | console.log(arrayify(reverse(new ListNode(1, new ListNode(2))))) // [2, 1]
34 | console.log(arrayify(reverse(LL1))) // [10, 7, 3, 5, 1, 13]
35 |
36 | //----------------------------------------------------------------------------------
37 |
38 | //Approaches: (Take a look at the visualization to help to understand the concept)
39 |
40 | //Time: O(n)
41 |
42 | function reverseIterative(head) {
43 | let curr = head;
44 | let prev;
45 | while(curr) {
46 | const holdNext = curr.next;
47 | curr.next = prev;
48 | prev = curr;
49 | curr = holdNext;
50 | }
51 | return prev;
52 | }
53 |
54 | // Test Cases
55 | const LL2 = new ListNode(13, new ListNode(1, new ListNode(5, new ListNode(3, new ListNode(7, new ListNode(10))))))
56 | console.log(arrayify(reverseIterative(new ListNode(1)))) // [1]
57 | console.log(arrayify(reverseIterative(new ListNode(1, new ListNode(2))))) // [2, 1]
58 | console.log(arrayify(reverseIterative(LL2))) // [10, 7, 3, 5, 1, 13]
59 |
60 |
61 | /*
62 | Visualization
63 |
64 | null 1 2 3 4
65 | p c
66 |
67 | null 1 (2 3 4)
68 | p c h---h
69 |
70 | (1 null)
71 | p c c.next
72 |
73 |
74 | 2 (1 null)
75 | c p
76 |
77 | (3 4)
78 | h-h
79 |
80 | 2 1 null
81 | c c.next
82 |
83 | 2 1 null
84 | p
85 |
86 | 3 (2 1 null)
87 | c p
88 |
89 | (4)
90 | h
91 |
92 | 3 2 1 null
93 | c c.next
94 |
95 | 3 2 1 null
96 | p
97 |
98 | 4 3 2 1 null
99 | c p
100 |
101 | h = null
102 |
103 | null 4 3 2 1 null
104 | c p
105 |
106 | h = null
107 |
108 | return p
109 |
110 | */
111 |
112 |
113 | /*
114 | Another Apporach (that handle edge cases):
115 |
116 | Input:
117 | list: []
118 | Expected Output:
119 | []
120 |
121 | function reverse(list) {
122 | let curr = list;
123 | let prev = null;
124 | while (curr) {
125 | let holdNext = curr.next;
126 | curr.next = prev;
127 | prev = curr;
128 | curr = holdNext;
129 | }
130 | return prev === null ? [] : prev;
131 | }
132 |
133 |
134 | */
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/PairLearning/cellTowerswBrian.js:
--------------------------------------------------------------------------------
1 | /*
2 | One-on-One with Brian Do!!! (around close to 2hrs)
3 |
4 | ATTEMPT #1
5 |
6 | Prompt (This is considered a MEDIUM TYPE problem)
7 |
8 | You are given an array representing the positions of cell towers along a 2 dimensional line. You are given a second array representing positions of customers across the same 2 dimensional line. Given these two inputs, you must determine a signal strength k such that every customer is covered by at least one cell tower. All cell towers must have the exact same signal strength and covers customers to its left and right equally.
9 |
10 | Function Signature:
11 | def search(listener, towers):
12 |
13 |
14 | leftI: 0
15 |
16 | left: 3
17 | right: Infinity
18 |
19 | time: O(nlogn + mlogm) if both arrays are unsorted
20 | time: O(n + m) if both arrays are sorted
21 |
22 |
23 |
24 | for (customers)
25 | while towers[leftI] < currCustomer
26 |
27 | towers: [2, 3, 5, 6]
28 | customers: [4, 20, 5]
29 | k = 14
30 |
31 | smallestDistanceNeeded = 3
32 | lastEncountered = customer
33 | lastEncounteredI = 4
34 |
35 | k = 3
36 |
37 | i
38 | ....1.......1....1......
39 | ...o.....o........o......
40 |
41 |
42 |
43 | 1. sort the towers array and the customers array
44 | 2. iterate through the customers array
45 | 3. find the closest tower on the left and right side of the customer and update k
46 | - set the left variable to -Infinity, the right varaible to Infinity
47 | - find the 2 towers that are closest to the customer in terms of distance, compare them, and only update k based on the highest smallest difference found.
48 | */
49 |
50 | function search(customers, towers) {
51 | customers.sort((a, b) => a - b); // also no.
52 | towers.sort((a, b) => a - b); // no.
53 |
54 | let k = 0
55 | let towerI = 0;
56 |
57 | for (let i = 0; i < customers.length; i++) {
58 | let left = -Infinity;
59 | let right = Infinity;
60 |
61 | while (customers[i] > towers[towerI]) {
62 | left = towers[towerI++]
63 | }
64 | right = towers[towerI] ?? Infinity //undefined or null. || (falsy) or ?? (nullish)
65 |
66 |
67 | const leftDistance = Math.abs(left - customers[i])
68 | const rightDistance = Math.abs(right - customers[i])
69 | const closestTowerDistance = Math.min(leftDistance, rightDistance)
70 | k = Math.max(k, closestTowerDistance)
71 | }
72 |
73 | return k
74 | }
75 |
76 |
77 | console.log(search([4, 5, 20], [2, 3, 5, 6]), 14);
78 | console.log(search([4, 5, 20], [2, 3, 5, 6, 21]), 1);
79 |
80 |
81 |
82 |
83 | // Javascript Solution (Formation)
84 | function search(listener, towers) {
85 | let maxTowerDistance = Number.MAX_SAFE_INTEGER;
86 | let towerIdx = 0;
87 | for (let i = 0; i < listener.length; i++) {
88 | while(towerIdx + 1 < towers.length
89 | && Math.abs(listener[i] - towers[towerIdx]) <= Math.abs(listener[i] - towers[towerIdx + 1])) {
90 | towerIdx++;
91 | }
92 | maxTowerDistance = Math.min(maxTowerDistance, Math.abs(listener[i] - towers[towerIdx]));
93 | }
94 | return maxTowerDistance;
95 | }
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/SodukuMatrixRotateMatrixwTonyandDaniel_07-21-22.py:
--------------------------------------------------------------------------------
1 | '''
2 | Tony and Daniel Office hours on Algo Marathon
3 |
4 | Approach the problem in High level Perspective First
5 | '''
6 |
7 |
8 | def rotate(matrix):
9 |
10 | # YES: iterate through the top left corners of the enclosing boxes
11 | # YES: stop when you're at or past the center of the square matrix
12 | # NO: loop from 0 to the center
13 | nesting = 0
14 | while nesting <= len(matrix)//2:
15 |
16 | for col in range(nesting, len(matrix) - nesting - 1):
17 | # do one musical chairs
18 | musicalChairs(matrix, nesting, col)
19 |
20 | nesting += 1
21 |
22 |
23 |
24 |
25 | def musicalChairs(matrix, nesting, col): # indexing is tricky
26 | temp = matrix[nesting][col]
27 | matrix[nesting][col] = matrix[nesting][len(matrix)-col-1]
28 | matrix[nesting][len(matrix)-col-1] = matrix[len(matrix)-nesting-1][len(matrix)-col-1]
29 | matrix[len(matrix)-nesting-1][len(matrix)-col-1] = matrix[len(matrix)-nesting-1][col]
30 | matrix[len(matrix)-nesting-1][col] = temp
31 |
32 |
33 | matrix = [[1,2,3],[4,5,6],[7,8,9]]
34 | print("Pre-rotation")
35 | print(matrix)
36 | print("\n\nPost-rotation")
37 | rotate(matrix)
38 | print(matrix[0])
39 | print(matrix[1])
40 | print(matrix[2])
41 |
42 | '''
43 |
44 | store the value at [0][0] then
45 | [0][0] gets the value in
46 | [0][2] gets the value in
47 | [2][2] gets the value in
48 | [2][0]
49 |
50 | now we have to do this for all the elements in the row up to length-2
51 | now we go down and right once [1][1], repeat for all elements in the row up to length-3
52 | stop when you're at or past the center of the square matrix
53 |
54 | # Mike's algorithm aka 4 way musical chairs
55 | temp = a
56 | a = b
57 | b = c
58 | c = d
59 | d = a
60 |
61 | Input:
62 | 1 2 3 1
63 | 3 5 5 2
64 | 2 5 5 3
65 | 1 3 2 1
66 |
67 | Output:
68 | 1 2 3 1
69 | 3 5 5 2
70 | 2 5 5 3
71 | 1 3 2 1
72 |
73 | '''
74 |
75 | # Not exactly but close: https://leetcode.com/problems/valid-sudoku/
76 | # Each row must contain the digits 1-9 without repetition.
77 | # Each column must contain the digits 1-9 without repetition.
78 | # Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
79 |
80 | # n = number of rows/col
81 | # Time Complexity: O(nlogn)
82 | # O(n*n*n) = O(n^3)
83 |
84 |
85 | # n^2 + n^2 + n^2 = 3n^2 = O(n^2) where n is the number of rows/cols
86 | # O(r*c) where r is the number of rows and c is the number of cols
87 | # O(t) where t is the number of cells
88 | # O(1) because the size is always 81 cells
89 |
90 |
91 |
92 | # Agree |
93 | # Disagree | X
94 |
95 | """
96 | Complexity:
97 | A: O(log N) |
98 | B: O(N) |
99 | C: O(N^2) |x
100 | D: O(1) | ----- WINNER!!!!!! 😲
101 | E: O(N^3) |
102 | """
103 |
104 | def isValidSudoku(matrix):
105 | return areRowsValid(matrix) \
106 | and areColsValid(matrix) \
107 | and areCellsValid(matrix)
108 |
109 | def areRowsValid(matrix):
110 | pass
111 |
112 | def areColsValid(matrix):
113 | pass
114 |
115 | def areCellsValid(matrix):
116 | pass
--------------------------------------------------------------------------------
/AlgoMockedInterview/1-on-1-with-Mentor /Afeez_08-25-22.js:
--------------------------------------------------------------------------------
1 | /*
2 | You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be
3 | integers or other lists. Implement an iterator to flatten it.
4 |
5 | Implement the NestedIterator class:
6 |
7 | - NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList.
8 | - int next() Returns the next integer in the nested list.
9 | - boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
10 |
11 | Your code will be tested with the following pseudocode:
12 |
13 | initialize iterator with nestedList
14 | res = []
15 | while iterator.hasNext()
16 | append iterator.next() to the end of res
17 | return res
18 |
19 | If res matches the expected flattened list, then your code will be judged as correct.
20 |
21 | Example 1:
22 |
23 | Input: nestedList = [[1,1],2,[1,1]]
24 | Output: [1,1,2,1,1]
25 | Explanation: By calling next repeatedly until hasNext returns false,
26 | the order of elements returned by next should be: [1,1,2,1,1].
27 |
28 | Example 2:
29 |
30 | Input: nestedList = [1,[4,[6]]]
31 | Output: [1,4,6]
32 | Explanation: By calling next repeatedly until hasNext returns false,
33 | the order of elements returned by next should be: [1,4,6].
34 |
35 |
36 | next
37 |
38 | hasNext
39 |
40 | [1, 4, 6]
41 |
42 | [1,[4,6]]
43 |
44 | ^
45 |
46 | number vs array
47 |
48 | //item.length
49 |
50 | Recursion (DFS)
51 |
52 | base case: when it has reached the end of the array
53 |
54 | recrusive: everytime it is an array,
55 |
56 | dfs(i + 1)
57 |
58 | Array.isArray()
59 |
60 |
61 | edge case: object
62 |
63 | */
64 |
65 | let num = 3
66 | console.log(num.length);
67 | console.log(Number([1,2]));
68 |
69 | /**
70 | * Your NestedIterator will be called like this:
71 | * var i = new NestedIterator(nestedList), a = [];
72 | * while (i.hasNext()) a.push(i.next());
73 | */
74 | 1
75 | [1, [2, 17, 7], 4]
76 | class NestedIterator {
77 | constructor(nestedList) {
78 | this._flattenList(nestedList)
79 | }
80 |
81 | _flattenList(nestedList) {
82 | let res = [];
83 |
84 |
85 | function dfs(nestedList, age) {
86 | //recursive call when the list item is an array
87 | //dfs(nestedList)
88 |
89 | age++; //21
90 |
91 |
92 | for (let i = 0; i < nestedList.length; i++) {
93 | if (!Array.isArray(nestedList[i])) {
94 | res.push(nestedList[i]);
95 | } else {
96 | dfs(nestedList, age);
97 | }
98 |
99 | }
100 |
101 |
102 | }
103 | dfs(nestedList, 19)
104 | return res;
105 | }
106 |
107 | hasNext() {
108 | return this._position < this._integers.length;
109 | }
110 |
111 | next() {
112 | if (!this.hasNext()) return undefined;
113 |
114 | return this._integers[this._position++];
115 | }
116 | }
117 |
118 | let list = new NestedIterator([[1,1],2,[1,1]])
119 |
120 |
121 | [1, [2, 17, 7], 4]
122 |
123 | res = [1,2, 17, 7]
124 |
125 | // https://leetcode.com/problems/flatten-nested-list-iterator/
--------------------------------------------------------------------------------
/1-on-1-w-Mentor-Fellow/authurDamm_DFS_Recursion.js:
--------------------------------------------------------------------------------
1 | class TreeNode {
2 | constructor(value = 0, leftChild = null, rightChild = null) {
3 | this.value = value
4 | this.left = leftChild
5 | this.right = rightChild
6 | }
7 | }
8 |
9 | function arrayifyTree(root) {
10 | if (!root) { return [] }
11 | var queue = []
12 | var array = []
13 | queue.push(root)
14 | while (queue.length !== 0) {
15 | var node = queue.shift()
16 | array.push(node.value)
17 | if (node.left) { queue.push(node.left) }
18 | if (node.right) { queue.push(node.right) }
19 | }
20 | return array
21 | }
22 |
23 | /*
24 | Given a binary tree, return the deepest node (furthest away child).
25 | Examples
26 | . a
27 | . / \
28 | . b c
29 | . /. \
30 | .d. e
31 | \
32 | f
33 | returns d
34 | equal depth in both right and left - return one of them
35 |
36 | ORDER of DFS calls (recursive call stack): a
37 |
38 | How many approaches to solve this problem?
39 |
40 | DFS (naturally recursive)
41 | */
42 |
43 |
44 | // dfsDepth(node, depth_of_parent) // depth
45 | // each node knows its depth is 1 + depth_of_parent
46 |
47 |
48 | function depthOfTree(root) { //top down pre order
49 | let maxDepth = -Infinity;
50 | let deepestNode = null;
51 | function depthDFS(root, depth) {
52 | // if (!root) return;
53 | if (depth > maxDepth) {
54 | maxDepth = depth;
55 | deepestNode = root;
56 | }
57 | depthDFS(root.left, depth+1)
58 | depthDFS(root.right, depth+1)
59 | }
60 | depthDFS(root, 0);
61 | return deepestNode;
62 | }
63 |
64 | // const tree1 = new TreeNode('a', new TreeNode('b', new TreeNode('d')), new TreeNode('c', null, new TreeNode('e', null, new TreeNode('f'))));
65 | // console.log(depthOfTree(tree1));
66 |
67 |
68 |
69 | // Preorder, inorder, postorder
70 |
71 |
72 | // heightOfTree(root) { //bottom up post order
73 |
74 | // const nodeHeights = {}; // {node: height}
75 |
76 | // function heightDFS(node) { // node =b
77 |
78 | // if (!node) return 0;
79 |
80 | // post-order, children first then root
81 | // const left = heightDFS(node.left)
82 | // const right = heightDFS(node.right)
83 | // const myHeight = Math.max(left, right);
84 |
85 | // nodeHeights[node] = myHeight; // { d: 0, b: 1, c: 0, a:2 }
86 | // return 1 + myHeight;
87 | // }
88 |
89 | // let x = heightDFS(root); // returns 3
90 | // return nodeHeights[root];
91 |
92 | // }
93 |
94 |
95 |
96 | // let lowestCommonAncestor = (root, c1, c2) => {
97 | // return solution(root, c1, c2)
98 |
99 | // };
100 |
101 | // function solution(root, val1, val2) {
102 | // if (!root || root === val1 || root === val2) {
103 | // return root;
104 | // }
105 |
106 | // const left = solution(root.left, val1, val2);
107 | // const right = solution(root.right, val1, val2);
108 |
109 | // if (left && right) {
110 | // return root;
111 | // }
112 |
113 | // return left ? left : right;
114 | // }
--------------------------------------------------------------------------------
/Weekly Gather Mentor Office Hours/AddOneRowToATreewDaniel_07-07-22.js:
--------------------------------------------------------------------------------
1 |
2 |
3 | /*
4 | Who thinks:
5 | - BFS is easier to code ***********
6 | - DFS is easier to code *******
7 |
8 | https://leetcode.com/problems/add-one-row-to-tree/
9 |
10 |
11 | Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
12 |
13 | Note that the root node is at depth 1.
14 |
15 | The adding rule is:
16 |
17 | Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
18 | cur's original left subtree should be the left subtree of the new left subtree root.
19 | cur's original right subtree should be the right subtree of the new right subtree root.
20 | If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
21 | */
22 | class Node {
23 | constructor(val, left, right) {
24 | this.val = val;
25 | this.left = left;
26 | this.right = right;
27 | }
28 | }
29 |
30 | function addOneRow(root, val, depth) {
31 |
32 | if (!root) return null;
33 |
34 | if (depth === 1) { // insert @ the root
35 | const newRoot = new Node(val, root);
36 | return newRoot;
37 | }
38 |
39 | let read = [root];
40 | let write = [];
41 | let writeDepth = 2; // if depth=2: dont enter loop (insert @ the root's children)
42 | // Collect the nodes at depth - 1 using BFS
43 | while (writeDepth < depth - 1) { // SAME AS while (writeDepth <= depth) {
44 | for (const node of read) {
45 | if (node.left) {
46 | write.push(node.left);
47 | }
48 | if (node.right) {
49 | write.push(node.right);
50 | }
51 | }
52 | read = write;
53 | write = [];
54 | writeDepth++;
55 | }
56 |
57 | // Iterate over the collected node and perform the required operations
58 | for (const node of read) {
59 | const newLeft = new Node(val, node.left);
60 | const newRight = new Node(val, node.right);
61 | node.left = newLeft;
62 | node.right = newRight;
63 | }
64 |
65 | return root;
66 | }
67 |
68 |
69 |
70 | const matrix = getMatrix();
71 |
72 | // n = total size
73 | // r = number of rows
74 | // c = number of columns
75 | // O(n)
76 | // O(r * c)
77 | // r * c = n
78 | // r == c
79 | // O(r^2)
80 |
81 | // Name: row-major traversal
82 | // for (let row = 0; row < matrix.length; row++) { // for each row
83 | // const currentRow = matrix[row];
84 | // for (let col = 0; col < currentRow.length; col++) { // for each element in that row
85 | // // do something here
86 | // }
87 | // }
88 |
89 | // Column major traveral
90 |
91 | // for (let col = 0; col < matrix[0].length; col++) { // for each column
92 | // for (let row = 0; row < matrix.length; row++) { // for each element in that column
93 | // }
94 |
95 | // for each row
96 | // describe the work to be done on that row in english
97 |
98 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/AlgoMarathon/Arrays/PairLearning/dogsAndHatswNancy.js:
--------------------------------------------------------------------------------
1 | /*
2 | One of the most common uses of a queue is to keep a list of "work to be done". Just like doing housework, often new things get added to the TODO list while doing some other task. New jobs get added to the end of the queue, and when one is complete, the next one is taken from the top of the list.
3 | Oliver is missing his favorite hat and is asking his friends at the dog park if they've seen it. Each dog either has seen it or suggests a list of other dogs to ask. Return the name of the dog who has seen the hat. Oliver starts out by asking his best friend. This function will take two parameters. The first is a map of dogs to a list of their friends. The second is Oliver's best friend, who Oliver will ask first.
4 |
5 | Function Signature:
6 | function findHat(dogs, bestFriend)
7 |
8 | Target runtime and space complexity:
9 | O(n)
10 |
11 | Examples:
12 | const dogs = {
13 | 'Carter': ['Fido', 'Ivy'],
14 | 'Ivy': ["HAT"], // Ivy has seen the hat
15 | 'Loki': ['Snoopy'],
16 | 'Pepper': ['Carter'],
17 | 'Snoopy': ['Pepper'],
18 | 'Fido': []
19 | };
20 |
21 | console.log(findHat(dogs, 'Loki')); // returns 'Ivy'
22 | */
23 |
24 |
25 | /*
26 |
27 | Questions:
28 | what if no one sees Ivy!! (we need to ask for clarification)
29 | what if no one sees the Hat!! (throw an error)
30 | Should the order of the seen dogs matter?
31 |
32 |
33 | approach:
34 | - queue: order of dogs to ask
35 | - set: dogs that we have asked
36 |
37 | */
38 |
39 |
40 | function findHat(dogs, bestFriend) {
41 | let queue =[bestFriend];
42 | let askedDogs = new Set();
43 | while (queue.length > 0) {
44 | let currentDog = queue.pop();
45 |
46 | if (dogs[currentDog][0] === 'HAT') return currentDog;
47 |
48 | dogs[currentDog].forEach(dog => {
49 | if (!askedDogs.has(dog)) askedDogs.add(dog)
50 | })
51 |
52 |
53 | // let dog = queue.pop(); //or shift()
54 | // if(!askedDogs.has(dog)) { //if we have not asked the dog
55 | // askedDogs.add(dog);
56 | // queue = [...queue, ...dogs[dog]];
57 | // }
58 | // if(dogs[dog][0] === 'HAT') {
59 | // return dog;
60 | // }
61 | }
62 | return "No Hat Found!";
63 | }
64 | /*
65 | Loki
66 | |
67 | Snoopy
68 | |
69 | Pepper
70 |
71 |
72 | W
73 | e. h
74 | t. a
75 | t.
76 |
77 |
78 |
79 | */
80 |
81 | //Test cases
82 | const dogs = {
83 | 'Carter': ['Fido', 'Ivy'],
84 | 'Ivy': ["HAT"], // Ivy has seen the hat
85 | 'Loki': ['Snoopy'],
86 | 'Pepper': ['Carter', 'loki'],
87 | 'Snoopy': ['Pepper'],
88 | 'Fido': []
89 | };
90 | const dogs2 = { //edge case that does not taken into consideration in this problem, we have assumed all the dogs at least know other dogs in the list
91 | 'Carter': ['Fido'],
92 | 'Ivy': ['HAT'],
93 | 'Loki': ['Snoopy'],
94 | 'Pepper': ['Carter'],
95 | 'Snoopy': ['Pepper'],
96 | 'Fido': []
97 | };
98 |
99 |
100 | console.log(findHat(dogs, 'Loki')); // returns 'Ivy'
101 | console.log(findHat(dogs2, 'Loki')); // return 'no hat found'
102 |
103 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/Public-Formation-Events/README.md:
--------------------------------------------------------------------------------
1 | # Formation Events
2 |
3 |
6 |
7 | ## NextDoor x Formation Panel Discussion (Live Stream) - 09/13/2022
8 |
9 | `YOU ARE WORTH SO MUCH MORE`
10 |
11 | Takeaways:
12 | - `When there are constraints, focus on your values and strength`
13 | - Sophie Advice on Job Searching:
14 | 1. Companies are taking leveling more seriously
15 | - focus more on system design is key
16 | 2. Past Experience
17 | - focus on presenting and promoting yourself to the public
18 | - Practical skills matter in actual interview setting
19 | - The more projects skill you have the better it is!
20 | - It is okay to take the time to figure out what you want
21 | - find any possible ways to help you to get into your desired companies
22 | - In terms of learning, think of yourself as a Founding Team member. Take Risk, pressure on learning, start something from ground zero
23 | - `WHAT YOU WANT` is key for job searching
24 | - FIGURE OUT your STRENGTH and what you want to work on
25 | - Companies are looking for `Good Fit People` and they want the people they hire can follow the engineering team structure!
26 | - If you are interested in and building social app?
27 | - Learn to build a news feed
28 | - Learn to build a prototype for a messenger app
29 | - building anything practical is the best way to prepare for social app companies ie, Facebook, NextDoor, etc.
30 | - `PICK THE RIGHT OPPORTUNITY` IS IMPORTANT
31 | - invest in yourself
32 | - find a role that matches your passion
33 | - invest in your network
34 | - where you start can impact and determine where you finish
35 | - WHERE IS YOUR `EXCITEMENT` AND WHERE CAN YOU `PUT YOUR ENERGY IN THE WORLD`?
36 | - `FINDING YOUR PURPOSE IN LIFE`
37 | - you can then lead with purpose and be on the driver seat
38 | - authenticity will show when you are doing what you like the most
39 | - Look into your `Ikigai` - key part of ikigai requires a concrete action that leads you closer to the meaningful goal to you. Everyone is different, so `what is your purpose in life? what do you want to do in your next role?`
40 |
41 |
42 | ## Formation Day - 10/01/2022
43 |
44 | Attended 4 events at Formation:
45 | (1) Engineering Method with Daniel
46 | (2) Algo Studio with Daniel
47 | (3) Algo Studio Session with Jeremy and Sophie
48 | (4) Algo Code Drill Session with Sophie
49 |
50 | Really helpful and knowledgable sessions. Even though I still need to work on my speed in understanding a problem and be able to fully understand what it means and what it is about.
51 |
52 | Takeaways:
53 | - Ask relevant questions to the problem
54 | - Take the time to explore the problem
55 | - Make sure to document down my high level understanding in plain English and not in Code
56 | - Make sure to fully understood the problem and make sure to have an insight on all the possible test cases (happy and edge cases) as well as knowing the input and output of the problem
57 | - It is okay in the interview that the interviewer has helped you. It would be great if you could solve the problem on your own through communicating with the interviewer, but if the interviewer can sense that you are stuck, a good intervewer will step in to make sure you can learn something from the session and able to give more guidance.
--------------------------------------------------------------------------------