├── .gitignore ├── Google ├── Problem#465.py ├── Problem#73.py ├── Problem#747.py ├── Problem#649.py ├── Problem#1.py ├── Problem#560.py ├── Problem#83.py ├── Problem#104#715.py ├── Problem#26.py ├── Problem#164.py ├── Problem#118.py ├── Problem#664.py ├── Problem#20.py ├── Problem#568.py ├── Problem#35.py ├── Problem#145#714.py ├── Problem#448.py ├── Problem#113.py └── Problem#3.py ├── Apple ├── Problem#233.py ├── Problem#451.py ├── Problem#273.py ├── Problem#580.py └── Problem#53.py ├── Amazon ├── Problem#224.py ├── Problem#184.py ├── Problem#157.py ├── Problem#372.py ├── Problem#197.py ├── Problem#398.py ├── Problem#534.py ├── Problem#49.py ├── Problem#12.py ├── Problem#58.py ├── Problem#43#746.py ├── Problem#29.py └── Problem#65.py ├── Facebook ├── Problem#15.py ├── Problem#51.py ├── Problem#424.py ├── Problem#47.py ├── Problem#168.py ├── Problem#216.py ├── Problem#69.py ├── Problem#117.py ├── Problem#426.py └── Problem#79.py ├── Palantir ├── Problem#202.py └── Problem#491.py ├── Dropbox └── Problem#212#719.py ├── Lyft └── Problem#102.py ├── MongoDB └── Problem#155.py ├── Others └── Problem#467.py ├── README.md ├── IBM └── Problem#205.py ├── Salesforce └── Problem#327#422.py ├── Bloomberg └── Problem#578.py ├── Microsoft ├── Problem#70.py ├── Problem#107#752.py ├── Problem#50.py ├── Problem#127.py └── Problem#452.py ├── Twitter └── Problem#386.py ├── Jane-Street └── Problem#5.py ├── Uber └── Problem#2.py ├── Airbnb └── Problem#177#699.py └── Stripe └── Problem#4.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /Google/Problem#465.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the head of a singly linked list, reverse it in-place. 3 | """ 4 | def reverseList(head): 5 | cur, prev = head, None 6 | while cur: 7 | cur.next, cur, prev = prev, cur.next, cur 8 | return prev 9 | -------------------------------------------------------------------------------- /Google/Problem#73.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the head of a singly linked list, reverse it in-place. 3 | """ 4 | def reverseList(head): 5 | prev = None 6 | cur = head 7 | while cur: 8 | nxt = cur.next 9 | cur.next = prev 10 | prev = cur 11 | cur = nxt 12 | return prev -------------------------------------------------------------------------------- /Apple/Problem#233.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement the function fib(n), which returns the nth number in the Fibonacci sequence, using only O(1) space. 3 | """ 4 | def getNthFib(n): 5 | if n == 1: 6 | return 0 7 | elif n == 2: 8 | return 1 9 | a,b = 0,1 10 | for _ in range(3,n+1): 11 | a,b = b,a + b 12 | return b -------------------------------------------------------------------------------- /Google/Problem#747.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings A and B, return whether or not A can be shifted some number of times to get B. 3 | For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false. 4 | """ 5 | def is_rotation(A, B): 6 | if len(A) != len(B): 7 | return False 8 | 9 | return B in A + A 10 | -------------------------------------------------------------------------------- /Apple/Problem#451.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement the function fib(n), which returns the nth number in the Fibonacci sequence, 3 | using only O(1) space. 4 | """ 5 | # Time Complexity: O(n) 6 | # Space Complexity: O(1) 7 | def fib(n: int) -> int: 8 | if n <= 1: 9 | return n 10 | a, b = 0, 1 11 | for _ in range(2, n+1): 12 | a, b = b, a + b 13 | return b -------------------------------------------------------------------------------- /Amazon/Problem#224.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted array, find the smallest positive integer that is not the sum of a subset of the array. 3 | For example, for the input [1, 2, 3, 10], you should return 7. 4 | Do this in O(N) time. 5 | """ 6 | def getSmallest(arr): 7 | res = 1 8 | for no in arr: 9 | if res >= no: 10 | res += no 11 | else: 12 | return res 13 | return res -------------------------------------------------------------------------------- /Facebook/Problem#15.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. 3 | """ 4 | import random 5 | def pick(nums): 6 | randomElement = None 7 | for i,data in enumerate(nums): 8 | if i == 0: 9 | randomElement = data 10 | elif random.randint(1,i+1) == 1: 11 | randomElement = data 12 | return randomElement -------------------------------------------------------------------------------- /Google/Problem#649.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, return the first recurring character in it, or null if there is no recurring character. 3 | For example, given the string "acbbac", return "b". Given the string "abcdef", return null. 4 | """ 5 | def firstRepeatedChar(s): 6 | 7 | alphabets = set() 8 | 9 | for c in s: 10 | if c in alphabets: 11 | return c 12 | alphabets.add(c) 13 | 14 | return None 15 | -------------------------------------------------------------------------------- /Google/Problem#1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of numbers and a number k, return whether any two numbers from the list add up to k. 3 | For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. 4 | Bonus: Can you do this in one pass? 5 | """ 6 | def twoSum(arr,target): 7 | n = set() 8 | for i in arr: 9 | temp = target - i 10 | if temp in n: 11 | return True 12 | n.add(i) 13 | return False 14 | -------------------------------------------------------------------------------- /Google/Problem#560.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of numbers and a number k, return whether any two numbers from the list add up to k. 3 | For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. 4 | Bonus: Can you do this in one pass? 5 | """ 6 | def twoSum(arr,target): 7 | n = set() 8 | for i in arr: 9 | temp = target - i 10 | if temp in n: 11 | return True 12 | n.add(i) 13 | return False 14 | -------------------------------------------------------------------------------- /Palantir/Problem#202.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that checks whether an integer is a palindrome. For example, 121 is a palindrome, as well as 888. 678 is not a palindrome. 3 | Do not convert the integer into a string. 4 | """ 5 | def isPalindrome(x): 6 | if x < 0: 7 | return False 8 | rev = 0 9 | temp = x 10 | while temp > 0: 11 | rev = (rev * 10) + (temp % 10) 12 | temp //= 10 13 | return True if rev == x else False -------------------------------------------------------------------------------- /Google/Problem#83.py: -------------------------------------------------------------------------------- 1 | """ 2 | Invert a binary tree. 3 | 4 | For example, given the following tree: 5 | 6 | a 7 | / \ 8 | b c 9 | / \ / 10 | d e f 11 | should become: 12 | 13 | a 14 | / \ 15 | c b 16 | \ / \ 17 | f e d 18 | """ 19 | def invertTree(root): 20 | if not root: 21 | return None 22 | root.left, root.right = root.right, root.left 23 | invertTree(root.left) 24 | invertTree(root.right) 25 | return root -------------------------------------------------------------------------------- /Dropbox/Problem#212#719.py: -------------------------------------------------------------------------------- 1 | """ 2 | Spreadsheets often use this alphabetical encoding for its columns: "A", "B", "C", ..., "AA", "AB", ..., "ZZ", "AAA", "AAB", .... 3 | Given a column number, return its alphabetical column id. For example, given 1, return "A". Given 27, return "AA". 4 | """ 5 | def convertToTitle(n): 6 | column_number = 0 7 | for i in range(len(s)): 8 | column_number += ((ord(s[-1-i]) - 64) * (26**i)) 9 | return column_number 10 | -------------------------------------------------------------------------------- /Amazon/Problem#184.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given n numbers, find the greatest common denominator between them. 3 | For example, given the numbers [42, 56, 14], return 14. 4 | """ 5 | def gcd(a,b): 6 | if b == 0: 7 | return a 8 | return gcd(b, a%b) 9 | 10 | def greatestDenominator(arr): 11 | if len(arr) == 1: 12 | return arr[0] 13 | gcdd = gcd(arr[0],arr[1]) 14 | for i in range(2,len(arr)): 15 | gcdd = gcd(gcdd,arr[i]) 16 | return gcdd -------------------------------------------------------------------------------- /Lyft/Problem#102.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of integers and a number K, return which contiguous elements of the list sum to K. 3 | For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4]. 4 | """ 5 | def subarraySum(nums, k): 6 | summ, d = 0, {} 7 | for i in range(len(nums)): 8 | summ += nums[i] 9 | if summ == k: 10 | return nums[:i+1] 11 | if summ - k in d: 12 | return nums[d[summ-k]+1:i+1] 13 | d[summ] = i -------------------------------------------------------------------------------- /Amazon/Problem#157.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, determine whether any permutation of it is a palindrome. 3 | 4 | For example, carrace should return true, since it can be rearranged to form racecar, which is a palindrome. 5 | daily should return false, since there's no rearrangement that can form a palindrome. 6 | """ 7 | def isPalindrome(s): 8 | temp = set() 9 | for c in s: 10 | if c in temp: 11 | temp.remove(c) 12 | else: 13 | temp.add(c) 14 | return len(temp) <= 1 -------------------------------------------------------------------------------- /MongoDB/Problem#155.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of elements, find the majority element, which appears more than half the time (> floor(len(lst) / 2.0)). 3 | 4 | You can assume that such element exists. 5 | For example, given [1, 2, 1, 1, 3, 4, 1], return 1. 6 | """ 7 | def majorityElement(nums): 8 | c,ans = 0,0 9 | for i in nums: 10 | if c == 0: 11 | c+=1 12 | ans = i 13 | elif ans == i: 14 | c += 1 15 | else: 16 | c -= 1 17 | return ans -------------------------------------------------------------------------------- /Amazon/Problem#372.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a natural number as input and returns the number of digits the input has. 3 | 4 | Constraint: don't use any loops. 5 | """ 6 | # Using Recursion 7 | def countDigit(n): 8 | if n == 0: 9 | return 0 10 | return 1 + countDigit(n // 10) 11 | 12 | # Using log 13 | # to understand https://math.stackexchange.com/a/231745 14 | # https://stackoverflow.com/a/24177168 15 | import math 16 | def countDigit_using_log(n): 17 | return math.floor(math.log(n, 10)+1) -------------------------------------------------------------------------------- /Facebook/Problem#51.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, 3 | write a function that shuffles a deck of cards represented as an array using only swaps. 4 | It should run in O(N) time. 5 | 6 | Hint: Make sure each one of the 52! permutations of the deck is equally likely. 7 | """ 8 | import random 9 | def shuffleCards(cards): 10 | for i in range(1,len(cards)): 11 | n = random.randint(0,i) 12 | cards[i], cards[n] = cards[n], cards[i] 13 | return cards -------------------------------------------------------------------------------- /Others/Problem#467.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a real number n, find the square root of n. For example, given n = 9, return 3. 3 | """ 4 | # Assuming we have to return an integer value. 5 | def mySqrt(x): 6 | if x == 0: 7 | return 0 8 | left, right = 1, x 9 | while left <= right: 10 | mid = (left + right) // 2 11 | squared = mid * mid 12 | if squared == x: 13 | return mid 14 | elif squared > x: 15 | right = mid - 1 16 | else: 17 | left = mid + 1 18 | return right -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Daily Coding Problems 2 | Solutions to Daily Coding Problem questions in Python 3 | 4 | ### Company Wise Questions: 5 | 6 | - [Google](Google) 7 | - [Facebook](Facebook) 8 | - [Microsoft](Microsoft) 9 | - [Amazon](Amazon) 10 | - [Uber](Uber) 11 | - [Apple](Apple) 12 | - [Stripe](Stripe) 13 | - [Twitter](Twitter) 14 | - [Jane Street](Jane-Street) 15 | - [MongoDB](MongoDB) 16 | - [Lyft](Lyft) 17 | - [Airbnb](Airbnb) 18 | - [Palantir](Palantir) 19 | - [IBM](IBM) 20 | - [Dropbox](Dropbox) 21 | - [Bloomberg](Bloomberg) 22 | - [Salesforce](Salesforce) 23 | - [Others](Others) 24 | -------------------------------------------------------------------------------- /Google/Problem#104#715.py: -------------------------------------------------------------------------------- 1 | """ 2 | Determine whether a doubly linked list is a palindrome. What if it’s singly linked? 3 | 4 | For example, 1 -> 4 -> 3 -> 4 -> 1 returns true while 1 -> 4 returns false. 5 | """ 6 | def isPalindromeSingly(head): 7 | rev = None 8 | slow = fast = head 9 | while fast and fast.next: 10 | fast = fast.next.next 11 | rev, rev.next, slow = slow, rev, slow.next 12 | if fast: 13 | slow = slow.next 14 | while rev and rev.data == slow.data: 15 | rev = rev.next 16 | slow = slow.next 17 | return not rev 18 | -------------------------------------------------------------------------------- /Amazon/Problem#197.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array and a number k that's smaller than the length of the array, rotate the array to the right k elements in-place. 3 | """ 4 | def rotate(nums, k): 5 | k = k % len(nums) 6 | count = start = 0 7 | while count < len(nums): 8 | cur = start 9 | prev = nums[start] 10 | while True: 11 | nextIndex = (cur + k) %len(nums) 12 | nums[nextIndex], prev = prev, nums[nextIndex] 13 | cur = nextIndex 14 | count += 1 15 | if start == cur: 16 | break 17 | start += 1 -------------------------------------------------------------------------------- /Google/Problem#26.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a singly linked list and an integer k, remove the kth last element from the list. 3 | k is guaranteed to be smaller than the length of the list. 4 | The list is very long, so making more than one pass is prohibitively expensive. 5 | Do this in constant space and in one pass. 6 | """ 7 | def removeKthFromEnd(head, k): 8 | p1 = p2 = head 9 | for i in range(k): 10 | p1 = p1.next 11 | if not p1: 12 | return p2.next 13 | while p1.next != None: 14 | p1 = p1.next 15 | p2 = p2.next 16 | p2.next = p2.next.next 17 | return head -------------------------------------------------------------------------------- /IBM/Problem#205.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer, find the next permutation of it in absolute order. For example, given 48975, the next permutation would be 49578. 3 | """ 4 | def nextPermutation(nums): 5 | i = len(nums) - 2 6 | while i >= 0 and nums[i] >= nums[i+1]: 7 | i -= 1 8 | if i >= 0: 9 | j = len(nums) - 1 10 | while j >= 0 and nums[j] <= nums[i]: 11 | j -= 1 12 | nums[i], nums[j] = nums[j], nums[i] 13 | i += 1 14 | j = len(nums) - 1 15 | while i < j: 16 | nums[i], nums[j] = nums[j], nums[i] 17 | i += 1 18 | j -= 1 -------------------------------------------------------------------------------- /Salesforce/Problem#327#422.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program to merge two binary trees. Each node in the new tree should hold a 3 | value equal to the sum of the values of the corresponding nodes of the input trees. 4 | If only one input tree has a node in a given position, the corresponding node in 5 | the new tree should match that input node. 6 | """ 7 | def mergeTrees(t1: TreeNode, t2: TreeNode) -> TreeNode: 8 | if not t1 or not t2: 9 | return t1 or t2 10 | t1.val += t2.val 11 | t1.left = mergeTrees(t1.left, t2.left) 12 | t1.right = mergeTrees(t1.right, t2.right) 13 | return t1 14 | -------------------------------------------------------------------------------- /Amazon/Problem#398.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a linked list and an integer k, remove the k-th node from the end of the list and return the head of the list. 3 | k is guaranteed to be smaller than the length of the list. 4 | Do this in one pass. 5 | """ 6 | def removeNthFromEnd(head, k): 7 | fast = head 8 | for i in range(k): 9 | fast = fast.next 10 | 11 | if not fast: 12 | return head.next 13 | 14 | slow = head 15 | while fast and fast.next: 16 | fast = fast.next 17 | slow = slow.next 18 | 19 | slow.next = slow.next.next 20 | 21 | return head 22 | -------------------------------------------------------------------------------- /Bloomberg/Problem#578.py: -------------------------------------------------------------------------------- 1 | """ 2 | Determine whether there exists a one-to-one character mapping from one string s1 to another s2. 3 | For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d. 4 | Given s1 = foo and s2 = bar, return false since the o cannot map to two characters. 5 | """ 6 | def isIsomorphic(s, t): 7 | d1 , d2 = {}, {} 8 | 9 | for i in range(len(s)): 10 | if d1.get(ord(s[i]),-1) != d2.get(ord(t[i]),-1): 11 | return False 12 | 13 | d1[ord(s[i])] = i 14 | d2[ord(t[i])] = i 15 | 16 | return True 17 | -------------------------------------------------------------------------------- /Google/Problem#164.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an array of length n + 1 whose elements belong to the set {1, 2, ..., n}. By the pigeonhole principle, 3 | there must be a duplicate. Find it in linear time and space. 4 | """ 5 | def findDuplicate(nums): 6 | tortoise = nums[0] 7 | hare = nums[0] 8 | while True: 9 | tortoise = nums[tortoise] 10 | hare = nums[nums[hare]] 11 | if tortoise == hare: 12 | break 13 | 14 | ptr1 = nums[0] 15 | ptr2 = tortoise 16 | while ptr1 != ptr2: 17 | ptr1 = nums[ptr1] 18 | ptr2 = nums[ptr2] 19 | return ptr1 -------------------------------------------------------------------------------- /Microsoft/Problem#70.py: -------------------------------------------------------------------------------- 1 | """ 2 | A number is considered perfect if its digits sum up to exactly 10. 3 | Given a positive integer n, return the n-th perfect number. 4 | For example, given 1, you should return 19. Given 2, you should return 28. 5 | """ 6 | def NthPerfect(n): 7 | count = 0 8 | curr = 19 9 | while True: 10 | summ = 0 11 | x = curr 12 | while x > 0: 13 | summ = summ + x % 10 14 | x //= 10 15 | if summ == 10: 16 | count+=1 17 | if count == n: 18 | return curr 19 | curr += 9 20 | return -1 -------------------------------------------------------------------------------- /Palantir/Problem#491.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that checks whether an integer is a palindrome. 3 | For example, 121 is a palindrome, as well as 888. 678 is not a palindrome. 4 | Do not convert the integer into a string. 5 | """ 6 | def isPalindrome_alternative(x): 7 | # If no is negative 8 | # If last digit is 0 and no is not 0 9 | if x < 0 or (x % 10 == 0 and x != 0): 10 | return False 11 | rev = 0 12 | while x > rev: 13 | rev = (rev*10) + (x%10) 14 | x //= 10 15 | # When the length is an odd number, we can get rid of the middle digit by rev/10 16 | return rev == x or rev//10 == x -------------------------------------------------------------------------------- /Amazon/Problem#534.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, determine whether any permutation of it is a palindrome. 3 | For example, carrace should return true, since it can be rearranged to form racecar, 4 | which is a palindrome. daily should return false, since there's no rearrangement that 5 | can form a palindrome. 6 | """ 7 | # Time Complexity: O(N), N -> length of s 8 | # Space Complexity: O(1) 9 | def palindromePermutation(s): 10 | alphabets = set() 11 | for c in s: 12 | if c in alphabets: 13 | alphabets.remove(c) 14 | else: 15 | alphabets.add(c) 16 | return len(alphabets) <= 1 17 | -------------------------------------------------------------------------------- /Apple/Problem#273.py: -------------------------------------------------------------------------------- 1 | """ 2 | A fixed point in an array is an element whose value is equal to its index. 3 | Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return False. 4 | For example, given [-6, 0, 2, 40], you should return 2. Given [1, 5, 7, 8], you should return False. 5 | """ 6 | def fixed_point(arr): 7 | start, end = 0, len(arr)-1 8 | while start <= end: 9 | mid = (start+end)//2 10 | if arr[mid] == mid: 11 | return mid 12 | elif arr[mid] < mid: 13 | start = mid + 1 14 | else: 15 | end = mid - 1 16 | return False -------------------------------------------------------------------------------- /Facebook/Problem#424.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers in which two elements appear exactly once and all other 3 | elements appear exactly twice, find the two elements that appear only once. 4 | 5 | For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. The order does not matter. 6 | Follow-up: Can you do this in linear time and constant space? 7 | """ 8 | def singleNumber(nums: List[int]) -> List[int]: 9 | xor = 0 10 | for no in nums: 11 | xor ^= no 12 | res = [0, 0] 13 | xor &= -xor 14 | for no in nums: 15 | if xor & no == 0: 16 | res[0] ^= no 17 | else: 18 | res[1] ^= no 19 | return res -------------------------------------------------------------------------------- /Amazon/Problem#49.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of numbers, find the maximum sum of any contiguous subarray of the array. 3 | For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 4 | 42, 14, -5, and 86. 5 | Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements. 6 | Do this in O(N) time. 7 | """ 8 | def maxSubArray(nums): 9 | if len(nums) == 0: 10 | return 0 11 | Sum = 0 12 | result = Sum 13 | for i in range(len(nums)): 14 | Sum = (Sum + nums[i]) if(Sum+nums[i]) >= nums[i] else nums[i] 15 | result = Sum if Sum > result else result 16 | return result -------------------------------------------------------------------------------- /Twitter/Problem#386.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string, sort it in decreasing order based on the frequency of characters. 3 | If there are multiple possible solutions, return any of them. 4 | For example, given the string tweet, return tteew. eettw would also be acceptable. 5 | """ 6 | def frequencySort(s: str) -> str: 7 | d1, d2 = {}, {} 8 | # counter of alphabets 9 | for c in s: 10 | d1[c] = d1.get(c, 0) + 1 11 | 12 | # make count as key and alphabets as value 13 | for k,v in d1.items(): 14 | d2[v] = d2.get(v, '') + k*v 15 | 16 | res = '' 17 | for i in range(len(s), -1, -1): 18 | if i in d2: 19 | res += d2[i] 20 | return res -------------------------------------------------------------------------------- /Google/Problem#118.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted list of integers, square the elements and give the output in sorted order. 3 | For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81]. 4 | """ 5 | def sortedSquares(A): 6 | l = len(A) 7 | j = 0 8 | while j < l and A[j] < 0: 9 | j += 1 10 | i = j - 1 11 | res = [] 12 | while i >= 0 and j < l: 13 | if A[i]**2 < A[j]**2: 14 | res.append(A[i]**2) 15 | i -= 1 16 | else: 17 | res.append(A[j]**2) 18 | j += 1 19 | while i >= 0: 20 | res.append(A[i]**2) 21 | i -= 1 22 | while j < l: 23 | res.append(A[j]**2) 24 | j += 1 25 | return res -------------------------------------------------------------------------------- /Microsoft/Problem#107#752.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print the nodes in a binary tree level-wise. For example, the following should print 1, 2, 3, 4, 5. 3 | 4 | 1 5 | / \ 6 | 2 3 7 | / \ 8 | 4 5 9 | """ 10 | def traverse_level_order(root): 11 | if not root: 12 | return [] 13 | 14 | current, res = [root], [] 15 | 16 | while current: 17 | nex, temp = [], [] 18 | 19 | for n in current: 20 | temp.append(n.val) 21 | if n.left: 22 | nex.append(n.left) 23 | if n.right: 24 | nex.append(n.right) 25 | 26 | current = nex 27 | res.append(temp) 28 | 29 | return res 30 | 31 | -------------------------------------------------------------------------------- /Facebook/Problem#47.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a array of numbers representing the stock prices of a company in chronological order, 3 | write a function that calculates the maximum profit you could have made from buying and selling that stock once. 4 | You must buy before you can sell it. 5 | For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and 6 | sell it at 10 dollars. 7 | """ 8 | def maxProfit(prices): 9 | if not prices:return 0 10 | profit, buy = 0, prices[0] 11 | for price in prices: 12 | if price > buy: 13 | profit = (price-buy) if (price-buy) > profit else profit 14 | else: 15 | buy = price 16 | return profit -------------------------------------------------------------------------------- /Jane-Street/Problem#5.py: -------------------------------------------------------------------------------- 1 | """ 2 | cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. 3 | For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. 4 | 5 | Given this implementation of cons: 6 | def cons(a, b): 7 | def pair(f): 8 | return f(a, b) 9 | return pair 10 | Implement car and cdr. 11 | """ 12 | def cons(a, b): 13 | def pair(f): 14 | return f(a, b) 15 | return pair 16 | 17 | def car(f): 18 | def left(a, b): 19 | return a 20 | return f(left) 21 | 22 | def cdr(f): 23 | def right(a, b): 24 | return b 25 | return f(right) 26 | 27 | print(car(cons(3,4))) 28 | print(cdr(cons(3,4))) -------------------------------------------------------------------------------- /Amazon/Problem#12.py: -------------------------------------------------------------------------------- 1 | """ 2 | There's a staircase with N steps, and you can climb 1 or 2 steps at a time. Given N, write a function that 3 | returns the number of unique ways you can climb the staircase. The order of the steps matters. 4 | For example, if N is 4, then there are 5 unique ways: 5 | 6 | 1, 1, 1, 1 7 | 2, 1, 1 8 | 1, 2, 1 9 | 1, 1, 2 10 | 2, 2 11 | What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of 12 | positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. Generalize 13 | your function to take in X. 14 | """ 15 | def climbStairs(n): 16 | if n == 1: 17 | return 1 18 | a,b = 1,2 19 | for _ in range(2,n): 20 | a,b = b, a+b 21 | return b 22 | -------------------------------------------------------------------------------- /Uber/Problem#2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, return a new array such that each element at index i of the new array is the 3 | product of all the numbers in the original array except the one at i. 4 | 5 | For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. 6 | If our input was [3, 2, 1], the expected output would be [2, 3, 6]. 7 | 8 | Follow-up: what if you can't use division? 9 | """ 10 | def productExceptSelf(nums): 11 | p = 1 12 | n = len(nums) 13 | result = [] 14 | for i in range(0,n): 15 | result.append(p) 16 | p = p * nums[i] 17 | p = 1 18 | for i in range(n-1,-1,-1): 19 | result[i] = result[i] * p 20 | p = p * nums[i] 21 | return result 22 | -------------------------------------------------------------------------------- /Google/Problem#664.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree of integers, find the maximum path sum between two nodes. 3 | The path must go through at least one node, and does not need to go through the root. 4 | """ 5 | class Solution: 6 | def maxPathSum(self, root: TreeNode) -> int: 7 | self.ans = float('-inf') 8 | 9 | def helper(root): 10 | if not root: 11 | return 0 12 | 13 | l = helper(root.left) 14 | r = helper(root.right) 15 | cur = root.val 16 | 17 | cur_max = max(cur+l, cur, cur+r) 18 | self.ans = max(self.ans, cur_max, cur+l+r) 19 | 20 | return cur_max 21 | 22 | helper(root) 23 | return self.ans 24 | -------------------------------------------------------------------------------- /Facebook/Problem#168.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an N by N matrix, rotate it by 90 degrees clockwise. 3 | For example, given the following matrix: 4 | [[1, 2, 3], 5 | [4, 5, 6], 6 | [7, 8, 9]] 7 | 8 | you should return: 9 | [[7, 4, 1], 10 | [8, 5, 2], 11 | [9, 6, 3]] 12 | Follow-up: What if you couldn't use any extra space? 13 | """ 14 | def rotate(matrix): 15 | l = len(matrix) 16 | for layer in range(l//2): 17 | first,last = layer, l-1-layer 18 | for i in range(first,last): 19 | offset = i - first 20 | top = matrix[first][i] 21 | matrix[first][i] = matrix[last-offset][first] 22 | matrix[last-offset][first] = matrix[last][last-offset] 23 | matrix[last][last-offset] = matrix[i][last] 24 | matrix[i][last] = top -------------------------------------------------------------------------------- /Google/Problem#20.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical. 3 | For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. 4 | In this example, assume nodes with the same value are the exact same node objects. 5 | Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space. 6 | """ 7 | def getIntersectionNode(headA, headB): 8 | if headA == None or headB == None: 9 | return None 10 | A_pointer = headA 11 | B_pointer = headB 12 | while A_pointer != B_pointer: 13 | A_pointer = headB if A_pointer == None else A_pointer.next 14 | B_pointer = headA if B_pointer == None else B_pointer.next 15 | return A_pointer -------------------------------------------------------------------------------- /Facebook/Problem#216.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a number in Roman numeral format, convert it to decimal. 3 | 4 | The values of Roman numerals are as follows: 5 | { 6 | 'M': 1000, 7 | 'D': 500, 8 | 'C': 100, 9 | 'L': 50, 10 | 'X': 10, 11 | 'V': 5, 12 | 'I': 1 13 | } 14 | In addition, note that the Roman numeral system uses subtractive notation for numbers such as IV and XL. 15 | For the input XIV, for instance, you should return 14. 16 | """ 17 | def romanToInt(s): 18 | dic={'I':1,'V':5,'X':10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 19 | num = prev = dic[s[-1]] 20 | for i in range(len(s)-2,-1,-1): 21 | val = dic[s[i]] 22 | if val < prev: 23 | num -= val 24 | else: 25 | num += val 26 | prev = val 27 | return num -------------------------------------------------------------------------------- /Google/Problem#568.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted list of integers, square the elements and give the output in sorted order. 3 | For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81]. 4 | """ 5 | def sortedSquares(A): 6 | l = len(A) 7 | j = 0 8 | while j < l and A[j] < 0: 9 | j += 1 10 | i = j - 1 11 | res = [] 12 | while i >= 0 and j < l: 13 | if A[i]**2 < A[j]**2: 14 | res.append(A[i]**2) 15 | i -= 1 16 | else: 17 | res.append(A[j]**2) 18 | j += 1 19 | 20 | while i >= 0: 21 | res.append(A[i]**2) 22 | i -= 1 23 | while j < l: 24 | res.append(A[j]**2) 25 | j += 1 26 | return res -------------------------------------------------------------------------------- /Apple/Problem#580.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, find a minimum path sum from root to a leaf. 3 | For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15. 4 | 10 5 | / \ 6 | 5 5 7 | \ \ 8 | 2 1 9 | / 10 | -1 11 | """ 12 | class Solution: 13 | def minPathSum(self, root: TreeNode) -> int: 14 | self.ans = float('inf') 15 | 16 | def helper(root, cur_sum=0): 17 | if not root: 18 | self.ans = min(self.ans, cur_sum) 19 | return 0 20 | 21 | cur_sum += root.val 22 | l = helper(root.left, cur_sum) 23 | r = helper(root.right, cur_sum) 24 | cur_sum -= root.val 25 | 26 | helper(root) 27 | 28 | return self.ans 29 | -------------------------------------------------------------------------------- /Facebook/Problem#69.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a list of integers, return the largest product that can be made by multiplying any three integers. 3 | For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5. 4 | You can assume the list has at least three integers. 5 | """ 6 | def maximumProduct(nums): 7 | min1 = min2 = float('inf') 8 | max1 = max2 = max3 = -float('inf') 9 | for i in nums: 10 | if i <= min1: 11 | min2 = min1 12 | min1 = i 13 | elif i <= min2: 14 | min2 = i 15 | if i >= max1: 16 | max3 = max2 17 | max2 = max1 18 | max1 = i 19 | elif i >= max2: 20 | max3 = max2 21 | max2 = i 22 | elif i >= max3: 23 | max3 = i 24 | return max(min1*min2*max1, max1*max2*max3) -------------------------------------------------------------------------------- /Apple/Problem#53.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the 3 | following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. 4 | """ 5 | class MyQueue: 6 | 7 | def __init__(self): 8 | self.s1 = [] 9 | self.s2 = [] 10 | 11 | def enqueue(self, x): 12 | self.s1.append(x) 13 | 14 | def dequeue(self): 15 | if self.empty(): 16 | return None 17 | self.shiftStack() 18 | return self.s2.pop() 19 | 20 | def shiftStack(self): 21 | if len(self.s2) == 0: 22 | while self.s1: 23 | self.s2.append(self.s1.pop()) 24 | 25 | def empty(self): 26 | return True if (len(self.s1)+len(self.s2)) <= 0 else False -------------------------------------------------------------------------------- /Facebook/Problem#117.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the level of the tree with minimum sum. 3 | """ 4 | def minLevelSum(root): 5 | level = minLevel = 0 6 | if not root: 7 | return minLevel 8 | 9 | queue = [[root]] 10 | minSum = float('inf') 11 | 12 | while queue: 13 | level += 1 14 | levelNodes = queue.pop(0) 15 | nextLevel = [] 16 | levelSum = 0 17 | while levelNodes: 18 | node = levelNodes.pop() 19 | levelSum +=node.val 20 | if node.left: 21 | nextLevel.append(node.left) 22 | if node.right: 23 | nextLevel.append(node.right) 24 | if nextLevel: 25 | queue.append(nextLevel) 26 | if levelSum < minSum: 27 | minSum = levelSum 28 | minLevel = level 29 | return minLevel 30 | -------------------------------------------------------------------------------- /Google/Problem#35.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that 3 | all the Rs come first, the Gs come second, and the Bs come last. You can only swap elements of the array. 4 | 5 | Do this in linear time and in-place. 6 | For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B']. 7 | """ 8 | def sortColors(arr): 9 | if arr is None: return 10 | index, low, high = 0, 0, len(arr) - 1 11 | while(low <= high): 12 | if arr[low] == 'G': 13 | low += 1 14 | elif arr[low] == 'R': 15 | arr[index], arr[low] = arr[low], arr[index] 16 | index += 1 17 | low += 1 18 | elif arr[low] == 'B': 19 | arr[high], arr[low] = arr[low], arr[high] 20 | high -= 1 21 | return arr -------------------------------------------------------------------------------- /Facebook/Problem#426.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a binary tree, return the level of the tree with minimum sum. 3 | """ 4 | def minLevelSum(root: TreeNode) -> int: 5 | level = min_level = 0 6 | if not root: 7 | return min_level 8 | queue = [[root]] 9 | min_sum = float('inf') 10 | while queue: 11 | level += 1 12 | level_nodes = queue.pop(0) 13 | next_level = [] 14 | level_sum = 0 15 | while level_nodes: 16 | node = level_nodes.pop() 17 | level_sum +=node.val 18 | if node.left: 19 | next_level.append(node.left) 20 | if node.right: 21 | next_level.append(node.right) 22 | if next_level: 23 | queue.append(next_level) 24 | if level_sum < min_sum: 25 | min_sum = level_sum 26 | min_level = level 27 | return min_level -------------------------------------------------------------------------------- /Facebook/Problem#79.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, write a function to determine whether the array could become non-decreasing by modifying at most 1 element. 3 | For example, given the array [10, 5, 7], you should return true, since we can modify the 10 into a 1 to make the array non-decreasing. 4 | Given the array [10, 5, 1], you should return false, since we can't modify any one element to get a non-decreasing array. 5 | """ 6 | def checkPossibility(nums): 7 | if len(nums) <= 2: 8 | return True 9 | 10 | count = index = 0 11 | for i in range(0,len(nums)-1): 12 | if nums[i] > nums[i+1]: 13 | index = i 14 | count += 1 15 | if count > 1: 16 | return False 17 | 18 | if index ==0 or index == len(nums)-2: 19 | return True 20 | return nums[index] <= nums[index+2] or nums[index+1] >= nums[index-1] -------------------------------------------------------------------------------- /Google/Problem#145#714.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the head of a singly linked list, swap every two nodes and return its head. 3 | For example, given 1 -> 2 -> 3 -> 4, return 2 -> 1 -> 4 -> 3. 4 | """ 5 | def swapPairs(head): 6 | 7 | ### Iterative Method 8 | # if not head: 9 | # return None 10 | # cur = head.next if head.next else head 11 | # prev = None 12 | # while head and head.next: 13 | # temp = head.next 14 | # head.next = head.next.next 15 | # temp.next = head 16 | # head = head.next 17 | # if prev: 18 | # prev.next = temp 19 | # prev = temp.next 20 | # return cur 21 | 22 | # Recursive Method 23 | if head is None or head.next is None: 24 | return head 25 | nextHead = head.next.next 26 | newHead = head.next 27 | head.next.next = head 28 | head.next = swapPairs(nextHead) 29 | return newHead 30 | -------------------------------------------------------------------------------- /Google/Problem#448.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of strictly the characters 'R', 'G', and 'B', segregate the values 3 | of the array so that all the Rs come first, the Gs come second, and the Bs come last. 4 | You can only swap elements of the array. 5 | 6 | Do this in linear time and in-place. 7 | 8 | For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should 9 | become ['R', 'R', 'R', 'G', 'G', 'B', 'B']. 10 | """ 11 | # Time Complexity: O(N) 12 | # Space Comlexity: O(1) 13 | def sortColors(colors): 14 | index, low, high = 0, 0, len(colors) - 1 15 | while low <= high: 16 | if colors[low] == 'G': 17 | low += 1 18 | elif colors[low] == 'R': 19 | colors[index], colors[low] = colors[low], colors[index] 20 | index += 1 21 | low += 1 22 | else: 23 | colors[high], colors[low] = colors[low], colors[high] 24 | high -= 1 -------------------------------------------------------------------------------- /Airbnb/Problem#177#699.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Given a linked list and a positive integer k, rotate the list to the right by k places. 4 | For example, given the linked list 7 -> 7 -> 3 -> 5 and k = 2, it should become 3 -> 5 -> 7 -> 7. 5 | Given the linked list 1 -> 2 -> 3 -> 4 -> 5 and k = 3, it should become 3 -> 4 -> 5 -> 1 -> 2. 6 | """ 7 | def rotateRight(head, k): 8 | if not head: 9 | return 10 | l = length(head) 11 | k = k % l 12 | if l == 1 or k % l == 0: 13 | return head 14 | count = 0 15 | curr = head 16 | while count < l-k: 17 | prev = head 18 | head = head.next 19 | count += 1 20 | prev.next = None 21 | result = head 22 | while head.next: 23 | head = head.next 24 | head.next = curr 25 | return result 26 | 27 | 28 | def length(head): 29 | count = 0 30 | while head: 31 | count += 1 32 | head = head.next 33 | return count 34 | -------------------------------------------------------------------------------- /Microsoft/Problem#50.py: -------------------------------------------------------------------------------- 1 | """ 2 | Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one 3 | of '+', '−', '∗', or '/'. 4 | 5 | Given the root to such a tree, write a function to evaluate it. 6 | For example, given the following tree: 7 | 8 | * 9 | / \ 10 | + + 11 | / \ / \ 12 | 3 2 4 5 13 | 14 | You should return 45, as it is (3 + 2) * (4 + 5). 15 | """ 16 | def evaluate(root): 17 | if root is None: 18 | return 0 19 | if root.left is None and root.right is None: 20 | return int(root.data) 21 | leftSum = evaluate(root.left) 22 | rightSum = evaluate(root.right) 23 | if root.data == '+': 24 | return leftSum + rightSum 25 | elif root.data == '-': 26 | return leftSum - rightSum 27 | elif root.data == '*': 28 | return leftSum * rightSum 29 | elif root.data == '/' : 30 | return leftSum // rightSum -------------------------------------------------------------------------------- /Microsoft/Problem#127.py: -------------------------------------------------------------------------------- 1 | """ 2 | Let's represent an integer in a linked list format by having each node represent a digit in the number. The nodes make up the number in reversed order. 3 | For example, the following linked list: 4 | 1 -> 2 -> 3 -> 4 -> 5 5 | is the number 54321. 6 | 7 | Given two linked lists in this format, return their sum in the same linked list format. 8 | For example, given 9 | 9 -> 9 10 | 5 -> 2 11 | return 124 (99 + 25) as: 12 | 4 -> 2 -> 1 13 | """ 14 | def addTwoNumbers(l1, l2): 15 | newL = ListNode(0) 16 | cur = newL 17 | carry = 0 18 | while l1 or l2: 19 | x = l1.val if l1 else 0 20 | y = l2.val if l2 else 0 21 | summ = x + y + carry 22 | carry = summ // 10 23 | cur.next = ListNode(summ%10) 24 | cur = cur.next 25 | if l1: 26 | l1 = l1.next 27 | if l2: 28 | l2 = l2.next 29 | if carry: 30 | cur.next = ListNode(carry) 31 | return newL.next -------------------------------------------------------------------------------- /Google/Problem#113.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string of words delimited by spaces, reverse the words in string. 3 | For example, given "hello world here", return "here world hello" 4 | Follow-up: given a mutable string representation, can you perform this operation in-place? 5 | """ 6 | def reverseWords(s): 7 | s = list(s) 8 | startIndex = 0 9 | endIndex = len(s)-1 10 | while s[startIndex] == ' ': 11 | startIndex += 1 12 | while s[endIndex] == ' ': 13 | endIndex -= 1 14 | 15 | start = startIndex 16 | end = start 17 | for i in range(startIndex,endIndex+1): 18 | if s[i] == ' ': 19 | reverseWord(s,start,end-1) 20 | start = end+1 21 | end += 1 22 | reverseWord(s,start,end-1) 23 | reverseWord(s,startIndex,endIndex) 24 | return "".join(s[startIndex:endIndex+1]) 25 | 26 | def reverseWord(s,start,end): 27 | while start < end: 28 | s[start],s[end] = s[end],s[start] 29 | start += 1 30 | end -= 1 31 | -------------------------------------------------------------------------------- /Amazon/Problem#58.py: -------------------------------------------------------------------------------- 1 | """ 2 | An sorted array of integers was rotated an unknown number of times. 3 | Given such an array, find the index of the element in the array in faster than linear time. 4 | If the element doesn't exist in the array, return null. 5 | For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array). 6 | You can assume all the integers in the array are unique. 7 | """ 8 | def search(nums, target): 9 | start = 0 10 | end = len(nums) - 1 11 | while start <= end: 12 | mid = (start + end)//2 13 | if nums[mid] == target: 14 | return mid 15 | elif nums[start] <= nums[mid]: 16 | if target >= nums[start] and target < nums[mid]: 17 | end = mid -1 18 | else: 19 | start = mid + 1 20 | else: 21 | if target <= nums[end] and target > nums[mid]: 22 | start = mid + 1 23 | else: 24 | end = mid - 1 25 | return None # If element not present in the array. -------------------------------------------------------------------------------- /Microsoft/Problem#452.py: -------------------------------------------------------------------------------- 1 | """ 2 | Let's represent an integer in a linked list format by having each node represent a digit in the number. 3 | The nodes make up the number in reversed order. 4 | 5 | For example, the following linked list: 6 | 1 -> 2 -> 3 -> 4 -> 5 7 | is the number 54321. 8 | 9 | Given two linked lists in this format, return their sum in the same linked list format. 10 | For example, given 11 | 9 -> 9 12 | 5 -> 2 13 | return 124 (99 + 25) as: 14 | 4 -> 2 -> 1 15 | """ 16 | class ListNode: 17 | def __init__(self, x): 18 | self.val = x 19 | self.next = None 20 | 21 | class Solution: 22 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 23 | res = cur = ListNode(0) 24 | nodes_sum = 0 25 | while l1 or l2 or nodes_sum: 26 | if l1: 27 | nodes_sum += l1.val 28 | l1 = l1.next 29 | if l2: 30 | nodes_sum += l2.val 31 | l2 = l2.next 32 | cur.next = ListNode(nodes_sum % 10) 33 | cur = cur.next 34 | nodes_sum //= 10 35 | return res.next 36 | -------------------------------------------------------------------------------- /Amazon/Problem#43#746.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement a stack that has the following methods: 3 | push(val), which pushes an element onto the stack 4 | pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, 5 | then it should throw an error or return null. 6 | max(), which returns the maximum value in the stack currently. If there are no elements in the stack, 7 | then it should throw an error or return null. 8 | Each method should run in constant time. 9 | """ 10 | class maxStack: 11 | def __init__(self): 12 | self.stack = [] 13 | self.maxS = [] 14 | 15 | def push(self, data): 16 | self.stack.append(data) 17 | if not self.maxS or self.maxS[-1] <= data: 18 | self.maxS.append(data) 19 | 20 | def pop(self): 21 | if not self.stack: 22 | return None 23 | popData = self.stack.pop() 24 | if self.maxS[-1] == popData: 25 | self.maxS.pop() 26 | return popData 27 | 28 | def max(self): 29 | if not self.maxS: 30 | return None 31 | return self.maxS[-1] 32 | -------------------------------------------------------------------------------- /Amazon/Problem#29.py: -------------------------------------------------------------------------------- 1 | """ 2 | Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. 3 | For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". 4 | Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. 5 | You can assume the string to be decoded is valid. 6 | """ 7 | class stringCompression: 8 | def encode(self, s): 9 | result = [] 10 | i = 0 11 | while i < len(s): 12 | char = s[i] 13 | charCount = 0 14 | while i < len(s) and s[i] == char: 15 | charCount += 1 16 | i += 1 17 | result.append(str(charCount)) 18 | result.append(char) 19 | return "".join(result) 20 | 21 | def decode(self, s): 22 | result = [] 23 | for i in range(0,len(s),2): 24 | countChar = int(s[i]) 25 | result.append(s[i+1]*countChar) 26 | return "".join(result) 27 | 28 | x = stringCompression() 29 | print(x.encode("AAAABBBCCDAA")) 30 | print(x.decode("4A3B2C1D2A")) -------------------------------------------------------------------------------- /Amazon/Problem#65.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. 3 | 4 | For example, given the following matrix: 5 | [[1, 2, 3, 4, 5], 6 | [6, 7, 8, 9, 10], 7 | [11, 12, 13, 14, 15], 8 | [16, 17, 18, 19, 20]] 9 | 10 | You should print out the following: 11 | 1 12 | 2 13 | 3 14 | 4 15 | 5 16 | 10 17 | 15 18 | 20 19 | 19 20 | 18 21 | 17 22 | 16 23 | 11 24 | 6 25 | 7 26 | 8 27 | 9 28 | 14 29 | 13 30 | 12 31 | """ 32 | def spiralOrder(matrix): 33 | if matrix == []: 34 | return [] 35 | top = left = 0 36 | bottom = len(matrix) - 1 37 | right = len(matrix[0]) - 1 38 | direction = 0 39 | while top <= bottom and left <= right: 40 | if direction == 0: 41 | for i in range(left,right+1): 42 | print(matrix[top][i]) 43 | top += 1 44 | elif direction == 1: 45 | for i in range(top,bottom+1): 46 | print(matrix[i][right]) 47 | right -= 1 48 | elif direction == 2: 49 | for i in range(right,left-1,-1): 50 | print(matrix[bottom][i]) 51 | bottom -= 1 52 | elif direction == 3: 53 | for i in range(bottom, top-1, -1): 54 | print(matrix[i][left]) 55 | left += 1 56 | direction = (direction+1) % 4 -------------------------------------------------------------------------------- /Stripe/Problem#4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, find the first missing positive integer in linear time and constant space. 3 | In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. 4 | For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. 5 | """ 6 | def firstMissingPositive(nums): 7 | """ 8 | if nums == []: 9 | return 1 10 | for i in range(0,len(nums)): 11 | if nums[i] <= 0 or nums[i] > len(nums): 12 | continue 13 | val = nums[i] 14 | while nums[val-1] != val: 15 | nextVal = nums[val-1] 16 | nums[val-1] = val 17 | val = nextVal 18 | if val <= 0 or val > len(nums): 19 | break 20 | for i in range(0,len(nums)): 21 | if nums[i] != i+1: 22 | return i+1 23 | return len(nums)+1 24 | """ 25 | nums = list(set(nums)) + [0] 26 | n = len(nums) 27 | for i in range(len(nums)): # delete those useless elements 28 | if nums[i] < 0 or nums[i] >= n: 29 | nums[i] = 0 30 | for i in range(len(nums)): # use the index as the hash to record the frequency of each number 31 | nums[nums[i] % n] += n 32 | for i in range(1, len(nums)): 33 | if nums[i] // n == 0: 34 | return i 35 | return n 36 | -------------------------------------------------------------------------------- /Google/Problem#3.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), 3 | which deserializes the string back into the tree. 4 | 5 | For example, given the following Node class 6 | class Node: 7 | def __init__(self, val, left=None, right=None): 8 | self.val = val 9 | self.left = left 10 | self.right = right 11 | 12 | The following test should pass: 13 | node = Node('root', Node('left', Node('left.left')), Node('right')) 14 | assert deserialize(serialize(node)).left.left.val == 'left.left' 15 | """ 16 | class Codec: 17 | 18 | def serialize(self, root): 19 | def serializeHelper(root, string): 20 | if root is None: 21 | string += "None," 22 | else: 23 | string += str(root.val) + "," 24 | string = serializeHelper(root.left, string) 25 | string = serializeHelper(root.right, string) 26 | return string 27 | return serializeHelper(root,"") 28 | 29 | def deserialize(self, data): 30 | def deserializeHeper(l): 31 | if l[0] == "None": 32 | l.pop(0) 33 | return None 34 | root = TreeNode(l[0]) 35 | l.pop(0) 36 | root.left = deserializeHeper(l) 37 | root.right = deserializeHeper(l) 38 | return root 39 | return deserializeHeper(data.split(',')) 40 | --------------------------------------------------------------------------------