├── .gitignore ├── LinkedLists ├── practice-solutions │ └── lru-cache-iamebonyhope.cs └── readme.md ├── recursion ├── practice-solutions │ ├── fibonacci-number-iamebonyhope.cs │ └── n-th-tribonacci-number-beginner-breakout-room.txt └── readme.md ├── stacks-and-queues ├── practice-solutions │ ├── min-stack-iamebonyhope.cs │ ├── minstack_jeans212.py │ ├── number-of-students-unable-to-eat-lunch-tobe.cs │ ├── basic-calculator-ii-intermediate-breakout-room.txt │ ├── implement-queue-using-stacks-rotimidokun.js │ └── valid-parentheses-beginner-breakout-room.txt └── readme.md ├── sorting-and-searching ├── practice-solutions │ ├── sort-colors-iamebonyhope.cs │ ├── selection-sort-implementation-ajoseaishat.py │ ├── insertion-sort-implementation-ajoseaishat.py │ ├── first-bad-version-iamebonyhope.cs │ └── merge-sort-implementation-ajoseaishat.py └── readme.md ├── strings-and-arrays ├── practice-solutions │ ├── string-compression-iamebonyhope.cs │ ├── maximum-subarray-barkty.js │ ├── reverse-string-barkty.cs │ ├── plus-one-rotimidokun.js │ ├── reverse-string-lordsolid.java │ ├── reverse-string-barkty.js │ ├── plus-one-lordsolid.java │ ├── container-with-most-water-lordsolid.java │ ├── implement-strstr-barkty.js │ ├── plus-one-barkty.js │ └── string-compression-lordsolid.java ├── Strings and Arrays.pdf └── readme.md ├── hash-tables ├── practice-solutions │ ├── check-if-array-pairs-are-divisible-by-k-iamebonyhope.cs │ ├── group-anagrams-iamebonyhope.cs │ ├── jewels-and-stones-barkty.js │ ├── intersection-of-two-arrays-barkty.js │ ├── two-sum-barkty.js │ ├── find-lucky-integer-in-an-array-barkty.js │ ├── intersection-of-two-arrays-ii-barkty.js │ ├── happy-number-barkty.js │ ├── two-sum-beginner-breakout-room-1.txt │ ├── two-sum-beginner-breakout-room-2.txt │ ├── two-sums-hash-map-arrays-katialagesantos.java │ ├── two-sums-katialagesantos.java │ └── group-anagrams-intermediate-breakout-room.txt └── readme.md ├── getting-started ├── Getting Started.pdf ├── practice-solutions │ └── first-bad-version-iamebonyhope.cs └── readme.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | 3 | .vs/ 4 | 5 | .iml 6 | -------------------------------------------------------------------------------- /LinkedLists/practice-solutions/lru-cache-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /recursion/practice-solutions/fibonacci-number-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /stacks-and-queues/practice-solutions/min-stack-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | ### 2 | -------------------------------------------------------------------------------- /sorting-and-searching/practice-solutions/sort-colors-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | ### 2 | -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/string-compression-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | // Sample file 2 | -------------------------------------------------------------------------------- /hash-tables/practice-solutions/check-if-array-pairs-are-divisible-by-k-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | sample file 2 | -------------------------------------------------------------------------------- /hash-tables/practice-solutions/group-anagrams-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | } 4 | -------------------------------------------------------------------------------- /getting-started/Getting Started.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wwcodelagos/algorithm-and-datastructures-series/HEAD/getting-started/Getting Started.pdf -------------------------------------------------------------------------------- /strings-and-arrays/Strings and Arrays.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wwcodelagos/algorithm-and-datastructures-series/HEAD/strings-and-arrays/Strings and Arrays.pdf -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/maximum-subarray-barkty.js: -------------------------------------------------------------------------------- 1 | var maxSubArray = function(nums) { 2 | let max = -Infinity 3 | let currentMax = -Infinity 4 | for (let i = 0; i < nums.length; i++) { 5 | currentMax = Math.max( 6 | currentMax + nums[i], 7 | nums[i], 8 | ) 9 | max = Math.max(max, currentMax) 10 | } 11 | return max 12 | }; -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/reverse-string-barkty.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public void ReverseString(char[] s) 4 | { 5 | int start = 0; 6 | int end = s.Length; 7 | int length = s.Length - 1; 8 | for(int i = 0; i < length / 2; i++) { 9 | if(start == s.Length / 2) 10 | var temp = s[start]; 11 | s[start] = arr[end]; 12 | s[end] = temp; 13 | 14 | start++; 15 | end-- 16 | }; 17 | Console.WriteLine(s); 18 | } 19 | } -------------------------------------------------------------------------------- /stacks-and-queues/practice-solutions/minstack_jeans212.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | self.stack = [] 5 | 6 | def push(self, val: int) -> None: 7 | self.stack.append(val) 8 | 9 | def pop(self) -> None: 10 | self.stack.pop() 11 | 12 | def top(self) -> int: 13 | return self.stack[-1] 14 | 15 | def getMin(self) -> int: 16 | return min(self.stack) 17 | 18 | 19 | # Your MinStack object will be instantiated and called as such: 20 | # obj = MinStack() 21 | # obj.push(val) 22 | # obj.pop() 23 | # param_3 = obj.top() 24 | # param_4 = obj.getMin() 25 | -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/plus-one-rotimidokun.js: -------------------------------------------------------------------------------- 1 | //Leetcode 66. 2 | //Solved using Javascript. 3 | 4 | var plusOne = function(digits) { 5 | //Join the items in the array. Remember to let the computer know, it is a type //of Number so it can be incremented by 1 6 | const joinNumbers = Number(digits.join("")); 7 | 8 | // Increment the result numbers by 1 9 | const incrementNumber = joinNumbers + 1; 10 | 11 | // convert back to string, and split to an array of items. Split method work on //strings. 12 | const splitNumbers = incrementNumber.toString().split(""); 13 | 14 | // return result 15 | return splitNumbers; 16 | }; 17 | -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/reverse-string-lordsolid.java: -------------------------------------------------------------------------------- 1 | //Time complexity: O(n) 2 | //Space complexity: O(1) 3 | 4 | //using two pointers approach and recursion 5 | //you can use iteration but start and end will end up at the middle 6 | public void reverseString(char[] s) { 7 | int start = 0; 8 | int end = s.length - 1; 9 | reversed(s, start, end); 10 | } 11 | 12 | public void reversed(char[] c, int start, int end){ 13 | 14 | if(start == c.length / 2) return; //base case 15 | 16 | //swap the items at the both indices 17 | char temp = c[start]; 18 | c[start] = c[end]; 19 | c[end] = temp; 20 | 21 | start++; 22 | end--; 23 | 24 | reversed(c, start, end); //recurse for the rest. 25 | } -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/reverse-string-barkty.js: -------------------------------------------------------------------------------- 1 | var reverseString = function(s) { 2 | // Brute force 3 | let temp; 4 | let reversedArray = [] 5 | for(let i = s.length; i > 0; i--) { 6 | temp = s.pop(s[i]) 7 | reversedArray.push(temp) 8 | } 9 | return reversedArray; 10 | } 11 | 12 | //Optimized solution using two-pointer approach 13 | function reversed(arr, start, end) { 14 | let end = arr.length - 1; 15 | let len = arr.length - 1; 16 | for (let i = 0; i < len / 2; i++) { 17 | //base case 18 | if(start == arr.length / 2) { 19 | return; 20 | } else { 21 | //swap items at both indices 22 | let temp = arr[start]; 23 | arr[start] = arr[end]; 24 | arr[end] = temp; 25 | 26 | start++; 27 | end-- 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /sorting-and-searching/practice-solutions/selection-sort-implementation-ajoseaishat.py: -------------------------------------------------------------------------------- 1 | # Time complexity(Average, Best and Worst case) = 0(n^2) 2 | 3 | def selection_sort(array): 4 | 5 | n = len(array) 6 | 7 | for i in range(n): 8 | min_index = i 9 | 10 | for j in range(i+1, n): 11 | # loop through the rest if the array to find the new min_index if there is a number lower than array[i] 12 | if(array[j] < array[min_index]): 13 | min_index = j 14 | 15 | # once we have gotten the minimum number in the unsorted array, we move to the correct position 16 | array[min_index], array[i] = array[i], array[min_index] 17 | 18 | return array 19 | 20 | 21 | test_array = [3, 0, 6, 1, 8, 9, -2] 22 | res = selection_sort(array= test_array) 23 | print(res) -------------------------------------------------------------------------------- /hash-tables/practice-solutions/jewels-and-stones-barkty.js: -------------------------------------------------------------------------------- 1 | var numJewelsInStones = function(jewels, stones) { 2 | //Set the counter 3 | let counter = 0; 4 | 5 | stones.split('').forEach(element => { 6 | jewels.indexOf(element) >= 0 ? counter++ : counter 7 | }); 8 | 9 | console.log(counter); 10 | 11 | 12 | // ?////////////////////////////////////// 13 | let stoneHash = { 14 | substring1: numberOfOccurrences 15 | }; 16 | 17 | const stone = stones.split(''); 18 | 19 | stone.forEach(element => { 20 | if(!stoneHash[element] || stoneHash[element] === 0) { 21 | stoneHash[element] = 1 22 | } 23 | stoneHash[element] = stoneHash[element] ++ 24 | }); 25 | 26 | console.log(stoneHash) 27 | return counter; 28 | }; 29 | 30 | numJewelsInStones('sss', 'seDftrssdetr'); -------------------------------------------------------------------------------- /hash-tables/practice-solutions/intersection-of-two-arrays-barkty.js: -------------------------------------------------------------------------------- 1 | var intersect = function(nums1, nums2) { 2 | const obj = {} 3 | const result =[] 4 | 5 | //Convert array to hashtable 6 | for(let i = 0; i < nums1.length; i++) { 7 | obj[nums1[i]] = obj[nums1[i]] + 1 || 1 8 | 9 | } 10 | 11 | //Loop through the second array 12 | for(let i = 0; i < nums2.length; i++) { 13 | //Check if the current array element exists in the hashtable 14 | if(obj[nums2[i]] !== undefined) { 15 | for(key in obj) { 16 | //Get the key of object 17 | if(obj[key] == obj[nums2[i]]) { 18 | //Convert to number and push to array 19 | result.push(key * 1) 20 | } 21 | } 22 | } 23 | } 24 | console.log(result) 25 | }; 26 | 27 | intersect() -------------------------------------------------------------------------------- /hash-tables/practice-solutions/two-sum-barkty.js: -------------------------------------------------------------------------------- 1 | var twoSum = function(nums, target) { 2 | let hashSum = {} 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | let difference = target - nums[i] 6 | 7 | if(hashSum[difference] || hashSum[difference] === 0) { 8 | console.log([hashSum[difference], i]) 9 | return [hashSum[difference], i] 10 | } else { 11 | hashSum[nums[i]] = i 12 | } 13 | 14 | } 15 | console.log(hashSum) 16 | 17 | // let seen = {} 18 | 19 | // for(let i = 0; i < nums.length; i++){ 20 | // let num2 = target - nums[i] 21 | // if(seen[num2] || seen[num2] === 0){ 22 | // console.log([seen[num2],i]) 23 | // return [seen[num2],i] 24 | // } else { 25 | // seen[nums[i]] = i 26 | // } 27 | // } 28 | }; 29 | 30 | twoSum([2,7,11,15], 9) 31 | twoSum([3,2,4], 6) 32 | twoSum([3,3], 6) -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/plus-one-lordsolid.java: -------------------------------------------------------------------------------- 1 | //Time complexity: O(n) 2 | //Space complexity: O(1) 3 | 4 | 5 | public int[] plusOne(int[] digits){ 6 | int n = digits.length; 7 | 8 | if(digits[n-1] != 9){ //if the last value is not 9 just add 1 to it and return the array 9 | digits[n-1] += 1; 10 | return digits; 11 | } 12 | 13 | 14 | //if that is not the case: 15 | int carry = 1; //variable to hold our carry value 16 | int sum = 0; //variable to hold sum 17 | 18 | for(int i = n-1; i >= 0; i--){ 19 | sum = digits[i] + carry; // add 1 to the last digit 20 | digits[i] = sum % 10; //get the last digit of the sum that will reside in that index 21 | carry = sum / 10; // update carry and do same for rest of the loop 22 | } 23 | 24 | if(carry > 0){ //we still have a value to carry over so create a new array to accomodate it 25 | digits = new int[n + 1]; 26 | digits[0] = 1; 27 | return digits; 28 | } 29 | } -------------------------------------------------------------------------------- /stacks-and-queues/practice-solutions/number-of-students-unable-to-eat-lunch-tobe.cs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countStudents(int[] students, int[] sandwiches) { 3 | int length = students.length; 4 | int sandPoint = 0; 5 | 6 | int sandWichSum = 0; 7 | 8 | Queue studs = new LinkedList(); 9 | 10 | for(int n : students){ 11 | studs.add(n); 12 | 13 | } 14 | 15 | 16 | while(!studs.isEmpty() && sandWichSum != studs.size()){ 17 | if(studs.peek() == sandwiches[sandPoint]){ 18 | studs.poll(); 19 | sandWichSum = 0; 20 | 21 | sandPoint++; 22 | 23 | }else{ 24 | int person = studs.remove(); 25 | studs.add(person); 26 | sandWichSum++; 27 | } 28 | 29 | length --; 30 | } 31 | 32 | return studs.size(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/container-with-most-water-lordsolid.java: -------------------------------------------------------------------------------- 1 | 2 | //Time complextiy = O(n) 3 | //Space complexity = O(1) 4 | 5 | //Using two pointer approach 6 | public int maxArea(int[] heights) { 7 | int left = 0; 8 | int right = heights.length - 1; 9 | int res = 0; //result variablle 10 | 11 | 12 | //Here we will calculate the area of each height conidering only the minimum height 13 | //then we record the highest area we have seen so far 14 | while(left < right){ 15 | int area = (right - left) * Math.min(heights[left], heights[right]); 16 | res = Math.max(res, area); //assign the maximum area so far, to the result variable 17 | 18 | if(heights[left] < heights[right]){ //if we have lesser height in the left, increment to find more less from left 19 | left++; 20 | }else if(heights[right] < heights[left]){ //if we have lesser in right, decrement to find more less from right 21 | right--; 22 | }else{ //if equal we can decrement right or increment left it doesn't matter, both will still give the same value. 23 | right--; 24 | } 25 | } 26 | 27 | return res; 28 | } -------------------------------------------------------------------------------- /hash-tables/practice-solutions/find-lucky-integer-in-an-array-barkty.js: -------------------------------------------------------------------------------- 1 | const findLucky = function(arr) { 2 | // let lucky = []; 3 | // let temp = 0 4 | // for(let i = 0; i < arr.length; i++) { 5 | // temp = arr[i] 6 | // for(let j = 1; j < arr.length; j++) { 7 | // if(arr[j] === temp) { 8 | // lucky.push(arr[j]) 9 | // } 10 | // } 11 | // // lucky.push(temp) 12 | // } 13 | // console.log(lucky); 14 | 15 | 16 | let lucky = [-1]; 17 | let hashObj = {}; 18 | 19 | for (let num of arr) { 20 | hashObj[num] ? hashObj[num] += 1 : hashObj[num] = 1; 21 | } 22 | 23 | let nums = Object.keys(hashObj); 24 | let frequencies = Object.values(hashObj); 25 | 26 | for (let num in nums) { 27 | if (nums[num] == frequencies[num]) { 28 | lucky.push(frequencies[num]); 29 | } 30 | } 31 | 32 | if (lucky.length === 1) { 33 | console.log(lucky) 34 | return lucky; 35 | } else { 36 | console.log(Math.max(...lucky)) 37 | return Math.max(...lucky); 38 | } 39 | }; 40 | 41 | findLucky([2,2,3,4]) 42 | findLucky([1,2,2,3,3,3]) -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/implement-strstr-barkty.js: -------------------------------------------------------------------------------- 1 | var strStr = function(haystack, needle) { 2 | //Brute force 3 | if (needle === '') { 4 | console.log(0); 5 | return 0; 6 | } else if(haystack.includes(needle)) { 7 | let index = haystack.indexOf(needle) 8 | console.log(index) 9 | return index; 10 | } 11 | console.log(-1); 12 | //return -1; 13 | 14 | //Optimized 15 | //Time Complexity O(n) 16 | 17 | if (needle === '') { 18 | return 0; 19 | } 20 | const map = {} 21 | const len = needle.length 22 | for(let i = 0; i < len; i++) { 23 | map[needle[i]] = i 24 | } 25 | let j = 0 26 | for(let i = 0; i < haystack.length;) { 27 | if (haystack[i + j] == needle[j]) { 28 | if (j == len - 1) { 29 | return i; 30 | } 31 | j++; 32 | } else { 33 | let index = map[haystack[i + len]] 34 | if(index === undefined) { 35 | i += len + 1 36 | } else { 37 | i += len - index 38 | } 39 | j = 0 40 | } 41 | } 42 | return -1 43 | }; -------------------------------------------------------------------------------- /sorting-and-searching/practice-solutions/insertion-sort-implementation-ajoseaishat.py: -------------------------------------------------------------------------------- 1 | # Time complexity(Average and Worst case) = 0(n^2) 2 | # Time Complexity(Best case) = 0(n) : When the array to be sorted is already sorted 3 | 4 | def insertion_sort(array): 5 | 6 | n = len(array) 7 | 8 | # loop through the array to place each element in the correct position starting from 9 | # the second element because there is nothing to compare the first element to 10 | for i in range(1, n): 11 | # curr_elem is the number we want to place in the right position 12 | curr_num = array[i] 13 | 14 | # j is the index of the element before curr_elem and also where we start comparing from 15 | j = i -1 16 | 17 | while (j >= 0 and curr_num < array[j]): 18 | # we move the bigger number to the right and decrement our j to compare curr_num with the next number 19 | array[j+1] = array[j] 20 | j = j-1 21 | 22 | # place curr_num in the right position 23 | array[j+1] = curr_num 24 | 25 | return array 26 | 27 | 28 | test_array = [3, 0, 6, 1, 8, 9] 29 | res = insertion_sort(array= test_array) 30 | print(res) -------------------------------------------------------------------------------- /hash-tables/practice-solutions/intersection-of-two-arrays-ii-barkty.js: -------------------------------------------------------------------------------- 1 | //Brute force 2 | 3 | var intersection = function(nums1, nums2) { 4 | const obj = {} 5 | const result = [] 6 | 7 | //Convert array to hashtable 8 | for(let i = 0; i < nums1.length; i++) { 9 | obj[nums1[i]] = obj[nums1[i]] + 1 || 1 10 | 11 | } 12 | 13 | //Loop through the second array 14 | for(let i = 0; i < nums2.length; i++) { 15 | //Check if the current array element exists in the hashtable 16 | if(obj[nums2[i]] !== undefined) { 17 | for(key in obj) { 18 | //Get the key of object 19 | if(obj[key] == obj[nums2[i]]) { 20 | //Convert to number and push to array 21 | result.push(key * 1) 22 | } 23 | } 24 | } 25 | for (let x = 0; x < result.length; x++) { 26 | for (var j = 0; j < result.length; j++) { 27 | if (x != j) { 28 | if(result[x] == result[j]) { 29 | result.pop(x) 30 | } 31 | } 32 | } 33 | } 34 | } 35 | return result; 36 | }; -------------------------------------------------------------------------------- /stacks-and-queues/practice-solutions/basic-calculator-ii-intermediate-breakout-room.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | //"3+2*2" -> stack: 3, 4 4 | public int calculate(String s) { 5 | Stack stack = new Stack<>(); 6 | 7 | int currNum = 0; 8 | char operand = '+'; 9 | int res = 0; 10 | 11 | for(int i = 0; i < s.length(); i++){ 12 | 13 | Character ch = s.charAt(i); 14 | 15 | if (Character.isDigit(ch)) { 16 | currNum *= 10; 17 | currNum += ch - '0'; 18 | //currNum = Integer.parseInt(ch.toString()); 19 | } 20 | 21 | if((!Character.isDigit(ch) && ch != ' ') || i == s.length() - 1) { 22 | if(operand == '+'){ 23 | stack.push(currNum); 24 | }else if(operand == '-'){ 25 | stack.push(-currNum); 26 | }else if(operand == '*'){ 27 | stack.push(stack.pop() * currNum); 28 | }else if(operand == '/'){ 29 | stack.push(stack.pop() / currNum); 30 | } 31 | 32 | currNum = 0; 33 | operand = ch; 34 | } 35 | } 36 | 37 | while(!stack.isEmpty()){ 38 | res += stack.pop(); 39 | } 40 | 41 | return res; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /LinkedLists/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Practice Questions 4 | 5 | ### Beginner 6 | 7 | [https://leetcode.com/problems/reverse-linked-list/](https://leetcode.com/problems/reverse-linked-list/) 8 | 9 | [https://leetcode.com/problems/linked-list-cycle/](https://leetcode.com/problems/linked-list-cycle/) 10 | 11 | [https://leetcode.com/problems/intersection-of-two-linked-lists/](https://leetcode.com/problems/intersection-of-two-linked-lists/) 12 | 13 | [https://leetcode.com/problems/delete-node-in-a-linked-list/](https://leetcode.com/problems/delete-node-in-a-linked-list/) 14 | 15 | 16 | ## Intermediate 17 | 18 | [https://leetcode.com/problems/add-two-numbers/](https://leetcode.com/problems/add-two-numbers/) 19 | 20 | [https://leetcode.com/problems/lru-cache/](https://leetcode.com/problems/lru-cache/) 21 | 22 |
23 |
24 | 25 | ## Resources 26 | [Linked List Data Structure | Interview Cake](https://www.interviewcake.com/concept/python/linked-list) 27 | 28 | [Linked List | Leetcode Explore](https://leetcode.com/explore/learn/card/linked-list/) 29 | 30 | [Linked List Basics](https://github.com/rogue0137/practice/blob/master/data_structure_info/linked_lists/linked_lists.md) 31 | 32 | [Linked List Introduction | CSDojo](https://github.com/rogue0137/practice/blob/master/data_structure_info/linked_lists/linked_lists.md) 33 | -------------------------------------------------------------------------------- /getting-started/practice-solutions/first-bad-version-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | // Time Complexity: O(log n) 2 | // Space Complexity: O(1) 3 | 4 | 5 | public class Solution : VersionControl { 6 | public int FirstBadVersion(int n) 7 | { 8 | // had to use long else I ll get overflow with (2126753390 + 1702766719)/2 9 | 10 | long start = 1; 11 | long end = n; 12 | 13 | while (start <= end) 14 | { 15 | long mid = (start + end) / 2; 16 | 17 | if (IsBadVersion((int)mid)) // then first bad version is between current start and mid 18 | { 19 | if (!IsBadVersion((int)(mid - 1))) // if the previous version before mid is good, then mid is the first bad 20 | { 21 | return (int)mid; 22 | } 23 | 24 | end = mid - 1; 25 | } 26 | else // then first bad version is between current mid and end 27 | { 28 | if (IsBadVersion((int)(mid + 1))) // if the next version after mid is bad, then that is the first bad 29 | { 30 | return (int)(mid + 1); 31 | } 32 | 33 | start = mid + 1; 34 | } 35 | } 36 | 37 | return (int)start; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /hash-tables/practice-solutions/happy-number-barkty.js: -------------------------------------------------------------------------------- 1 | //Brute force 2 | 3 | var isHappy = function(n) { 4 | //Check if integer is equal to 1 5 | if(n === 1) { 6 | console.log(true) 7 | return true; 8 | } else if(n !== 1 && n >= 7) { 9 | //Check if integer has two or more digits 10 | 11 | //Convert it to a string and split 12 | const splits = n.toString().split('') 13 | //Declare an empty array variable 14 | let integer = []; 15 | let powered = [] 16 | let sum = 0; 17 | //Loop and convert array values to numbers 18 | for(let i = 0; i < splits.length; i++){ 19 | integer.push(Number(splits[i])) 20 | } 21 | console.log(integer) 22 | 23 | //Square each digits 24 | for (let j = 0; j < integer.length; j++) { 25 | powered.push(Math.pow(integer[j], 2)) 26 | } 27 | console.log(powered) 28 | 29 | //Sum each integer in the array 30 | for(let s = 0; s < powered.length; s++) { 31 | sum += powered[s] 32 | } 33 | console.log(sum); 34 | 35 | //Recursion 36 | return isHappy(sum) 37 | } 38 | 39 | return false 40 | 41 | }; 42 | isHappy(10) 43 | isHappy(19) 44 | isHappy(25) 45 | isHappy(7) 46 | isHappy(5) 47 | -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/plus-one-barkty.js: -------------------------------------------------------------------------------- 1 | var plusOne = function(digits) { 2 | //Brute force 3 | 4 | //Get the last number in the array 5 | let number = Number(digits.join('')); 6 | number += 1; 7 | let integer = number.toString().split(''); 8 | 9 | let integerArray = []; 10 | integer.map(x => integerArray.push(Number(x))) 11 | console.log(integerArray); 12 | return integerArray; 13 | } 14 | 15 | var plusOneO = function(digits) { 16 | //Optimized version 17 | 18 | // 1. reverse array 19 | // 2. add 1, check if < 10 20 | // a3. <10 - reverse array back and return 21 | // b3. >10 - replace element with result%10 22 | // b4. add one to next element and repeat actions 23 | 24 | let rev = digits.reverse(); 25 | let i = 0; 26 | 27 | function add(arr, i) { 28 | // debugger 29 | // if (arr[i]+1) { 30 | if (i !== arr.length) { 31 | if (arr[i] + 1 > 9) { 32 | arr[i] = (arr[i] + 1) % 10; 33 | i++ 34 | add(arr, i) 35 | } else { 36 | arr[i] = arr[i] + 1 37 | } 38 | } else { 39 | arr.push(1) 40 | } 41 | } 42 | 43 | add(rev, i) 44 | console.log(rev.reverse()); 45 | return rev.reverse(); 46 | } 47 | plusOne([1, 2, 3, 6, 9, 7, 8, 9]); 48 | plusOne([7, 1, 6, 1, 2, 3]) 49 | plusOneO([9, 9]) 50 | plusOneO([1, 9]) 51 | plusOneO([2, 4]) 52 | -------------------------------------------------------------------------------- /strings-and-arrays/practice-solutions/string-compression-lordsolid.java: -------------------------------------------------------------------------------- 1 | 2 | // Time Complexity: O(n) 3 | // Space Complexity: O(1) 4 | 5 | 6 | public int compress(char[]chars){ 7 | // prevent NPE and empy array processing 8 | if(chars==null||chars.length==0) return 0; 9 | 10 | // Since sb.length is never > than chars.length, required space is known 11 | StringBuilder sb=new StringBuilder(chars.length); 12 | 13 | 14 | // using two pointers algo 15 | int i = 0,j = 1; 16 | while(i < chars.length || j < chars.length){ 17 | //if the values i and j indices are equal, keep moving the j pointer 18 | //till the values don't match. 19 | if(j < chars.length && chars[i] == chars[j]) { 20 | j++; 21 | }else{ //found values that don't match 22 | if(j - i == 1){ //check if group length is 1 & append single character 23 | sb.append(chars[i]); 24 | }else sb.append(chars[i]).append(j-i); //else append the character and the group length 25 | i = j; j++; //sset i to j index and increment j 26 | } 27 | } 28 | 29 | // modify chars populating it with characters from sb 30 | i = 0; 31 | while(i < sb.length()){ 32 | chars[i++] = sb.charAt(i); 33 | } 34 | 35 | return sb.length(); //length of the string is the length of the result array 36 | } -------------------------------------------------------------------------------- /sorting-and-searching/practice-solutions/first-bad-version-iamebonyhope.cs: -------------------------------------------------------------------------------- 1 | /* The isBadVersion API is defined in the parent class VersionControl. 2 | bool IsBadVersion(int version); */ 3 | 4 | // Time Complexity: O(log n) 5 | // Space Complexity: O(1) 6 | 7 | 8 | public class Solution : VersionControl { 9 | public int FirstBadVersion(int n) 10 | { 11 | // had to use long else I ll get overflow with (2126753390 + 1702766719)/2 12 | 13 | long start = 1; 14 | long end = n; 15 | 16 | while (start <= end) 17 | { 18 | long mid = (start + end) / 2; 19 | 20 | if (IsBadVersion((int)mid)) // then first bad version is between current start and mid 21 | { 22 | if (!IsBadVersion((int)(mid - 1))) // if the previous version before mid is good, then mid is the first bad 23 | { 24 | return (int)mid; 25 | } 26 | 27 | end = mid - 1; 28 | } 29 | else // then first bad version is between current mid and end 30 | { 31 | if (IsBadVersion((int)(mid + 1))) // if the next version after mid is bad, then that is the first bad 32 | { 33 | return (int)(mid + 1); 34 | } 35 | 36 | start = mid + 1; 37 | } 38 | } 39 | 40 | return (int)start; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /recursion/readme.md: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | [Recorded meetup session](https://www.youtube.com/watch?v=Rw_Hus65dLY&t=68s) 5 | 6 |
7 |
8 | 9 | 10 | ## Practice Questions 11 | 12 | ### Beginner 13 | 14 | [https://leetcode.com/problems/n-th-tribonacci-number/](https://leetcode.com/problems/n-th-tribonacci-number/) 15 | 16 | [https://www.hackerrank.com/challenges/recursive-digit-sum/problem?isFullScreen=true](https://www.hackerrank.com/challenges/recursive-digit-sum/problem?isFullScreen=true) 17 | 18 | [https://leetcode.com/problems/fibonacci-number/](https://leetcode.com/problems/fibonacci-number/) 19 | 20 |
21 | 22 | ## Intermediate 23 | 24 | [https://leetcode.com/problems/k-th-symbol-in-grammar/](https://leetcode.com/problems/k-th-symbol-in-grammar/) 25 | 26 | [https://leetcode.com/problems/valid-tic-tac-toe-state/](https://leetcode.com/problems/valid-tic-tac-toe-state/) 27 | 28 | [https://leetcode.com/problems/word-break/](https://leetcode.com/problems/word-break/) 29 | 30 |
31 |
32 | 33 | 34 | ## Resources 35 | 36 | [https://leetcode.com/explore/learn/card/recursion-i/](https://leetcode.com/explore/learn/card/recursion-i/) 37 | 38 | [https://leetcode.com/explore/learn/card/recursion-ii/](https://leetcode.com/explore/learn/card/recursion-ii/) 39 | 40 | [https://www.byte-by-byte.com/recursion/](https://www.byte-by-byte.com/recursion/) 41 | 42 | [Recursion on Khan Academy](https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursion) 43 | 44 | [https://www.programiz.com/python-programming/recursion](https://www.programiz.com/python-programming/recursion) 45 | -------------------------------------------------------------------------------- /sorting-and-searching/practice-solutions/merge-sort-implementation-ajoseaishat.py: -------------------------------------------------------------------------------- 1 | # Time complexity(Average, Best and Worst case) = 0(n^2) 2 | 3 | from operator import le 4 | from turtle import left, right 5 | 6 | 7 | def merge_sort(array): 8 | 9 | # recursively didvide your list into 2 equal parts until each part has one or zero number(s) 10 | if(len(array) <= 1): 11 | return array 12 | 13 | # get the middle point of the array 14 | n = len(array) 15 | mid_point = n//2 16 | 17 | left_array = array[:mid_point] 18 | right_array = array[mid_point:] 19 | 20 | # recursively run the merge sort on left and right array 21 | left_array = merge_sort(left_array) 22 | right_array = merge_sort(right_array) 23 | 24 | return merge_list(left_array, right_array) 25 | 26 | 27 | 28 | def merge_list(left_array, right_array): 29 | # This is used to join the splitted array back to the original array in sorted form 30 | 31 | res = [] 32 | n = len(left_array) 33 | m = len(right_array) 34 | 35 | 36 | while(len(left_array) > 0 and len(right_array) > 0): 37 | if(left_array[0] < right_array[0]): 38 | res.append(left_array[0]) 39 | left_array.remove(left_array[0]) 40 | 41 | else: 42 | res.append(right_array[0]) 43 | right_array.remove(right_array[0]) 44 | 45 | 46 | 47 | if(len(left_array) == 0): 48 | res = res + right_array 49 | else: 50 | res = res + left_array 51 | 52 | return res 53 | 54 | 55 | 56 | test_array = [3, 0, 6, -5, 1, 8, 9, -2] 57 | res = merge_sort(array= test_array) 58 | print(res) -------------------------------------------------------------------------------- /hash-tables/practice-solutions/two-sum-beginner-breakout-room-1.txt: -------------------------------------------------------------------------------- 1 | # python 2 | dict or {} 3 | records = dict() 4 | records = {} 5 | 6 | # C# 7 | records = new Dictionary() 8 | 9 | # java 10 | HashMap() 11 | records = new HashMap() 12 | 13 | # javascript 14 | records = new Object() 15 | records = {} 16 | 17 | class Solution: 18 | def twoSum(self, nums: List[int], target: int) -> List[int]: 19 | seen = {} 20 | 21 | for j in range(len(nums)): 22 | difference = target - nums[j] 23 | 24 | if(difference in seen): 25 | return [seen[difference], j] 26 | 27 | seen[difference] = j 28 | 29 | 30 | # two for-loops - python 31 | nums = [2,7,11,15] 32 | target = 9 33 | len(nums) = 4 34 | 35 | range(start, end, increment) start, start+increment ..... end-1 36 | range(end) -> start = 0, increment = 1 37 | 38 | range(4) -> 0,1,2,3 39 | 40 | i = 0 41 | a = nums[i] = 2 42 | j = 1 43 | b = 7 44 | 45 | a + b = 2 + 7 = 9 46 | 47 | [i,j] = [0, 1] 48 | 49 | for i in range(len(nums)): 50 | a = nums[i] 51 | for j in range(i + 1, len(nums)): 52 | b = nums[j] 53 | if a + b == target: 54 | return [i,j] 55 | 56 | 57 | class Solution: 58 | def findLucky(self, arr: List[int]) -> int: 59 | for i in range(len(arr)): 60 | count = 1 61 | value = arr[i] 62 | for j in range(i+1,len(arr)): 63 | if value == arr[j]: 64 | count = count + 1 65 | if count == value: 66 | return value 67 | return -1 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /stacks-and-queues/practice-solutions/implement-queue-using-stacks-rotimidokun.js: -------------------------------------------------------------------------------- 1 | //Leetcode 232. 2 | //Solved using two stacks. 3 | //Solved using Javascript classes. 4 | //Amortized Time complexity 0(1) - constant. Worst case - 0(n), but happens once during pop/peek operation. 5 | //Space Complexity 0(n) - linear. As we add more inputs, we have to create more space. 6 | 7 | class MyQueue { 8 | constructor() { 9 | //create two stacks, one for pushing, one for popping. 10 | this.pushStack = [] 11 | this.popStack = [] 12 | } 13 | 14 | //push to the push stack 15 | push(val) { 16 | this.pushStack.push(val) 17 | } 18 | 19 | //if nothing in the pop stack and something in the pushstack, push into the empty pop stack what you pop from the push stack. 20 | pop() { 21 | if(!this.popStack.length) { 22 | while(this.pushStack.length){ 23 | this.popStack.push(this.pushStack.pop()) 24 | } 25 | } 26 | //pop from the pop stack which is no longer empty 27 | return this.popStack.pop() 28 | } 29 | 30 | //if nothing in the pop stack and something in the pushstack, push into the empty pop stack what you pop from the push stack. 31 | peek() { 32 | if(!this.popStack.length) { 33 | while(this.pushStack.length){ 34 | this.popStack.push(this.pushStack.pop()) 35 | } 36 | } 37 | //return the last item in the pop stack which is no longer empty 38 | return this.popStack[this.popStack.length - 1] 39 | } 40 | 41 | //if both stacks are empty, return true, else false 42 | empty() { 43 | if(!this.pushStack.length && !this.popStack.length) { 44 | return true 45 | } 46 | return false 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /hash-tables/practice-solutions/two-sum-beginner-breakout-room-2.txt: -------------------------------------------------------------------------------- 1 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 2 | 3 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | 5 | You can return the answer in any order. 6 | 7 | Example 1: 8 | 9 | Input: nums = [3,2,15,7], target = 9 10 | Output: [0,1] 11 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 12 | Example 2: 13 | 14 | Input: nums = [3,2,4], target = 6 15 | Output: [1,2] 16 | Example 3: 17 | 18 | Input: nums = [3,3], target = 6 19 | Output: [0,1] 20 | 21 | 22 | //sophia 23 | //python 24 | class Solution: 25 | def twoSum(self,nums,target): 26 | numbers = {} 27 | for i in range(len(nums)): 28 | match = target - nums[i] 29 | if match in numbers: 30 | return [i, numbers[match]] 31 | numbers[nums[i]] = i 32 | 33 | input = [1,2,3,4] 34 | target = 5 35 | output = [1,2] 36 | time= O(n) 37 | space = O(n) 38 | 39 | 40 | 41 | 42 | 43 | 44 | // Dimeji 45 | For x,y in nums; 46 | if x + y = target, 47 | index = nums.index(x,y) 48 | Print (index) 49 | 50 | 51 | 52 | 53 | 54 | //Hope Chijuka brute force solution 55 | public int[] findSum(int[] array, int target) { //3,2,15,7 56 | for(int i = 0; i < array.length; i++) { 57 | for(int j = i+1; i < array.length; j++) { 58 | if(array[i] + array[j] == target) return new int[] {i, j}; 59 | } 60 | } 61 | return new int[0]; 62 | } 63 | public int[] findSumII(int[] array, int target) { 64 | HashSet set = new HashSet(); 65 | for(int i = 0; i < array.length; i++) { 66 | set.add(array[i]); 67 | if(set.contains(target - array[i])) 68 | return new int[] {set.get(target - array[i]), i}; 69 | } 70 | return new int[0]; 71 | } 72 | 73 | 74 | 75 | // Moses 76 | 77 | def calc(nums, tar): 78 | for 79 | 80 | -------------------------------------------------------------------------------- /getting-started/readme.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | This was a getting started session. Majorly going through what to expect from the series, what you want to achieve from it, how technical interviews work and finally a brief introduction on time and space complexity. 4 | 5 | Recorded session: [getting started youtube video](https://youtu.be/4UbPttU9kgE) 6 | 7 | Slides: [getting started slides](https://github.com/wwcodelagos/algorithm-and-datastructures-series/blob/main/getting-started/Getting%20Started.pdf) 8 | 9 |
10 | 11 | ## Major Highlights 12 | 13 | - Technical interview process 14 | - Problem solving process 15 | - Tips and tricks for technical interviews 16 | - Time and space complexity 17 | 18 |
19 | 20 | ## Resources on Time and Space Complexity: 21 | ### Videos 22 | 23 | - [Big O Notation, Gayle Laakmann McDowell](https://youtu.be/v4cd1O4zkGw) 24 | - [Introduction to Big-O, William Fiset](https://youtu.be/zUUkiEllHG0) 25 | 26 | ### Articles 27 | 28 | - [Asymptotic Notation, Khan Academy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) 29 | - [Big O Notation | Interview Cake](https://www.interviewcake.com/article/java/big-o-notation-time-and-space-complexity) 30 | - [Coding Interview Cheatsheet. Big O Notation | by Michael Verdi | Medium](https://medium.com/@verdi/coding-interview-cheatsheet-4c0676cd4a5c) 31 | - [A Beginner’s Guide to Big O Notation- Part 1](https://medium.com/better-programming/a-beginners-guide-to-big-o-notation-pt-1-19ec031b698b) 32 | - [A Beginner’s Guide to Big O Notation- Part 2](https://medium.com/swlh/a-beginners-guide-to-big-o-notation-part-2-c4ede76cea36) 33 | 34 |
35 | 36 | 37 | ## Practice Question 38 | 39 | [https://leetcode.com/problems/first-bad-version/](https://leetcode.com/problems/first-bad-version/) 40 | 41 | 42 |
43 |
44 | 45 | join us on slack [https://bit.ly/wwcodelagos-slack](https://bit.ly/wwcodelagos-slack) 46 | -------------------------------------------------------------------------------- /hash-tables/practice-solutions/two-sums-hash-map-arrays-katialagesantos.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | int[] indices = new int[2]; 4 | indices[0]=-1; 5 | indices[1]=-1; 6 | 7 | // map each num entry to a list containing the indices 8 | // of ocurrence in nums 9 | Map> numsMap = new HashMap(); 10 | for(int i=0; i< nums.length; i++){ 11 | Integer key = nums[i]; 12 | if(numsMap.get(key)!=null){ 13 | List indicesList = numsMap.get(key); 14 | indicesList.add(i); 15 | }else{ 16 | numsMap.put(key, Arrays.asList(i)); 17 | } 18 | } 19 | 20 | Integer[] numValues = numsMap.keySet().toArray(new Integer[0]); 21 | 22 | // verify if same num occur as many times as equal to target 23 | for(int i=0; i numIndices = (List) numsMap.get(numValue); 26 | int ocurrences = numIndices.size(); 27 | int sumTotalNum = numValue * ocurrences; 28 | if(ocurrences==2 && (sumTotalNum==target)){ 29 | indices[0]=numIndices.get(0); 30 | indices[1]=numIndices.get(1); 31 | } 32 | } 33 | 34 | if(indices[0]==-1){ 35 | for(int i=0; i> numsMap = new HashMap(); 10 | for(int i=0; i< nums.length; i++){ 11 | Integer key = nums[i]; 12 | if(numsMap.get(key)!=null){ 13 | List indicesList = numsMap.get(key); 14 | indicesList.add(i); 15 | }else{ 16 | List newList = new ArrayList(); 17 | newList.add(i); 18 | numsMap.put(key, newList); 19 | } 20 | } 21 | 22 | Integer[] numValues = numsMap.keySet().toArray(new Integer[0]); 23 | 24 | // verify if same num occur as many times as equal to target 25 | for(int i=0; i numIndices = (List) numsMap.get(numValue); 28 | int ocurrences = numIndices.size(); 29 | int sumTotalNum = numValue * ocurrences; 30 | if(ocurrences==2 && (sumTotalNum==target)){ 31 | indices[0]=numIndices.get(0); 32 | indices[1]=numIndices.get(1); 33 | } 34 | } 35 | 36 | if(indices[0]==-1){ 37 | for(int i=0; i [1,2,3,4] -> O(N =4)-> 1 x 3 -> N x K - O(NK) 7 | Output: [["bat"],["nat","tan"],["ate","eat","tea", “tea”]] 8 | 9 | Eat > e1a1t1 10 | 11 | 12 | Example 2: 13 | Input: strs = [""] 14 | Output: [[""]] 15 | 16 | 17 | Example 3: 18 | Input: strs = ["a", “b”, ab, ba] 19 | Output: [["a"], [“b”], [ab, ba]] 20 | 21 | 22 | To sort each word -> O(K * LogK) 23 | 24 | (Constant RT)O(1) -> (Linear RT)O(N) -> O(KN) -> (With sorting - Logarithmic RT)O(KLogK* N) -> O( K*N*N -1).... 25 | -> 26 | Constraints: 27 | * 1 <= strs.length <= 104 28 | * 0 <= strs[i].length <= 100 29 | * strs[i] consists of lowercase English letters. 30 | 31 | 32 | —-------------------------------- 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | ~, 41 | Input: strs = [“ananan”, “annna”, “ana”, “naa”, “bna”] 42 | 43 | Output str = [[ana, naa], [ananan], [annna], [bna]] 44 | 45 | 46 | —--- 47 | 48 | Input: strs = ["eat",“eatt”,"tea",”tea”,"tan","ate","nat","bat"] 49 | 50 | Dict = [ eat -> aet, tea -> aet] 51 | { 52 | “aet”: [eat, ] 53 | “Abt”: [bat] 54 | “Ant”: [nat, tan] 55 | 56 | } 57 | Return Dict.values() 58 | [...]-> [["bat"],["nat","tan"],["ate","eat","tea", “tea”]] 59 | 60 | —--------------- 61 | [a,b……z] -26 62 | a1e1t1 63 | 64 | Dict{ 65 | A -> 1 66 | . 67 | E -> 1 68 | . 69 | T -> 1 70 | z 71 | } 72 | 73 | [a,b,c,d,e,f,g,h,i,j,k,l, m,n,o,p,q,r,s,t,u,v,w] 74 | [1…………………1……………………………………………………1……………………… 1] 75 | Key ->a1e1t1 76 | 77 | 78 | 79 | Finding a more optimal way to create the keys without sorting 80 | 81 | 82 | For the word in array -> 83 | Fn::GetKey(word) -> K+26 84 | Dict = {a:, b:0,...z:0} 85 | Str = ‘’ 86 | For k in word: //O(K) 87 | Dict[k]++ 88 | For char in Dict.keys() //O(26) 89 | If(Dict[char]>0): 90 | Str = char + Dict[char] 91 | Return str 92 | -------------------------------------------------------------------------------- /recursion/practice-solutions/n-th-tribonacci-number-beginner-breakout-room.txt: -------------------------------------------------------------------------------- 1 | Hi everyone! 2 | 3 | Here is an example code of using memoization in Python 4 | 5 | class Solution: 6 | def __init__(self): 7 | self.mem = {} 8 | def tribonacci(self, n: int) -> int: 9 | return self.compute(n) 10 | 11 | def compute(self, n): 12 | if n in self.mem: 13 | return self.mem[n] 14 | 15 | if n == 0: 16 | self.mem[n] = 0 17 | elif n <= 2: 18 | self.mem[n] = 1 19 | else: 20 | self.mem[n] = self.compute(n-1) + self.compute(n-2) + self.compute(n-3) 21 | 22 | return self.mem[n] 23 | 24 | THANKS EVERYONE FOR JOINING! SEE YOU IN 2 WEEKS TIME 25 | 26 | 27 | 28 | i 29 | 30 | 31 | Gbemisola's solution 32 | First, check if the argument is 0 or 1 33 | Second create a variable to store the result 34 | Third, loop through the argument and return the result 35 | 36 | function tribonacci(n) { 37 | if(n === 0) return 0 38 | if(n === 1 || n === 2) return 1 39 | 40 | let result = 0 41 | for (let i = 0; i < n; i++) { 42 | 43 | // --- I think I am stuck here 44 | result += (i + (n-1) + (n - 2) + (n - 3)) 45 | } 46 | return result 47 | } 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | Modupe's Solution 62 | First I could create an array and put in the t0 till t3 i.e [T1, T2, T3] 63 | then I will compute for The remaining numbers up till Tn 64 | so something like 65 | Code: 66 | const newArray = [0,1,1] 67 | 68 | for (let i = 3; i <= n; i++){ 69 | newArray[i] = newArray[i-1] + newArray[i-2] + newArray[i-3] 70 | or better still 71 | newArray.push(newArray[i-1] + newArray[i-2] + newArray[i-3]) 72 | } 73 | 74 | return newArray[n] 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | //Damilola Solution with Iteration 86 | 87 | Since the Size can be determined i will use an Array Data Structure 88 | Then i would use for loop to iterate through the arrays 89 | My third step if 90 | 91 | if (n===0) 92 | return o 93 | if(n===1 or n===2) return 1 94 | else 95 | Add the first three numbers 96 | 97 | Then return result 98 | 99 | 100 | Time Complexity: O(n) 101 | 102 | 103 | -------------------------------------------------------------------------------- /sorting-and-searching/readme.md: -------------------------------------------------------------------------------- 1 | # Quick Overview 2 | 3 | 4 |
5 | 6 | [Recorded meetup session](https://www.youtube.com/watch?v=_3YcJKwU9Ik) 7 | 8 |
9 | 10 | 11 | ## Common Sorting Algorithms 12 | 13 | - Bubble sort: swapping until list is sorted 14 | - Selection sort: select minimum and move to front until list is sorted 15 | - Insertion sort: assume first element is sorted, insert every other element in proper position, by shifting elements when needed 16 | - Merge sort: divide until 1 or 2 elements left, then build back up 17 | - Quick sort: select a pivot, then rearrange element around pivot 18 | - Counting sort: count and recreate the elements 19 | 20 | [Bubble Sort (With Code in Python/C++/Java/C) (programiz.com)](https://www.programiz.com/dsa/bubble-sort) 21 | 22 | [Sorting algorithm reference, for coding interviews and computer science classes | Interview Cake](https://www.interviewcake.com/sorting-algorithm-cheat-sheet) 23 | 24 |
25 |
26 | 27 | ## Common Searching Algorithms 28 | 29 | - Linear search: sequentially search from start to end until element is found 30 | - Binary search: divide and conquer, reducing search space 31 | - Jump search: search by skipping over a fixed size of elements 32 | 33 |
34 |
35 | 36 | 37 | ## When to Use 38 | 39 | - Search in a sorted array: 40 | - Search in an unsorted array: 41 | - Insert into a sorted array: 42 | - Merge two or k sorted arrays: 43 | - Sort an array of just 2 types of element: 44 | 45 |
46 |
47 | 48 | ## Practice Questions 49 | 50 | ### Beginner 51 | 52 | [https://leetcode.com/problems/merge-sorted-array/](https://leetcode.com/problems/merge-sorted-array/) 53 | 54 | [https://leetcode.com/problems/guess-number-higher-or-lower/](https://leetcode.com/problems/guess-number-higher-or-lower/) 55 | 56 | [https://leetcode.com/problems/first-bad-version/](https://leetcode.com/problems/first-bad-version/) 57 | 58 | [https://leetcode.com/problems/remove-duplicates-from-sorted-array/](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) 59 | 60 |
61 | 62 | ### Intermediate 63 | 64 | [https://leetcode.com/problems/sort-colors/](https://leetcode.com/problems/sort-colors/) 65 | 66 | [https://leetcode.com/problems/search-in-rotated-sorted-array/](https://leetcode.com/problems/search-in-rotated-sorted-array/) 67 | 68 | [https://leetcode.com/problems/merge-intervals](https://leetcode.com/problems/merge-intervals) 69 | 70 | [https://leetcode.com/problems/merge-k-sorted-lists](https://leetcode.com/problems/merge-k-sorted-lists) 71 | 72 |
73 |
74 | 75 | ## Resources 76 | 77 | [https://www.interviewcake.com/sorting-algorithm-cheat-sheet](https://www.interviewcake.com/sorting-algorithm-cheat-sheet) 78 | 79 | [https://www.programiz.com/dsa/sorting-and-searching](https://www.programiz.com/dsa/bubble-sort) 80 | 81 | Gayle Laakmaan McDowell + Hackerrank videos on sorting and searching: 82 | - [Binary Search](https://youtu.be/P3YID7liBug) 83 | - [Quicksort](https://youtu.be/SLauY6PpjW4) 84 | - [Merge Sort](https://youtu.be/KF2j-9iSf4Q) 85 | - [Heaps](https://youtu.be/t0Cq6tVNRBA) 86 | - [Graph Search](https://youtu.be/zaBhtODEL0w) 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithm and Datastructures Series 2 | 3 | 4 | Welcome to the WWCode Lagos Algorithms and Datastructures series repo! This is or was (depending on when are you are seeing this repo 😊) used to track a bi-weekly series on learning various algorithms and data structure concepts. 5 | 6 | You can use this repo as a self-serve learning platform to help you in preparing for technical interviews. 7 | 8 | 9 |
10 | 11 | 12 | ## **How To Use This Repo** 13 | 14 | You're starting at the right place! This file contains general resources and links to pages on specific concepts. 15 | 16 | For each concept, you find the recorded session from the bi-weekly meetup, the slides used during the meetup, resources and practice problems on the concept. 17 | 18 | You also find solutions to the practice problems solved by others in the community. 19 | 20 | 21 |
22 | 23 | 24 | ## **How To Contribute** 25 | 26 | We are encouraging you to solve the practice problems after learning through each concept and also send us a pull request of your working solution in any language. 27 | 28 | If you also solved an interesting problem related to any concept, or you find an helpful resource, feel free to send us a pull request of it. 29 | 30 | If you've never contributed to open-source before, let this be your first contribution! [Here's a step by step reference](https://akrabat.com/the-beginners-guide-to-contributing-to-a-github-project/) to contributing. 31 | 32 | If you are a more advanced coder, we would welcome your help reviewing PRs of code solutions and provide helpful feedback on best practices. 33 | 34 | 35 |
36 | 37 | 38 | ## General **Resources** 39 | 40 | - [https://www.udacity.com/course/refresh-your-resume--ud243](https://www.udacity.com/course/refresh-your-resume--ud243) 41 | - [https://medium.com/@IAMebonyhope/writing-a-good-resume-for-a-software-developer-internship-position-a6de0337c8ea](https://medium.com/@IAMebonyhope/writing-a-good-resume-for-a-software-developer-internship-position-a6de0337c8ea) 42 | - [http://www.crackingthecodinginterview.com/](http://www.crackingthecodinginterview.com/) 43 | - [https://www.byte-by-byte.com/coding-interview-101/](https://www.byte-by-byte.com/coding-interview-101/) 44 | - [https://classroom.udacity.com/courses/ud513](https://classroom.udacity.com/courses/ud513) 45 | - [https://medium.com/swlh/how-to-study-for-data-structures-and-algorithms-interviews-at-faang-65043e00b5df](https://medium.com/swlh/how-to-study-for-data-structures-and-algorithms-interviews-at-faang-65043e00b5df) 46 | - [Wikiversity Data Structures and Algorithms](https://en.wikiversity.org/wiki/Data_Structures_and_Algorithms) 47 | - [https://leetcode.com/explore/interview/card/top-interview-questions-easy/](https://leetcode.com/explore/interview/card/top-interview-questions-easy/) 48 | - [The HackerRank Interview Preparation Kit | HackerRank](https://www.hackerrank.com/interview/interview-preparation-kit) 49 | - [Coding interview study plan](https://www.techinterviewhandbook.org/coding-interview-study-plan/) 50 | 51 | 52 |
53 | 54 | 55 | ## Concepts 56 | 57 | - [Getting Started & Time and Space Complexity](https://github.com/wwcodelagos/algorithm-and-datastructures-series/tree/main/getting-started#getting-started) 58 | - [Strings & Arrays](https://github.com/wwcodelagos/algorithm-and-datastructures-series/tree/main/strings-and-arrays#quick-overview) 59 | - [Hash Tables](https://github.com/wwcodelagos/algorithm-and-datastructures-series/tree/main/hash-tables#quick-overview) 60 | - [Stacks & Queues](https://github.com/wwcodelagos/algorithm-and-datastructures-series/tree/main/stacks-and-queues#quick-overview) 61 | - [Sorting & Searching](https://github.com/wwcodelagos/algorithm-and-datastructures-series/tree/main/sorting-and-searching#quick-overview) 62 | - [Recursion](https://github.com/wwcodelagos/algorithm-and-datastructures-series/tree/main/recursion) 63 | 64 |
65 |
66 |
67 | 68 | Join us on slack https://bit.ly/wwcodelagos-slack 69 | -------------------------------------------------------------------------------- /strings-and-arrays/readme.md: -------------------------------------------------------------------------------- 1 | # Quick Overview 2 | 3 |
4 |
5 | 6 | [Recorded meetup session](https://youtu.be/a7JCBxnaVJs) 7 | 8 | [Slides for the session](https://github.com/wwcodelagos/algorithm-and-datastructures-series/blob/main/strings-and-arrays/Strings%20and%20Arrays.pdf) 9 | 10 |
11 |
12 | 13 | ## Relationship Between Strings and Arrays 14 | 15 | - An array is a sequential collection of elements of similar datatypes while a string is a sequence of characters 16 | - Arrays can hold elements of any data type while strings contains only characters 17 | - String is an array of characters. 18 | - Strings are immutable but arrays are mutable. 19 | 20 |
21 |
22 | 23 | ## Fast Facts (Things to note for any language you are using) 24 | 25 | ### Strings 26 | 27 | - Cost of Modification 28 | - For most languages strings are immutable (can't change the content of the string once it's initialized) 29 | - Think of converting to char array when modification is needed 30 | - String s2 = s1 + "x” 31 | - Comparison: how do you compare two strings 32 | - .equals, .compare or == 33 | - Is it case sensitive or not by default 34 | - How to convert string to array and vice versa 35 | 36 | ### Arrays 37 | 38 | - Static and dynamic arrays 39 | - what is the default 40 | - arrays 41 | - arraylists 42 | - lists 43 | - Multidimensional arrays 44 | 45 | ### Common Operations 46 | 47 | - Accessing the ith element 48 | - Finding the index of an element 49 | - Iterating with or without index 50 | - Getting the length 51 | - Getting the sub (string or array) 52 | - Splitting or slicing 53 | - Checking if it contains an element 54 | 55 |
56 |
57 | 58 | ## Common Patterns 59 | 60 | When you are preparing for interviews, instead of trying to memorize as many leetcode problems as possible with the hope that you’ll get asked one of those exact questions, you can learn common patterns that can be applied to many different problems. 61 | 62 | ### Using a HashMap or Length-256 Integer Array 63 | 64 | - Counting the occurrence 65 | - Store for the future 66 | 67 | ### Using 2 pointers 68 | 69 | - Whenever you have to use a nested for loop 70 | - Comparing or swapping two elements 71 | - Do an operation in-place 72 | - Fast and slow runner 73 | 74 | Example: 75 | 76 | - Reverse a string or array 77 | - Sort an array in place 78 | 79 | ### Sliding Window 80 | 81 | - Finding sub (array or string) within another (array or sting) 82 | - Perform an operation from a starting point to ending point within the string or array 83 | 84 | Example 85 | 86 | - Find longest substring without repeating characters 87 | - Maximum sum subarray of size ‘K’ 88 | 89 |
90 |
91 | 92 | ## Common Mistakes 93 | 94 | - Not knowing the string or array operations available in your language 95 | - Time complexity of an operation: put into account under the hood operations 96 | - Modifying strings 97 | 98 |
99 |
100 | 101 | ## Practice Questions 102 | 103 | ### Beginner: 104 | 105 | [https://leetcode.com/problems/reverse-string/](https://leetcode.com/problems/reverse-string/) (come up with an optimal O(log n) solution using 2-pointer approach) 106 | 107 | [https://leetcode.com/problems/plus-one/](https://leetcode.com/problems/plus-one/) 108 | 109 | [https://leetcode.com/problems/implement-strstr/](https://leetcode.com/problems/implement-strstr/) 110 | 111 | [https://leetcode.com/problems/maximum-subarray/](https://leetcode.com/problems/maximum-subarray/) 112 | 113 | ### Intermediate 114 | 115 | [https://leetcode.com/problems/string-compression/](https://leetcode.com/problems/string-compression/) (come up with an optimal solution using 2-pointer approach) 116 | 117 | [https://leetcode.com/problems/container-with-most-water/](https://leetcode.com/problems/container-with-most-water/) 118 | 119 | [https://leetcode.com/problems/longest-substring-without-repeating-characters/](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 120 | 121 | [https://leetcode.com/problems/circular-array-loop/](https://leetcode.com/problems/circular-array-loop/) 122 | 123 |
124 |
125 | 126 | ## Resources 127 | 128 | - [https://www.crackingthecodinginterview.com/](https://www.crackingthecodinginterview.com/) Arrays and Strings 129 | - [https://leetcode.com/explore/learn/card/array-and-string/](https://leetcode.com/explore/learn/card/array-and-string/) 130 | - [https://www.byte-by-byte.com/strings/](https://www.byte-by-byte.com/strings/) 131 | -------------------------------------------------------------------------------- /stacks-and-queues/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Quick Overview 4 | 5 |
6 | 7 | [Recorded meetup session](https://www.youtube.com/watch?v=jr3l8-VVjHA) 8 | 9 |
10 | 11 | 12 | ## What are Queues 13 | 14 | - First in, First out (FIFO) e.g. people on a queue. 15 | - Enqueue to add element to the back of the queue. 16 | - Dequeue to remove element from the front of the queue. 17 | - Add at one end, remove from the other end. 18 | 19 |
20 | 21 | ### Usage 22 | 23 | **Current applications:** 24 | 25 | - Job queues (printers). 26 | - Processing requests (web servers). 27 | - CPU and disk scheduling. 28 | - Process synchronization. 29 | - Call centers. 30 | 31 | **How you can use them:** 32 | 33 | - Breadth-first search. 34 | - Maintaining order. 35 | - Concurrent programming. 36 | 37 |
38 | 39 | ### Types of Queue: 40 | 41 | - Simple Queue. 42 | - Circular Queue. 43 | - Priority Queue. 44 | - Double Ended Queue (Deque). 45 | 46 |
47 |
48 |
49 | 50 | ## What are Stacks 51 | 52 | - Last in, First out (LIFO) e.g. stack of books or plates. 53 | - Push to add element to the top of the stack. 54 | - Pop to remove element from the top of the stack. 55 | - Add and remove from one end. 56 | 57 |
58 | 59 | ### Usage 60 | 61 | **Current applications:** 62 | 63 | - Back button in browsers. 64 | - Function call stack. 65 | 66 | **How you can use them:** 67 | 68 | - Depth-first search. 69 | - Replace recursion. 70 | - String parsing. 71 | - Reversing. 72 | - Evaluating expressions. 73 | 74 |
75 |
76 |
77 | 78 | 79 | ## Things to Note 80 | 81 | - Space complexity; most times it is O(n). 82 | - Time complexity; deletion and insertion O(1), visiting all elements O(n). 83 | - How they are implemented, try implementing one with a list. 84 | - How common operations work. 85 | 86 |
87 | 88 | 89 | ### Common Operations 90 | 91 | - Adding an element. 92 | - Removing an element. 93 | - Checking if it is empty. 94 | - Checking if it full. 95 | - Peek - looking at the top or front element without removing. 96 | 97 |
98 |
99 |
100 | 101 | ## Practice Questions 102 | 103 | ### Beginners 104 | 105 | [https://leetcode.com/problems/min-stack/](https://leetcode.com/problems/min-stack/) 106 | 107 | [https://leetcode.com/problems/valid-parentheses/](https://leetcode.com/problems/valid-parentheses/) 108 | 109 | [https://leetcode.com/problems/implement-stack-using-queues/](https://leetcode.com/problems/implement-stack-using-queues/) 110 | 111 | [https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/) 112 | 113 |
114 | 115 | ### Intermediate 116 | 117 | [https://leetcode.com/problems/basic-calculator-ii/](https://leetcode.com/problems/basic-calculator-ii/) 118 | 119 | [https://leetcode.com/problems/reveal-cards-in-increasing-order/](https://leetcode.com/problems/reveal-cards-in-increasing-order/) 120 | 121 | [https://leetcode.com/problems/simplify-path/](https://leetcode.com/problems/simplify-path/) 122 | 123 | [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) 124 | 125 | [https://leetcode.com/problems/find-the-winner-of-the-circular-game/](https://leetcode.com/problems/find-the-winner-of-the-circular-game/) 126 | 127 |
128 |
129 |
130 | 131 | ## Resources 132 | 133 | - [https://www.programiz.com/dsa/stack](https://www.programiz.com/dsa/stack) 134 | - [https://www.programiz.com/dsa/queue](https://www.programiz.com/dsa/queue) 135 | - [Stacks and Queues (cmu.edu)](https://www.andrew.cmu.edu/course/15-121/lectures/Stacks%20and%20Queues/Stacks%20and%20Queues.html#:~:text=A%20queue%20is%20a%20container,%2Dout%20(FIFO)%20principle.&text=The%20difference%20between%20stacks%20and,item%20the%20least%20recently%20added.) 136 | - [https://www.educative.io/blog/data-structures-stack-queue-java-tutorial](https://www.educative.io/blog/data-structures-stack-queue-java-tutorial) 137 | - [https://introcs.cs.princeton.edu/java/43stack/](https://introcs.cs.princeton.edu/java/43stack/) 138 | - [https://leetcode.com/explore/learn/card/queue-stack/](https://leetcode.com/explore/learn/card/queue-stack/) 139 | - [https://www.interviewcake.com/concept/python/stack](https://www.interviewcake.com/concept/python/stack) 140 | - [https://www.interviewcake.com/concept/python/queue](https://www.interviewcake.com/concept/python/queue) 141 | - [video on stacks & queues by Gayle Laakmann McDowell](https://www.youtube.com/watch?v=wjI1WNcIntg) 142 | -------------------------------------------------------------------------------- /hash-tables/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Quick Overview 4 | 5 |
6 | 7 | [Recorded meetup session](https://youtu.be/-gs2k28KQDo) 8 | 9 |
10 | 11 | ## What are Hash Tables 12 | 13 | - Hash Table is a data structure which maps a key to a value using hash functions through a process called hashing. 14 | - Key/value pairs. 15 | - Supports quick insertion and searching. 16 | - Keys and values can be any datatype, as long as it is hashable, technically keys are primitive datatype. 17 | - There are two different kinds of hash tables: hashset and hashmap. 18 | 19 |
20 |
21 | 22 | ## Key Concepts 23 | 24 | ### **Hash function** 25 | 26 | This is any function that can be used to map map the key to the index of a specific bucket. The values (index) returned by a hash function are called hashes. 27 | 28 | The values are used to index a fixed-size table called a hash table. 29 | 30 | Use of a hash function to index a hash table is called *hashing.* 31 | 32 | The hash function is the most important component of a hash table. 33 | 34 | Example: y = x % 5 35 | where x is the key value and y is the index of the assigned bucket. 36 | 37 | ### Hashing 38 | 39 | This is the practice of using an algorithm (or hash function) to map data of any size to a fixed length. 40 | In hashing, keys are converted into hash values called hashes. 41 | 42 | Hashing is a one-way function. 43 | 44 | ### Hash Collision 45 | 46 | There’s always a chance that two different keys for hash function will generate the same hash value. This is known as a hash collision. 47 | 48 | For instance, in our previous hash function (y = x % 5), both 1987 and 2 have the same hash value of 2. 49 | 50 |
51 |
52 | 53 | ## HashSet and HashMaps 54 | 55 | | HashSet | HashMap | 56 | | --- | --- | 57 | | Implementation of a set data structure to store no repeated values | Implementation of a map data structure to store (key, value) pairs | 58 | | Stores just values | Stores keys and values | 59 | | Doesn't allow duplicate values | Doesn't allow duplicate keys, but allows duplicate values | 60 | | Useful when uniqueness needs to be maintained | Useful when you want to store more information rather than only the key | 61 | 62 |
63 |
64 | 65 | ## Identifying Hash Table Questions 66 | 67 | - Check if an item has been visited or checked before e.g. Detect if a List is Cyclic . 68 | - Check if an item is unique. 69 | - Count the occurrence of an item. 70 | - Check if a list or array contains duplicate. 71 | - When you are using nested for loop. 72 | - When you need to search. 73 | - When you need to aggregate information. 74 | - When working with dynamic programming. 75 | 76 |
77 |
78 | 79 | ## Things to Note 80 | 81 | - Space complexity; most times it is O(n) 82 | - Time complexity; average and amortized case is O(1), worst case could be O(n) 83 | - How they are implemented, try implementing one. 84 | - How collisions are handled in hash tables. 85 | - They do not maintain the order of insertion. 86 | - They are named differently in several programming languages. 87 | - How common operations work. 88 | 89 |
90 |
91 | 92 | ## Common Operations (In the language you are using) 93 | 94 | - Checking if it contains a key. 95 | - Adding and inserting. 96 | - Getting the length. 97 | - Getting all keys and values. 98 | - Iterating through the hash tables. 99 | 100 |
101 |
102 | 103 | ## Practice Questions 104 | 105 | ### Beginner: 106 | 107 | [https://leetcode.com/problems/find-lucky-integer-in-an-array/](https://leetcode.com/problems/find-lucky-integer-in-an-array/) 108 | 109 | [https://leetcode.com/problems/two-sum](https://leetcode.com/problems/two-sum) 110 | 111 | [https://leetcode.com/problems/happy-number/](https://leetcode.com/problems/happy-number/) 112 | 113 | [https://leetcode.com/problems/jewels-and-stones/](https://leetcode.com/problems/jewels-and-stones/) 114 | 115 | [https://leetcode.com/problems/intersection-of-two-arrays-ii/](https://leetcode.com/problems/intersection-of-two-arrays-ii/) 116 | 117 | ### Intermediate 118 | 119 | [https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/](https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/) 120 | 121 | [https://leetcode.com/problems/group-anagrams/](https://leetcode.com/problems/group-anagrams/) 122 | 123 | [https://leetcode.com/problems/valid-sudoku/](https://leetcode.com/problems/valid-sudoku/) 124 | 125 | [https://leetcode.com/problems/top-k-frequent-words/](https://leetcode.com/problems/top-k-frequent-words/) 126 | 127 |
128 |
129 | 130 | ## Resources 131 | 132 | - [video on hash tables by Gayle Laakmann McDowell](https://youtu.be/shs0KM3wKv8) 133 | - [https://leetcode.com/explore/learn/card/hash-table/](https://leetcode.com/explore/learn/card/hash-table/) 134 | - [https://www.interviewbit.com/courses/programming/topics/hashing/](https://www.interviewbit.com/courses/programming/topics/hashing/) 135 | -------------------------------------------------------------------------------- /stacks-and-queues/practice-solutions/valid-parentheses-beginner-breakout-room.txt: -------------------------------------------------------------------------------- 1 | 1, 3, 4, 5, 2 2 | stack = [1,3,4,5,2] 3 | stack.push(1) 4 | stack.push(3) 5 | .... 6 | 7 | stack.pop() 8 | return 2 9 | stack = [1,3,4,5] 10 | 11 | stack.top() 12 | return 5 13 | stack = [1,3,4,5] 14 | 15 | def __init__(self): 16 | # initialize a list 17 | self.stack = [] 18 | 19 | def push(self, x: int) -> None: 20 | self.stack.append(x) 21 | 22 | def pop(self) -> int: 23 | return stack.pop() 24 | 25 | def top(self) -> int: 26 | return self.stack[-1] 27 | 28 | def empty(self) -> bool: 29 | return len(self.stack) == 0; 30 | 31 | 32 | 33 | 34 | PHP --> Desmond 35 | 36 | class MyStack { 37 | /** 38 | */ 39 | 40 | Private $list 41 | 42 | function __construct() { 43 | $this->list = []; 44 | } 45 | 46 | /** 47 | * @param Integer $x 48 | * @return NULL 49 | */ 50 | function push($x) { 51 | $this->list[] = $x; 52 | } 53 | 54 | /** 55 | * @return Integer 56 | */ 57 | function pop() { 58 | $this->list = array_pop($this->list); 59 | return $this->list; 60 | } 61 | 62 | /** 63 | * @return Integer 64 | */ 65 | function top() { 66 | return end($this->list); 67 | } 68 | 69 | /** 70 | * @return Boolean 71 | */ 72 | function empty() { 73 | if($this->list){ 74 | return false; 75 | } 76 | return true; 77 | } 78 | } 79 | 80 | /** 81 | * Your MyStack object will be instantiated and called as such: 82 | * $obj = MyStack(); 83 | * $obj->push($x); 84 | * $ret_2 = $obj->pop(); 85 | * $ret_3 = $obj->top(); 86 | * $ret_4 = $obj->empty(); 87 | */ 88 | 89 | 90 | 91 | 92 | Moses: --> Python 93 | class MyStack: 94 | 95 | def __init__(self): 96 | self.stack = list() 97 | 98 | def push(self, x: int) -> None: 99 | self.stack.append(x) 100 | 101 | def pop(self) -> int: 102 | if len(self.stack) > 0: 103 | return self.stack.pop() 104 | else: 105 | return None 106 | 107 | 108 | def top(self) -> int: 109 | if len(self.stack) > 0: 110 | return self.stack[len(self.stack)-1] 111 | 112 | 113 | def empty(self) -> bool: 114 | return self.stack == 0 115 | 116 | 117 | 118 | Javascript: -- Tosin 119 | 120 | var MyStack = function() { 121 | stack = [] 122 | }; 123 | 124 | MyStack.prototype.push = function(x) { 125 | stack.push(x) 126 | }; 127 | 128 | MyStack.prototype.pop = function() { 129 | if(stack.length == 0) { 130 | return null 131 | } 132 | stack.pop() 133 | }; 134 | 135 | MyStack.prototype.top = function() { 136 | if(!stack.length == 0 ) { 137 | return stack.length-1 138 | } 139 | return null 140 | }; 141 | 142 | MyStack.prototype.empty = function() { 143 | if(stack.length == 0) { 144 | return true 145 | } 146 | return false 147 | }; 148 | 149 | 150 | 151 | 152 | Gbemisola ---- C# //Not sure it's correct. I am attemting a linked list 153 | public class Node 154 | 155 | { 156 | 157 | public T Value {get; set;} 158 | public Node Next {get; set;} 159 | public Node(T value) 160 | 161 | { 162 | 163 | this.Value = value; 164 | 165 | } 166 | 167 | } 168 | 169 | public class Stack 170 | { 171 | public Node Head {get; set;} 172 | public Node Tail {get; set;} 173 | public int Count {get; set;} 174 | 175 | public StackNode Push(G value) 176 | 177 | { 178 | 179 | Node node = new Node(value); 180 | 181 | if(this.Head == null) 182 | 183 | { 184 | 185 | Head = Tail = node; 186 | this.Count += 1; 187 | return node; 188 | 189 | } 190 | 191 | var temp = Head; 192 | Head = node 193 | Head.Next = node; 194 | this.Count += 1; 195 | return node; 196 | 197 | } 198 | 199 | public StackNode Pop(G value) 200 | 201 | { 202 | Node temp = Head; 203 | this.Head = temp.Next; 204 | temp.Next = null; 205 | this.Count -= 1; 206 | return temp; 207 | 208 | } 209 | 210 | public bool Empty() 211 | { 212 | if (this.Count == 0) 213 | { 214 | return true; 215 | } 216 | return false; 217 | } 218 | 219 | } 220 | 221 | ******************** Valid Parentheses ******************** 222 | stack=['(',')','{','}'] 223 | s="(){}" 224 | 225 | (){} 226 | 01 227 | 228 | 229 | }3 230 | {2 231 | )1 232 | (0 233 | 234 | # for loop to iterate through the items 235 | # push items into the stack 236 | # check if the item is direct opposite of the top of stack 237 | 238 | stack = [] 239 | parentheses = {"{":"}", "(":")", "[":"]"} 240 | # another check you can do here: if len(s) is not even, return false 241 | if len(s) % 2 != 0: 242 | return False 243 | 244 | for i in range(len(s)): 245 | c = s[i] 246 | if c in parenthesis: 247 | stack.append(c) 248 | 249 | elif len(stack) and parentheses[stack[-1]] == c: 250 | stack.pop() 251 | 252 | else: 253 | return False 254 | 255 | return len(stack) == 0 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | --------------------------------------------------------------------------------