diff --git a/README.md b/README.md index 184fe912..0aecbf73 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ -# CS Build Week 2: Interview Prep -This is a general repo that you can fork for holding any artifacts you -might need to submit during the week. Feel free to make subdirectories -here as necessary. +======= +# CS Build Week 2 -For all details about the week, [check out the page in -TrainingKit](https://learn.lambdaschool.com/cs/sprint/reco0t22NdXmr8VyL). \ No newline at end of file + +## Taking the opportunity to save my code challenge practice. + +Some of the problems are done in both python and Javascript. Some were solved more than one way. +>>>>>>> 6c54ba4bca544d7403a83a6c6d5edf803644a1b2 diff --git a/add-two-numbers/add-two-numbers.js b/add-two-numbers/add-two-numbers.js new file mode 100644 index 00000000..4c4c5eba --- /dev/null +++ b/add-two-numbers/add-two-numbers.js @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function (l1, l2) { + let sum = 0; + let curr = new ListNode(0); + let res = curr; + + while (l1 || l2) { + if (l1) { + sum += l1.val; + l1 = l1.next; + } + if (l2) { + sum += l2.val; + l2 = l2.next; + } + + curr.next = new ListNode(sum % 10); + curr = curr.next; + + sum = sum > 9 ? 1 : 0; + } + + if (sum) { + curr.next = new ListNode(sum); + } + + return res.next; +}; diff --git a/add-two-numbers/add-two-numbers.py b/add-two-numbers/add-two-numbers.py new file mode 100644 index 00000000..ad62fe76 --- /dev/null +++ b/add-two-numbers/add-two-numbers.py @@ -0,0 +1,33 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + # convert the linked lists to integers + def conv_int(l: ListNode): + s = "" + while l != None: + s += str(l.val) + l = l.next + return int(s[::-1]) + + # convert sum of integers to a linked list + def to_list(n: int): + s = str(n)[::-1] + head = prev = None + for ch in s: + node = ListNode(int(ch)) + if prev is not None: + prev.next = node + prev = node + if head is None: + head = prev + return head + + # return the sum of the two linked lists + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + a = Solution.conv_int(l1) + b = Solution.conv_int(l2) + return Solution.to_list(a + b) + \ No newline at end of file diff --git a/contains-dups/contains-dups.js b/contains-dups/contains-dups.js new file mode 100644 index 00000000..f18f0bd8 --- /dev/null +++ b/contains-dups/contains-dups.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} x + * @return {boolean} + */ + +var containsDuplicate = function (x) { + // create a set b/c sets cannot contain dups + let numbers = new Set(); + // iterate over the array + for (let num of x) { + // get to a number, check if it's already in the set + if (!numbers.has(num)) { + // if it's not in the set add the number to the set + numbers.add(num); + // but if you see it was already added to the set + } else { + // signal the array contains duplicates + return true; + } + } + // if code runs and no duplicates are found, return false + return false; +}; diff --git a/contains-dups/contains-dups.py b/contains-dups/contains-dups.py new file mode 100644 index 00000000..28b161eb --- /dev/null +++ b/contains-dups/contains-dups.py @@ -0,0 +1,20 @@ +/* + * @param {number[]} nums + * @return {boolean} + */ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + + # First pass solution not very efficient + checked = set() + + for number in nums: + if number in checked: + return True + checked.add(number) + return False + + + + # Single line solution, slightly more efficient + return len(set(nums)) < len(nums) \ No newline at end of file diff --git a/find-duplicate-num.py b/find-duplicate-num.py new file mode 100644 index 00000000..f292beb5 --- /dev/null +++ b/find-duplicate-num.py @@ -0,0 +1,18 @@ +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + # create a set b/c sets can't have dups + num_set = set() + no_dups = -1 + + # loop through the list + for i in range(len(nums)): + # check for number that is repeated + if nums[i] in num_set: + # return that number + return nums[i] + #. if the number is not repeating + else: + # add it to the set + num_set.add(nums[i]) + + return no_dups \ No newline at end of file diff --git a/first_not_repeating_character.py b/first_not_repeating_character.py new file mode 100644 index 00000000..f467c916 --- /dev/null +++ b/first_not_repeating_character.py @@ -0,0 +1,18 @@ +s = "abacabad" + +def first_not_repeating_character(s): + + nothing = s + # Check that the string exists + while len(nothing) > 0: + # Evaluate the character at index 0 + curr = nothing[0] + # Iterate through entire string, looking for char[0] again + if curr in nothing[1:]: + # If it repeats, remove all instances from the string + nothing = nothing.replace(curr, '') + # If the char doesn't repeat, return the char[0] + else: + return curr + # If there are only repeating characters, per instructions return '_' + return '_' diff --git a/longest-substring-wout-dups/longest-substring-wout-dups.js b/longest-substring-wout-dups/longest-substring-wout-dups.js new file mode 100644 index 00000000..3f8ddb7e --- /dev/null +++ b/longest-substring-wout-dups/longest-substring-wout-dups.js @@ -0,0 +1,22 @@ +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + let start = 0, res = 0; + let charsInWindow = new Set(); + + for (let end = 0; end < s.length; end++) { + let entering = s[end]; + console.log('test', entering) + + while (charsInWindow.has(entering)) { + charsInWindow.delete(s[start++]); + } + charsInWindow.add(s[end]); + console.log('look', s[end]) + res = Math.max(res, end - start + 1); + console.log(res, end - start + 1) + } + return res; +} \ No newline at end of file diff --git a/longest-substring-wout-dups/longest-substring-wout-dups.py b/longest-substring-wout-dups/longest-substring-wout-dups.py new file mode 100644 index 00000000..7ea21d26 --- /dev/null +++ b/longest-substring-wout-dups/longest-substring-wout-dups.py @@ -0,0 +1,14 @@ +def lengthOfLongestSubstring(self, s): + hash_table = {} + maxLength = 0 + start = 0 + + for i in range(len(s)): + + if (s[i] in hash_table): + start = max(start, hash_table[s[i]]+1) + + maxLength = max(maxLength,i-start+1) + hash_table[s[i]]=i + + return maxLength \ No newline at end of file diff --git a/lowest-common-ancestor/lowest-common-ancestor.py b/lowest-common-ancestor/lowest-common-ancestor.py new file mode 100644 index 00000000..a71b7760 --- /dev/null +++ b/lowest-common-ancestor/lowest-common-ancestor.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if root==None: #Base Case + return None + + if root==p or root==q: + return root + left = self.lowestCommonAncestor(root.left,p,q) #Check Left Nodes + right = self.lowestCommonAncestor(root.right,p,q) #Check Right Nodes + + if left!=None and right!=None: #Pass Node to root + return root + if left==None and right==None: #Pass None to root + return None + + return left if left else right \ No newline at end of file diff --git a/maximum-depth-binary-tree.py b/maximum-depth-binary-tree.py new file mode 100644 index 00000000..1fcd07d7 --- /dev/null +++ b/maximum-depth-binary-tree.py @@ -0,0 +1,33 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def height(self, root) -> int: # indicates return will be an integer + # Check for a value in root node + if root is None: + # if root node is empty return 0 + return 0 + else: + # if root node is not empty, find max height on either left or right side of tree and add one + # return the value + return 1 + max(self.height(root.left), self.height(root.right)) + + + def isBalanced(self, root: TreeNode) -> bool: # indicates return will be a boolean + # check for a value in root node + if root == None: + # empty root node == balanced => return true + return True + # if it's not empty, find the height of the left and right sides then compare them to find if they're balanced and return the boolean + else: return abs(self.height(root.left) - self.height(root.right)) <= 1 and (self.isBalanced(root.left) and self.isBalanced(root.right)) + + + + + + + + \ No newline at end of file diff --git a/merge-2-sorted-lists/merg-2-sorted-lists.js b/merge-2-sorted-lists/merg-2-sorted-lists.js new file mode 100644 index 00000000..bbe21147 --- /dev/null +++ b/merge-2-sorted-lists/merg-2-sorted-lists.js @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + function merge(left, right) { + if(!left) return right; + if(!right) return left; + + if(left.val < right.val) { + left.next = merge(left.next, right); + return left; + } + right.next = merge(left, right.next); + return right; + } + return merge(l1, l2); +}; \ No newline at end of file diff --git a/merge-2-sorted-lists/merge-2-sorted-lists.py b/merge-2-sorted-lists/merge-2-sorted-lists.py new file mode 100644 index 00000000..a4be3976 --- /dev/null +++ b/merge-2-sorted-lists/merge-2-sorted-lists.py @@ -0,0 +1,45 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + # initialize head to list node 0 + head = ListNode(0) + ptr = head + + while True: + # check for nodes in both lists + if l1 is None and l2 is None: + # if both lists are empty, loop is done + break + # if the first list is empty but second is not + elif l1 is None: + # return all of the second list + ptr.next = l2 + break + # if the second list is empty but first is not + elif l2 is None: + # return all of first list + ptr.next = l1 + break + else: + # set temporary head of 0 + smallerVal = 0 + # check if value of next node in l1 is less than in l2 + if l1.val < l2.val: + smallerVal = l1.val + # if that's the case, insert into new list and move pointer to next + l1 = l1.next + else: + # if value in l2 is greater than in l1, insert into new list + smallerVal = l2.val + # then move the pointer to the next node in l2 + l2 = l2.next + + newNode = ListNode(smallerVal) + ptr.next = newNode + ptr = ptr.next + + return head.next \ No newline at end of file diff --git a/palindrome-number/palindrome-number.js b/palindrome-number/palindrome-number.js new file mode 100644 index 00000000..d56e3543 --- /dev/null +++ b/palindrome-number/palindrome-number.js @@ -0,0 +1,27 @@ +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function(x) { + // quickly check if negative + if (x < 0) { + // if yes, return false + return false + } + // check if x is the same as it's reversed form + return x === reversedInteger(x); + +}; + // + var reversedInteger = function(x) { + // initialize variable starting as 0 + let reversed = 0; + // checking if you have positive integer + while (x > 0) { + // variable started as 0, * 10 is 0 then add next int of x % 10 + reversed = (reversed * 10) + (x % 10); + // remove last number of given input + x = Math.floor(x / 10); + } + return reversed; +}; \ No newline at end of file diff --git a/palindrome-number/palindrome-number.py b/palindrome-number/palindrome-number.py new file mode 100644 index 00000000..f6a5a95b --- /dev/null +++ b/palindrome-number/palindrome-number.py @@ -0,0 +1,30 @@ +class Solution: + def isPalindrome(self, x: int) -> bool: + # quickly check if x is negative b/c neg ints can't be palindromes + if x < 0: + # if negative, return false + return False + # quickly check if x is a single digit, it will always be a palindrome + if x < 10: + # if it is, return true + return True + # initialize count to be 0 + count = 0 + # initialize empty list + lst = [] + # loop through the input + while x > 0: + count += 1 + # take mod of input and append to empty list + lst.append(x % 10) + # double divide the input by 10 to check if the append num is correct + x = x // 10 + + for i in range (count // 2): + if lst[i] == lst[count -i - 1]: + continue + + else: + return False + + return True \ No newline at end of file diff --git a/queue-using-stack.py b/queue-using-stack.py new file mode 100644 index 00000000..97a34c12 --- /dev/null +++ b/queue-using-stack.py @@ -0,0 +1,29 @@ +class MyQueue: + + def __init__(self): + # Initialize myStack and tempStack with empty lists + self.myStack, self.tempStack = [], [] + + def push(self, x: int) -> None: + # Append x elem to myStack + self.myStack.append(x) + + def pop(self) -> int: + # Pop oldest elem in queue by moving all myStack to tempStack putting oldest now at [0] + if not self.tempStack: + while self.myStack: + self.tempStack.append(self.myStack.pop()) + top_elem = self.tempStack.pop() + # Finally, put remaining elem back into myStack and get the top elem then return it + while self.tempStack: + self.myStack.append(self.tempStack.pop()) + return(top_elem) + + def empty(self) -> bool: + + return(not self.myStack) + + + + + diff --git a/remove-dups-from-linked-list.py b/remove-dups-from-linked-list.py new file mode 100644 index 00000000..649452b8 --- /dev/null +++ b/remove-dups-from-linked-list.py @@ -0,0 +1,55 @@ +# +# @lc app=leetcode id=83 lang=python3 +# +# [83] Remove Duplicates from Sorted List +# + +# @lc code=start +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + + # curr = head + # prev = None + + # # empty set b/c sets can't contain dups + # s = set() + + # # do till linked list is not empty + # while curr: + # # if curr node is seen before, ignore it + # if curr.val in s: + # prev.next = curr.next + + # # insert curr node into the set and move to next node + # else: + # s.add(curr.val) + # prev = curr + + # curr = prev.next + # return head + + + + + + node = head + while node: + lead = node + while node.next and node.next.val == lead.val: + node = node.next + node = lead.next = node.next + return head + + + + + + + +# @lc code=end + diff --git a/remove-dups-from-sorted-array/remove-dups.js b/remove-dups-from-sorted-array/remove-dups.js new file mode 100644 index 00000000..0fa50eb6 --- /dev/null +++ b/remove-dups-from-sorted-array/remove-dups.js @@ -0,0 +1,13 @@ +var removeDuplicates = function(nums) { + let start = nums[0]; + console.log('start', start) + for (let i = [1]; i < nums.length; i++) { + if (nums[i] === start) { + console.log('NUMS-I', nums[i]) + nums.splice(i, 1); + --i; + } + start = nums[i]; + } + return nums.length; +}; diff --git a/remove-dups-from-sorted-array/remove-dups.py b/remove-dups-from-sorted-array/remove-dups.py new file mode 100644 index 00000000..da77cd1e --- /dev/null +++ b/remove-dups-from-sorted-array/remove-dups.py @@ -0,0 +1,5 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + + nums[:] = sorted(set(nums)) + return len(nums) \ No newline at end of file diff --git a/reverse-integer.js b/reverse-integer.js new file mode 100644 index 00000000..8e639116 --- /dev/null +++ b/reverse-integer.js @@ -0,0 +1,18 @@ +var reverse = function(x) { + + let negative = x < 0; // keep track if variable is negative + let reverse = 0; // instantiate 0 + + if (negative) { + x *= -1; // make x positive + } + + while (x > 0) { + reverse = (reverse * 10) + (x % 10) + x = Math.floor(x / 10); // remove last digit of x + } + if (reverse > (2 ** 31 - 1)) { + return 0; + } + return negative ? (reverse * -1) : reverse; +}; \ No newline at end of file diff --git a/sort-an-array/sort-an-array.js b/sort-an-array/sort-an-array.js new file mode 100644 index 00000000..d963a5fa --- /dev/null +++ b/sort-an-array/sort-an-array.js @@ -0,0 +1,12 @@ +var sortArray = function(nums) { + // check for valid input + if (nums.length <= 1) return nums + // create pivot point and pop number from there in array + const pivot = nums.pop(); + // create new array to store numbers smaller than pivot + const smlArr = sortArray(nums.filter(n => n <= pivot)); + // create new array to store numbers larger than pivot + const lrgArr = sortArray(nums.filter(n => n > pivot)); + // return new array by combining two new arrays divided by the pivot point + return smlArr.concat(pivot, lrgArr) +}; \ No newline at end of file diff --git a/sort-an-array/sort-an-array.py b/sort-an-array/sort-an-array.py new file mode 100644 index 00000000..af27ec4c --- /dev/null +++ b/sort-an-array/sort-an-array.py @@ -0,0 +1,51 @@ +class Solution(object): + def sortArray(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + # sanity checks, parameters are positive integers between 0 and 5001 + if len(nums) > 5000 and len(nums) < 1: + return [] + + start = 0 + end = len(nums) - 1 + # as the testcases are smaller arrays use quicksort + self.quickSort(nums, start, end) + return nums + + def quickSort(self, nums, start, end): + if start >= end: + return + + # find mid index for pivot point + md_index = (start + end) // 2 + # swap first and mid index elements + nums[start], nums[md_index] = nums[md_index], nums[start] + + p_index = self.partition(nums, start, end) + # recursive calls to both the left and right sides + self.quickSort(nums, start, p_index - 1) + self.quickSort(nums, p_index + 1, end) + + def partition(self, nums, start, end): + + low = start + 1 + high = end + pivot = nums[start] + + while True: + + while low <= high and nums[high] >= pivot: + high -= 1 + + while low <= high and nums[low] <= pivot: + low += 1 + + if (low <= high): + nums[low], nums[high] = nums[high], nums[low] + else: + break + # swap start index with high index + nums[start], nums[high] = nums[high], nums[start] + return high \ No newline at end of file diff --git a/two-sum.py b/two-sum.py new file mode 100644 index 00000000..66ffb965 --- /dev/null +++ b/two-sum.py @@ -0,0 +1,13 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + # Create a hashtable to store key, value pairs + hashtable = {} + # store keys as index location and vals as original str + # loop through hashtable + for index, num in enumerate(nums): + # if you find the index number + if num in hashtable: + # output should show the key, value pair for the one you're looking for + return [hashtable[num], index] + # in hashtable subtract num at specified index from given target + hashtable[target - num] = index \ No newline at end of file