diff --git a/README.md b/README.md new file mode 100644 index 0000000..7094aa3 --- /dev/null +++ b/README.md @@ -0,0 +1,5623 @@ +# Daily Coding Problem Solutions + +## Problems + +### Problem 1 + +Given a list of numbers, return whether any two sums to k. +For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. + +Bonus: Can you do this in one pass? + +[Solution](Solutions/001.py) + +--- + +### Problem 2 + +This problem was asked by Uber. + +Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. + +For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. + +Follow-up: what if you can't use division? + +[Solution](Solutions/002.py) + +--- + +### Problem 3 + +This problem was asked by Google. + +Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. + +[Solution](Solutions/003.py) + +--- + +### Problem 4 + +This problem was asked by Stripe. + +Given an array of integers, find the first missing positive integer in linear time and constant space. 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. + +For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. + +You can modify the input array in-place. + +[Solution](Solutions/004.py) + +--- + +### Problem 5 + +This problem was asked by Jane Street. + +cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. + +Given this implementation of cons: + +```python +def cons(a, b): + return lambda f : f(a, b) +``` + +Implement car and cdr. + +[Solution](Solutions/005.py) + +--- + +### Problem 6 + +This problem was asked by Google. + +An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. + +If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. + +[Solution](Solutions/006.py) + +--- + +### Problem 7 + +This problem was asked by Facebook. + +Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. + +For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. + +You can assume that the messages are decodable. For example, '001' is not allowed. + +[Solution](Solutions/007.py) + +--- + +### Problem 8 + +This problem was asked by Google. + +A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. + +Given the root to a binary tree, count the number of unival subtrees. + +For example, the following tree has 5 unival subtrees: + +``` + 0 + / \ + 1 0 + / \ + 1 0 + / \ + 1 1 +``` + +[Solution](Solutions/008.py) + +--- + +### Problem 9 + +This problem was asked by Airbnb. + +Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. + +For example, [2, 4, 6, 8] should return 12, since we pick 4 and 8. [5, 1, 1, 5] should return 10, since we pick 5 and 5. + +[Solution](Solutions/009.py) + +--- + +### Problem 10 + +This problem was asked by Apple. + +Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds. + +[Solution](Solutions/010.py) + +--- + +### Problem 11 + +This problem was asked by Twitter. + +Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. + +For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. + +Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. + +[Solution](Solutions/011.py) + +--- + +### Problem 12 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 13 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 14 + +This problem was asked by Google. + +The area of a circle is defined as r^2. Estimate \pi to 3 decimal places using a Monte Carlo method. + +Hint: The basic equation of a circle is x^2 + y^2 = r^2. + +[Solution](Solutions/014.py) + +--- + +### Problem 15 + +This problem was asked by Facebook. + +Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. + +[Solution](Solutions/015.py) + +--- + +### Problem 16 + +This problem was asked by Twitter. + +You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: + +record(order_id): adds the order_id to the log +get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. +You should be as efficient with time and space as possible. + +[Solution](Solutions/016.py) + +--- + +### Problem 17 + +This problem was asked by Google. + +Suppose we represent our file system by a string in the following manner: + +The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: + +``` +dir + subdir1 + subdir2 + file.ext +``` + +The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. + +The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: + +``` +dir + subdir1 + file1.ext + subsubdir1 + subdir2 + subsubdir2 + file2.ext +``` + +The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. + +We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes). + +Given a string representing the file system in the above format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. + +[Solution](Solutions/017.py) + +--- + +### Problem 18 + +This problem was asked by Google. + +Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k. + +For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since: + +``` +10 = max(10, 5, 2) +7 = max(5, 2, 7) +8 = max(2, 7, 8) +8 = max(7, 8, 7) +``` + +Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results. You can simply print them out as you compute them. + +[Solution](Solutions/018.py) + +--- + +### Problem 19 + +This problem was asked by Facebook. + +A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. + +Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost which achieves this goal. + +[Solution](Solutions/019.py) + +--- + +### Problem 20 + +This problem was asked by Google. + +Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical. + +For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. + +In this example, assume nodes with the same value are the exact same node objects. + +Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space. + +[Solution](Solutions/020.py) + +--- + +### Problem 21 + +This problem was asked by Snapchat. + +Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. + +For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. + +[Solution](Solutions/021.py) + +--- + +### Problem 22 + +This problem was asked by Microsoft. + +Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. + +For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. + +Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. + +[Solution](Solutions/022.py) + +--- + +### Problem 23 + +This problem was asked by Google. + +You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on. + +Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board. + +For example, given the following board: + +``` +[[f, f, f, f], + [t, t, f, t], + [f, f, f, f], + [f, f, f, f]] +``` + +and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row. + +[Solution](Solutions/023.py) + +--- + +### Problem 24 + +This problem was asked by Google. + +Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked. + +Design a binary tree node class with the following methods: + +is_locked, which returns whether the node is locked +lock, which attempts to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true. +unlock, which unlocks the node. If it cannot be unlocked, then it should return false. Otherwise, it should unlock it and return true. +You may augment the node to add parent pointers or any other property you would like. You may assume the class is used in a single-threaded program, so there is no need for actual locks or mutexes. Each method should run in O(h), where h is the height of the tree. + +[Solution](Solutions/024.py) + +--- + +### Problem 25 + +This problem was asked by Facebook. + +Implement regular expression matching with the following special characters: + +- . (period) which matches any single character +- \* (asterisk) which matches zero or more of the preceding element + That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression. + +For example, given the regular expression "ra." and the string "ray", your function should return true. The same regular expression on the string "raymond" should return false. + +Given the regular expression `".*at"` and the string "chat", your function should return true. The same regular expression on the string "chats" should return false. + +[Solution](Solutions/025.py) + +--- + +### Problem 26 + +This problem was asked by Google. + +Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list. + +The list is very long, so making more than one pass is prohibitively expensive. + +Do this in constant space and in one pass. + +[Solution](Solutions/026.py) + +--- + +### Problem 27 + +This problem was asked by Facebook. + +Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). + +For example, given the string "([])[]({})", you should return true. + +Given the string "([)]" or "((()", you should return false. + +[Solution](Solutions/027.py) + +--- + +### Problem 28 + +This problem was asked by Palantir. + +Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified. + +More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left. + +If you can only fit one word on a line, then you should pad the right-hand side with spaces. + +Each word is guaranteed not to be longer than k. + +For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following: + +["the quick brown", # 1 extra space on the left +"fox jumps over", # 2 extra spaces distributed evenly +"the lazy dog"] # 4 extra spaces distributed evenly + +[Solution](Solutions/028.py) + +--- + +### Problem 29 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 30 + +You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up. + +Compute how many units of water remain trapped on the map in O(N) time and O(1) space. + +For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle. + +Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water. + +[Solution](Solutions/030.py) + +--- + +### Problem 31 + +This problem was asked by Google. + +The edit distance between two strings refers to the minimum number of character insertions, deletions, and substitutions required to change one string to the other. For example, the edit distance between "kitten" and "sitting" is three: substitute the "k" for "s", substitute the "e" for "i", and append a "g". + +Given two strings, compute the edit distance between them. + +[Solution](Solutions/031.py) + +--- + +### Problem 32 + +This problem was asked by Jane Street. + +Suppose you are given a table of currency exchange rates, represented as a 2D array. Determine whether there is a possible arbitrage: that is, whether there is some sequence of trades you can make, starting with some amount A of any currency, so that you can end up with some amount greater than A of that currency. + +There are no transaction costs and you can trade fractional quantities. + +[Solution](Solutions/032.py) + +--- + +### Problem 33 + +This problem was asked by Microsoft. + +Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element. + +Recall that the median of an even-numbered list is the average of the two middle numbers. + +For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out: + +``` +2 +1.5 +2 +3.5 +2 +2 +2 +``` + +[Solution](Solutions/033.py) + +--- + +### Problem 34 + +This problem was asked by Quora. + +Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically). + +For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically. + +As another example, given the string "google", you should return "elgoogle". + +[Solution](Solutions/034.py) + +--- + +### Problem 35 + +This problem was asked by Google. + +Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that all the Rs come first, the Gs come second, and the Bs come last. You can only swap elements of the array. + +Do this in linear time and in-place. + +For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B']. + +[Solution](Solutions/035.py) + +--- + +### Problem 36 + +This problem was asked by Dropbox. + +Given the root to a binary search tree, find the second largest node in the tree. + +[Solution](Solutions/036.py) + +--- + +### Problem 37 + +This problem was asked by Google. + +The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set. + +For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}. + +You may also use a list or array to represent a set. + +[Solution](Solutions/037.py) + +--- + +### Problem 38 + +This problem was asked by Microsoft. + +You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal. + +[Solution](Solutions/038.py) + +--- + +### Problem 39 + +This problem was asked by Dropbox. + +Conway's Game of Life takes place on an infinite two-dimensional board of square cells. Each cell is either dead or alive, and at each tick, the following rules apply: + +Any live cell with less than two live neighbours dies. +Any live cell with two or three live neighbours remains living. +Any live cell with more than three live neighbours dies. +Any dead cell with exactly three live neighbours becomes a live cell. +A cell neighbours another cell if it is horizontally, vertically, or diagonally adjacent. + +Implement Conway's Game of Life. It should be able to be initialized with a starting list of live cell coordinates and the number of steps it should run for. Once initialized, it should print out the board state at each step. Since it's an infinite board, print out only the relevant coordinates, i.e. from the top-leftmost live cell to bottom-rightmost live cell. + +You can represent a live cell with an asterisk `*` and a dead cell with a dot `.`. + +[Solution](Solutions/039.py) + +--- + +### Problem 40 + +This problem was asked by Google. + +Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer. + +For example, given `[6, 1, 3, 3, 3, 6, 6]`, return `1`. Given `[13, 19, 13, 13]`, return `19`. + +Do this in $O(N)$ time and $O(1)$ space. + +[Solution](Solutions/040.py) + +--- + +### Problem 41 + +This problem was asked by Facebook. + +Given an unordered list of flights taken by someone, each represented as (origin, destination) pairs, and a starting airport, compute the person's itinerary. If no such itinerary exists, return null. If there are multiple possible itineraries, return the lexicographically smallest one. All flights must be used in the itinerary. + +For example, given the list of flights [('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')] and starting airport 'YUL', you should return the list ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD']. + +Given the list of flights [('SFO', 'COM'), ('COM', 'YYZ')] and starting airport 'COM', you should return null. + +Given the list of flights [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')] and starting airport 'A', you should return the list ['A', 'B', 'C', 'A', 'C'] even though ['A', 'C', 'A', 'B', 'C'] is also a valid itinerary. However, the first one is lexicographically smaller. + +[Solution](Solutions/041.py) + +--- + +### Problem 42 + +This problem was asked by Google. + +Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k. If such a subset cannot be made, then return null. + +Integers can appear more than once in the list. You may assume all numbers in the list are positive. + +For example, given `S = [12, 1, 61, 5, 9, 2]` and `k = 24`, return [12, 9, 2, 1] since it sums up to 24. + +[Solution](Solutions/042.py) + +--- + +### Problem 43 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 44 + +This problem was asked by Google. + +We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. + +Given an array, count the number of inversions it has. Do this faster than O(N^2) time. + +You may assume each element in the array is distinct. + +For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. + +[Solution](Solutions/044.py) + +--- + +### Problem 45 + +This problem was asked by Two Sigma. + +Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive). + +[Solution](Solutions/045.py) + +--- + +### Problem 46 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 47 + +This problem was asked by Facebook. + +Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it. + +For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars. + +[Solution](Solutions/047.py) + +--- + +### Problem 48 + +This problem was asked by Google. + +Given pre-order and in-order traversals of a binary tree, write a function to reconstruct the tree. + +For example, given the following preorder traversal: + +``` +[a, b, d, e, c, f, g] +``` + +And the following inorder traversal: + +``` +[d, b, e, a, f, c, g] +``` + +You should return the following tree: + +``` + a + / \ + b c + / \ / \ +d e f g +``` + +[Solution](Solutions/048.py) + +--- + +### Problem 49 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 50 + +This problem was asked by Microsoft. + +Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'. + +Given the root to such a tree, write a function to evaluate it. + +For example, given the following tree: + +``` + * + / \ + + + + / \ / \ +3 2 4 5 +``` + +You should return 45, as it is (3 + 2) \* (4 + 5). + +[Solution](Solutions/050.py) + +--- + +### Problem 51 + +This problem was asked by Facebook. + +Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps. + +It should run in O(N) time. + +Hint: Make sure each one of the 52! permutations of the deck is equally likely. + +[Solution](Solutions/051.py) + +--- + +### Problem 52 + +This problem was asked by Google. + +Implement an LRU (Least Recently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods: + +set(key, value): sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least recently used item. +get(key): gets the value at key. If no such key exists, return null. +Each operation should run in O(1) time. + +[Solution](Solutions/052.py) + +--- + +### Problem 53 + +This problem was asked by Apple. + +Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. + +[Solution](Solutions/053.py) + +--- + +### Problem 54 + +This problem was asked by Dropbox. + +Sudoku is a puzzle where you're given a partially-filled 9 by 9 grid with digits. The objective is to fill the grid with the constraint that every row, column, and box (3 by 3 subgrid) must contain all of the digits from 1 to 9. + +Implement an efficient sudoku solver. + +[Solution](Solutions/054.py) + +--- + +### Problem 55 + +This problem was asked by Microsoft. + +Implement a URL shortener with the following methods: + +- shorten(url), which shortens the url into a six-character alphanumeric string, such as zLg6wl. +- restore(short), which expands the shortened string into the original url. If no such shortened string exists, return null. + +Hint: What if we enter the same URL twice? + +[Solution](Solutions/055.py) + +--- + +### Problem 56 + +This problem was asked by Google. + +Given an undirected graph represented as an adjacency matrix and an integer k, write a function to determine whether each vertex in the graph can be colored such that no two adjacent vertices share the same color using at most k colors. + +[Solution](Solutions/056.py) + +--- + +### Problem 57 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 58 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 59 + +This problem was asked by Google. + +Implement a file syncing algorithm for two computers over a low-bandwidth network. What if we know the files in the two computers are mostly the same? + +[Solution](Solutions/059.py) + +--- + +### Problem 60 + +This problem was asked by Facebook. + +Given a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same. + +For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55. + +Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't split it up into two subsets that add up to the same sum. + +[Solution](Solutions/060.py) + +--- + +### Problem 61 + +This problem was asked by Google. + +Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. + +Do this faster than the naive method of repeated multiplication. + +For example, pow(2, 10) should return 1024. + +[Solution](Solutions/061.py) + +--- + +### Problem 62 + +This problem was asked by Facebook. + +There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down. + +For example, given a 2 by 2 matrix, you should return 2, since there are two ways to get to the bottom-right: + +- Right, then down +- Down, then right + +Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right. + +[Solution](Solutions/062.py) + +--- + +### Problem 63 + +This problem was asked by Microsoft. + +Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down. + +For example, given the following matrix: + +``` +[['F', 'A', 'C', 'I'], + ['O', 'B', 'Q', 'P'], + ['A', 'N', 'O', 'B'], + ['M', 'A', 'S', 'S']] +``` + +and the target word 'FOAM', you should return true, since it's the leftmost column. Similarly, given the target word 'MASS', you should return true, since it's the last row. + +[Solution](Solutions/063.py) + +--- + +### Problem 64 + +This problem was asked by Google. + +A knight's tour is a sequence of moves by a knight on a chessboard such that all squares are visited once. + +Given N, write a function to return the number of knight's tours on an N by N chessboard. + +[Solution](Solutions/064.py) + +--- + +### Problem 65 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 66 + +This problem was asked by Square. + +Assume you have access to a function toss_biased() which returns 0 or 1 with a probability that's not 50-50 (but also not 0-100 or 100-0). You do not know the bias of the coin. + +Write a function to simulate an unbiased coin toss. + +[Solution](Solutions/066.py) + +--- + +### Problem 67 + +This problem was asked by Google. + +Implement an LFU (Least Frequently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods: + +- `set(key, value)`: sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least frequently used item. If there is a tie, then the least recently used key should be removed. +- `get(key)`: gets the value at key. If no such key exists, return null. + +Each operation should run in O(1) time. + +[Solution](Solutions/067.py) + +--- + +### Problem 68 + +This problem was asked by Google. + +On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that have another bishop located between them, i.e. bishops can attack through pieces. + +You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered the same as (2, 1). + +For example, given M = 5 and the list of bishops: + +``` +(0, 0) +(1, 2) +(2, 2) +(4, 0) +``` + +The board would look like this: + +``` +[b 0 0 0 0] +[0 0 b 0 0] +[0 0 b 0 0] +[0 0 0 0 0] +[b 0 0 0 0] +``` + +You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4. + +[Solution](Solutions/068.py) + +--- + +### Problem 69 + +This problem was asked by Facebook. + +Given a list of integers, return the largest product that can be made by multiplying any three integers. + +For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 _ -10 _ 5. + +You can assume the list has at least three integers. + +[Solution](Solutions/069.py) + +--- + +### Problem 70 + +A number is considered perfect if its digits sum up to exactly 10. + +Given a positive integer n, return the n-th perfect number. + +For example, given 1, you should return 19. Given 2, you should return 28. + +[Solution](Solutions/070.py) + +--- + +### Problem 71 + +This problem was asked by Two Sigma. + +Using a function rand7() that returns an integer from 1 to 7 (inclusive) with uniform probability, implement a function rand5() that returns an integer from 1 to 5 (inclusive). + +(repeated question - Problem 45) + +[Solution](Solutions/071.py) + +--- + +### Problem 72 + +This problem was asked by Google. + +In a directed graph, each node is assigned an uppercase letter. We define a path's value as the number of most frequently-occurring letter along that path. For example, if a path in the graph goes through "ABACA", the value of the path is 3, since there are 3 occurrences of 'A' on the path. + +Given a graph with n nodes and m directed edges, return the largest value path of the graph. If the largest value is infinite, then return null. + +The graph is represented with a string and an edge list. The i-th character represents the uppercase letter of the i-th node. Each tuple in the edge list (i, j) means there is a directed edge from the i-th node to the j-th node. Self-edges are possible, as well as multi-edges. + +For example, the following input graph: + +``` +ABACA +[(0, 1), + (0, 2), + (2, 3), + (3, 4)] +``` + +Would have maximum value 3 using the path of vertices `[0, 2, 3, 4], (A, A, C, A)`. + +The following input graph: + +``` +A +[(0, 0)] +``` + +Should return null, since we have an infinite loop. + +[Solution](Solutions/072.py) + +--- + +### Problem 73 + +This problem was asked by Google. + +Given the head of a singly linked list, reverse it in-place. + +[Solution](Solutions/073.py) + +--- + +### Problem 74 + +This problem was asked by Apple. + +Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i-th row and j-th column is (i + 1) _ (j + 1) (if 0-indexed) or i _ j (if 1-indexed). + +Given integers N and X, write a function that returns the number of times X appears as a value in an N by N multiplication table. + +For example, given N = 6 and X = 12, you should return 4, since the multiplication table looks like this: + +| | | | | | | +| --- | --- | --- | --- | --- | --- | +| 1 | 2 | 3 | 4 | 5 | 6 | +| 2 | 4 | 6 | 8 | 10 | 12 | +| 3 | 6 | 9 | 12 | 15 | 18 | +| 4 | 8 | 12 | 16 | 20 | 24 | +| 5 | 10 | 15 | 20 | 25 | 30 | +| 6 | 12 | 18 | 24 | 30 | 36 | + +And there are 4 12's in the table. + +[Solution](Solutions/074.py) + +--- + +### Problem 75 + +This problem was asked by Microsoft. + +Given an array of numbers, find the length of the longest increasing subsequence in the array. The subsequence does not necessarily have to be contiguous. + +For example, given the array `[0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]`, the longest increasing subsequence has length 6: it is `0, 2, 6, 9, 11, 15`. + +[Solution](Solutions/075.py) + +--- + +### Problem 76 + +This problem was asked by Google. + +You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is lexicographically later as you go down each row. It does not matter whether each row itself is ordered lexicographically. + +For example, given the following table: + +``` +cba +daf +ghi +``` + +This is not ordered because of the a in the center. We can remove the second column to make it ordered: + +``` +ca +df +gi +``` + +So your function should return 1, since we only needed to remove 1 column. + +As another example, given the following table: + +``` +abcdef +``` + +Your function should return 0, since the rows are already ordered (there's only one row). + +As another example, given the following table: + +``` +zyx +wvu +tsr +``` + +Your function should return 3, since we would need to remove all the columns to order it. + +[Solution](Solutions/076.py) + +--- + +### Problem 77 + +This problem was asked by Snapchat. + +Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged. + +The input list is not necessarily ordered in any way. + +For example, given `[(1, 3), (5, 8), (4, 10), (20, 25)]`, you should return `[(1, 3), (4, 10), (20, 25)]`. + +[Solution](Solutions/077.py) + +--- + +### Problem 78 + +This problem was asked recently by Google. + +Given k sorted singly linked lists, write a function to merge all the lists into one sorted singly linked list. + +[Solution](Solutions/078.py) + +--- + +### Problem 79 + +This problem was asked by Facebook. + +Given an array of integers, write a function to determine whether the array could become non-decreasing by modifying at most 1 element. + +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. + +Given the array `[10, 5, 1]`, you should return false, since we can't modify any one element to get a non-decreasing array. + +[Solution](Solutions/079.py) + +--- + +### Problem 80 + +This problem was asked by Google. + +Given the root of a binary tree, return a deepest node. For example, in the following tree, return d. + +``` + a + / \ + b c + / +d +``` + +[Solution](Solutions/080.py) + +--- + +### Problem 81 + +This problem was asked by Yelp. + +Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit. + +For example if `{'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], }` then `"23"` should return `['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']`. + +[Solution](Solutions/081.py) + +--- + +### Problem 82 + +This problem was asked Microsoft. + +Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters. + +For example, given a file with the content "Hello world", three read7() returns "Hello w", "orld" and then "". + +[Solution](Solutions/082/082.py) + +--- + +### Problem 83 + +This problem was asked by Google. + +Invert a binary tree. + +For example, given the following tree: + +``` + a + / \ + b c + / \ / +d e f +``` + +should become: + +``` + a + / \ + c b + \ / \ + f e d +``` + +[Solution](Solutions/083.py) + +--- + +### Problem 84 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 85 + +This problem was asked by Facebook. + +Given three 32-bit integers x, y, and b, return x if b is 1 and y if b is 0, using only mathematical or bit operations. You can assume b can only be 1 or 0. + +[Solution](Solutions/085.py) + +--- + +### Problem 86 + +This problem was asked by Google. + +Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid (i.e. each open parenthesis is eventually closed). + +For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we must remove all of them. + +[Solution](Solutions/086.py) + +--- + +### Problem 87 + +This problem was asked by Uber. + +A rule looks like this: + +`A NE B` + +This means this means point A is located northeast of point B. + +`A SW C` + +means that point A is southwest of C. + +Given a list of rules, check if the sum of the rules validate. For example: + +``` +A N B +B NE C +C N A +``` + +does not validate, since A cannot be both north and south of C. + +``` +A NW B +A N B +``` + +is considered valid. + +[Solution](Solutions/087.py) + +--- + +### Problem 88 + +This question was asked by ContextLogic. + +Implement division of two positive integers without using the division, multiplication, or modulus operators. Return the quotient as an integer, ignoring the remainder. + +[Solution](Solutions/088.py) + +--- + +### Problem 89 + +This problem was asked by LinkedIn. + +Determine whether a tree is a valid binary search tree. + +A binary search tree is a tree with two children, left and right, and satisfies the constraint that the key in the left child must be less than or equal to the root and the key in the right child must be greater than or equal to the root. + +[Solution](Solutions/089.py) + +--- + +### Problem 90 + +This question was asked by Google. + +Given an integer n and a list of integers l, write a function that randomly generates a number from 0 to n-1 that isn't in l (uniform). + +[Solution](Solutions/090.py) + +--- + +### Problem 91 + +This problem was asked by Dropbox. + +What does the below code snippet print out? How can we fix the anonymous functions to behave as we'd expect? + +```python +functions = [] +for i in range(10): + functions.append(lambda : i) + +for f in functions: + print(f()) +``` + +[Solution](Solutions/091.py) + +--- + +### Problem 92 + +This problem was asked by Airbnb. + +We're given a hashmap with a key courseId and value a list of courseIds, which represents that the prerequsite of courseId is courseIds. Return a sorted ordering of courses such that we can finish all courses. + +Return null if there is no such ordering. + +For example, given `{'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}`, should return `['CSC100', 'CSC200', 'CSCS300']`. + +[Solution](Solutions/092.py) + +--- + +### Problem 93 + +This problem was asked by Apple. + +Given a tree, find the largest tree/subtree that is a BST. + +Given a tree, return the size of the largest tree/subtree that is a BST. + +[Solution](Solutions/093.py) + +--- + +### Problem 94 + +This problem was asked by Google. + +Given a binary tree of integers, find the maximum path sum between two nodes. The path must go through at least one node, and does not need to go through the root. + +[Solution](Solutions/094.py) + +--- + +### Problem 95 + +This problem was asked by Palantir. + +Given a number represented by a list of digits, find the next greater permutation of a number, in terms of lexicographic ordering. If there is not greater permutation possible, return the permutation with the lowest value/ordering. + +For example, the list `[1,2,3]` should return `[1,3,2]`. The list `[1,3,2]` should return `[2,1,3]`. The list `[3,2,1]` should return `[1,2,3]`. + +Can you perform the operation without allocating extra memory (disregarding the input memory)? + +[Solution](Solutions/095.py) + +--- + +### Problem 96 + +This problem was asked by Microsoft. + +Given a number in the form of a list of digits, return all possible permutations. + +For example, given `[1,2,3]`, return `[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]`. + +[Solution](Solutions/096.py) + +--- + +### Problem 97 + +This problem was asked by Stripe. + +Write a map implementation with a get function that lets you retrieve the value of a key at a particular time. + +It should contain the following methods: + +``` + set(key, value, time): # sets key to value for t = time. + get(key, time): # gets the key at t = time. +``` + +The map should work like this. If we set a key at a particular time, it will maintain that value forever or until it gets set at a later time. In other words, when we get a key at a time, it should return the value that was set for that key set at the most recent time. + +Consider the following examples: + +``` +d.set(1, 1, 0) # set key 1 to value 1 at time 0 +d.set(1, 2, 2) # set key 1 to value 2 at time 2 +d.get(1, 1) # get key 1 at time 1 should be 1 +d.get(1, 3) # get key 1 at time 3 should be 2 + +d.set(1, 1, 5) # set key 1 to value 1 at time 5 +d.get(1, 0) # get key 1 at time 0 should be null +d.get(1, 10) # get key 1 at time 10 should be 1 + +d.set(1, 1, 0) # set key 1 to value 1 at time 0 +d.set(1, 2, 0) # set key 1 to value 2 at time 0 +d.get(1, 0) # get key 1 at time 0 should be 2 +``` + +[Solution](Solutions/097.py) + +--- + +### Problem 98 + +This problem was asked by Coursera. + +Given a 2D board of characters and a word, find if the word exists in the grid. + +The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. + +For example, given the following board: + +``` +[ + ['A','B','C','E'], + ['S','F','C','S'], + ['A','D','E','E'] +] +``` + +`exists(board, "ABCCED")` returns true, `exists(board, "SEE")` returns true, `exists(board, "ABCB")` returns false. + +[Solution](Solutions/098.py) + +--- + +### Problem 99 + +This problem was asked by Microsoft. + +Given an unsorted array of integers, find the length of the longest consecutive elements sequence. + +For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4. + +Your algorithm should run in O(n) complexity. + +[Solution](Solutions/099.py) + +--- + +### Problem 100 + +This problem was asked by Google. + +You are in an infinite 2D grid where you can move in any of the 8 directions: + +``` + (x,y) to + (x+1, y), + (x - 1, y), + (x, y+1), + (x, y-1), + (x-1, y-1), + (x+1,y+1), + (x-1,y+1), + (x+1,y-1) +``` + +You are given a sequence of points and the order in which you need to cover the points. Give the minimum number of steps in which you can achieve it. You start from the first point. + +Example: +Input: `[(0, 0), (1, 1), (1, 2)]` +Output: 2 +It takes 1 step to move from (0, 0) to (1, 1). It takes one more step to move from (1, 1) to (1, 2). + +[Solution](Solutions/100.py) + +--- + +### Problem 101 + +This problem was asked by Alibaba. + +Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number. + +A solution will always exist. See Goldbach’s conjecture. + +Example: + +Input: 4 +Output: 2 + 2 = 4 +If there are more than one solution possible, return the lexicographically smaller solution. + +If `[a, b]` is one solution with `a <= b`, and `[c, d]` is another solution with `c <= d`, then + +```python +[a, b] < [c, d] +if a < c or a==c and b < d. +``` + +[Solution](Solutions/101.py) + +--- + +### Problem 102 + +This problem was asked by Lyft. + +Given a list of integers and a number K, return which contiguous elements of the list sum to K. + +For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4]. + +[Solution](Solutions/102.py) + +--- + +### Problem 103 + +This problem was asked by Square. + +Given a string and a set of characters, return the shortest substring containing all the characters in the set. + +For example, given the string "figehaeci" and the set of characters {a, e, i}, you should return "aeci". + +If there is no substring containing all the characters in the set, return null. + +[Solution](Solutions/103.py) + +--- + +### Problem 104 + +This problem was asked by Google. + +Determine whether a doubly linked list is a palindrome. What if it’s singly linked? + +For example, `1 -> 4 -> 3 -> 4 -> 1` returns true while `1 -> 4` returns false. + +[Solution](Solutions/104.py) + +--- + +### Problem 105 + +This problem was asked by Facebook. + +Given a function f, and N return a debounced f of N milliseconds. + +That is, as long as the debounced f continues to be invoked, f itself will not be called for N milliseconds. + +[Solution](Solutions/105.py) + +--- + +### Problem 106 + +This problem was asked by Pinterest. + +Given an integer list where each number represents the number of hops you can make, determine whether you can reach to the last index starting at index 0. + +For example, `[2, 0, 1, 0]` returns `true` while `[1, 1, 0, 1]` returns `false`. + +[Solution](Solutions/106.py) + +--- + +### Problem 107 + +This problem was asked by Microsoft. + +Print the nodes in a binary tree level-wise. For example, the following should print `1, 2, 3, 4, 5`. + +``` + 1 + / \ +2 3 + / \ + 4 5 +``` + +[Solution](Solutions/107.py) + +--- + +### Problem 108 + +This problem was asked by Google. + +Given two strings A and B, return whether or not A can be shifted some number of times to get B. + +For example, if A is `abcde` and B is `cdeab`, return true. If A is `abc` and B is `acb`, return false. + +[Solution](Solutions/108.py) + +--- + +### Problem 109 + +This problem was asked by Cisco. + +Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on. + +For example, `10101010` should be `01010101`. `11100010` should be `11010001`. + +Bonus: Can you do this in one line? + +[Solution](Solutions/109.py) + +--- + +### Problem 110 + +This problem was asked by Facebook. + +Given a binary tree, return all paths from the root to leaves. + +For example, given the tree + +``` + 1 + / \ + 2 3 + / \ + 4 5 +``` + +it should return `[[1, 2], [1, 3, 4], [1, 3, 5]]`. + +[Solution](Solutions/110.py) + +--- + +### Problem 111 + +This problem was asked by Google. + +Given a word W and a string S, find all starting indices in S which are anagrams of W. + +For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4. + +[Solution](Solutions/111.py) + +--- + +### Problem 112 + +This problem was asked by Twitter. + +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. Assume that each node in the tree also has a pointer to its parent. + +According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself)." + +[Solution](Solutions/112.py) + +--- + +### Problem 113 + +This problem was asked by Google. + +Given a string of words delimited by spaces, reverse the words in string. For example, given "hello world here", return "here world hello" + +Follow-up: given a mutable string representation, can you perform this operation in-place? + +[Solution](Solutions/113.py) + +--- + +### Problem 114 + +This problem was asked by Facebook. + +Given a string and a set of delimiters, reverse the words in the string while maintaining the relative order of the delimiters. For example, given "hello/world:here", return "here/world:hello" + +Follow-up: Does your solution work for the following cases: "hello/world:here/", "hello//world:here" + +[Solution](Solutions/114.py) + +--- + +### Problem 115 + +This problem was asked by Google. + +Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. + +[Solution](Solutions/115.py) + +--- + +### Problem 116 + +This problem was asked by Jane Street. + +Generate a finite, but an arbitrarily large binary tree quickly in `O(1)`. + +That is, `generate()` should return a tree whose size is unbounded but finite. + +[Solution](Solutions/116.py) + +--- + +### Problem 117 + +This problem was asked by Facebook. + +Given a binary tree, return the level of the tree with minimum sum. + +[Solution](Solutions/117.py) + +--- + +### Problem 118 + +This problem was asked by Google. + +Given a sorted list of integers, square the elements and give the output in sorted order. + +For example, given `[-9, -2, 0, 2, 3]`, return `[0, 4, 4, 9, 81]`. + +[Solution](Solutions/118.py) + +--- + +### Problem 119 + +This problem was asked by Google. + +Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them. + +For example, given the intervals `[0, 3], [2, 6], [3, 4], [6, 9]`, one set of numbers that covers all these intervals is `{3, 6}`. + +[Solution](Solutions/119.py) + +--- + +### Problem 120 + +This problem was asked by Microsoft. + +Implement the singleton pattern with a twist. First, instead of storing one instance, store two instances. And in every even call of getInstance(), return the first instance and in every odd call of getInstance(), return the second instance. + +[Solution](Solutions/120.py) + +--- + +### Problem 121 + +This problem was asked by Google. + +Given a string which we can delete at most k, return whether you can make a palindrome. + +For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get 'waterretaw'. + +[Solution](Solutions/121.py) + +--- + +### Problem 122 + +This question was asked by Zillow. + +You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at `matrix[0][0]`, and can only move right or down, find the maximum number of coins you can collect by the bottom right corner. + +For example, in this matrix + +``` +0 3 1 1 +2 0 0 4 +1 5 3 1 +``` + +The most we can collect is `0 + 2 + 1 + 5 + 3 + 1 = 12` coins. + +[Solution](Solutions/122.py) + +--- + +### Problem 123 + +This problem was asked by LinkedIn. + +Given a string, return whether it represents a number. Here are the different kinds of numbers: + +- "10", a positive integer +- "-10", a negative integer +- "10.1", a positive real number +- "-10.1", a negative real number +- "1e5", a number in scientific notation + +And here are examples of non-numbers: + +- "a" +- "x 1" +- "a -2" +- "-" + +[Solution](Solutions/123.py) + +--- + +### Problem 124 + +This problem was asked by Microsoft. + +You have 100 fair coins and you flip them all at the same time. Any that come up tails you set aside. The ones that come up heads you flip again. How many rounds do you expect to play before only one coin remains? + +Write a function that, given $n$, returns the number of rounds you'd expect to play until one coin remains. + +[Solution](Solutions/124.py) + +--- + +### Problem 125 + +This problem was asked by Google. + +Given the root of a binary search tree, and a target K, return two nodes in the tree whose sum equals K. + +For example, given the following tree and K of 20 + +``` + 10 + / \ + 5 15 + / \ + 11 15 +``` + +Return the nodes 5 and 15. + +[Solution](Solutions/125.py) + +--- + +### Problem 126 + +This problem was asked by Facebook. + +Write a function that rotates a list by k elements. For example, `[1, 2, 3, 4, 5, 6]` rotated by two becomes `[3, 4, 5, 6, 1, 2]`. Try solving this without creating a copy of the list. How many swap or move operations do you need? + +[Solution](Solutions/126.py) + +--- + +### Problem 127 + +This problem was asked by Microsoft. + +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. + +For example, the following linked list: + +`1 -> 2 -> 3 -> 4 -> 5` +is the number `54321`. + +Given two linked lists in this format, return their sum in the same linked list format. + +For example, given + +`9 -> 9` +`5 -> 2` +return `124 (99 + 25)` as: + +`4 -> 2 -> 1` + +[Solution](Solutions/127.py) + +--- + +### Problem 128 + +The Tower of Hanoi is a puzzle game with three rods and n disks, each a different size. + +All the disks start off on the first rod in a stack. They are ordered by size, with the largest disk on the bottom and the smallest one at the top. + +The goal of this puzzle is to move all the disks from the first rod to the last rod while following these rules: + +- You can only move one disk at a time. +- A move consists of taking the uppermost disk from one of the stacks and placing it on top of another stack. +- You cannot place a larger disk on top of a smaller disk. + +Write a function that prints out all the steps necessary to complete the Tower of Hanoi. You should assume that the rods are numbered, with the first rod being 1, the second (auxiliary) rod being 2, and the last (goal) rod being 3. + +For example, with n = 3, we can do this in 7 moves: + +- Move 1 to 3 +- Move 1 to 2 +- Move 3 to 2 +- Move 1 to 3 +- Move 2 to 1 +- Move 2 to 3 +- Move 1 to 3 + +[Solution](Solutions/128.py) + +--- + +### Problem 129 + +Given a real number n, find the square root of n. For example, given n = 9, return 3. + +[Solution](Solutions/129.py) + +--- + +### Problem 130 + +This problem was asked by Facebook. + +Given an array of numbers representing the stock prices of a company in chronological order and an integer k, return the maximum profit you can make from k buys and sells. You must buy the stock before you can sell it, and you must sell the stock before you can buy it again. + +For example, given `k = 2` and the array `[5, 2, 4, 0, 1]`, you should return `3`. + +[Solution](Solutions/130.py) + +--- + +### Problem 131 + +This question was asked by Snapchat. + +Given the head to a singly linked list, where each node also has a 'random' pointer that points to anywhere in the linked list, deep clone the list. + +[Solution](Solutions/131.py) + +--- + +### Problem 132 + +This question was asked by Riot Games. + +Design and implement a HitCounter class that keeps track of requests (or hits). It should support the following operations: + +- `record(timestamp)`: records a hit that happened at timestamp +- `total()`: returns the total number of hits recorded +- `range(lower, upper)`: returns the number of hits that occurred between timestamps lower and upper (inclusive) + +Follow-up: What if our system has limited memory? + +[Solution](Solutions/132.py) + +--- + +### Problem 133 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 134 + +This problem was asked by Facebook. + +You have a large array with most of the elements as zero. + +Use a more space-efficient data structure, SparseArray, that implements the same interface: + +- `init(arr, size)`: initialize with the original large array and size. +- `set(i, val)`: updates index at i with val. +- `get(i)`: gets the value at index i. + +[Solution](Solutions/134.py) + +--- + +### Problem 135 + +This question was asked by Apple. + +Given a binary tree, find a minimum path sum from root to a leaf. + +For example, the minimum path in this tree is `[10, 5, 1, -1]`, which has sum 15. + +``` + 10 + / \ +5 5 + \ \ + 2 1 + / + -1 +``` + +[Solution](Solutions/135.py) + +--- + +### Problem 136 + +This question was asked by Google. + +Given an N by M matrix consisting only of 1's and 0's, find the largest rectangle containing only 1's and return its area. + +For example, given the following matrix: + +``` +[[1, 0, 0, 0], + [1, 0, 1, 1], + [1, 0, 1, 1], + [0, 1, 0, 0]] +``` + +Return 4. + +[Solution](Solutions/136.py) + +--- + +### Problem 137 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 138 + +This problem was asked by Google. + +Find the minimum number of coins required to make n cents. + +You can use standard American denominations, that is, 1¢, 5¢, 10¢, and 25¢. + +For example, given n = 16, return 3 since we can make it with a 10¢, a 5¢, and a 1¢. + +[Solution](Solutions/138.py) + +--- + +### Problem 139 + +This problem was asked by Google. + +Given an iterator with methods next() and hasNext(), create a wrapper iterator, PeekableInterface, which also implements peek(). peek shows the next element that would be returned on next(). + +Here is the interface: + +``` +class PeekableInterface(object): + def __init__(self, iterator): + pass + + def peek(self): + pass + + def next(self): + pass + + def hasNext(self): + pass +``` + +[Solution](Solutions/139.py) + +--- + +### Problem 140 + +This problem was asked by Facebook. + +Given an array of integers in which two elements appear exactly once and all other elements appear exactly twice, find the two elements that appear only once. + +For example, given the array `[2, 4, 6, 8, 10, 2, 6, 10]`, return 4 and 8. The order does not matter. + +Follow-up: Can you do this in linear time and constant space? + +[Solution](Solutions/140.py) + +--- + +### Problem 141 + +This problem was asked by Microsoft. + +Implement 3 stacks using a single list: + +``` +class Stack: + def __init__(self): + self.list = [] + + def pop(self, stack_number): + pass + + def push(self, item, stack_number): + pass +``` + +[Solution](Solutions/141.py) + +--- + +### Problem 142 + +This problem was asked by Google. + +You're given a string consisting solely of `(`, `)`, and `*`. +`*` can represent either a `(`, `)`, or an empty string. Determine whether the parentheses are balanced. + +For example, `(()*` and `(*)` are balanced. `)*(` is not balanced. + +[Solution](Solutions/142.py) + +--- + +### Problem 143 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 144 + +This problem was asked by Google. + +Given an array of numbers and an index `i`, return the index of the nearest larger number of the number at index `i`, where distance is measured in array indices. + +For example, given `[4, 1, 3, 5, 6]` and index `0`, you should return `3`. + +If two distances to larger numbers are equal, then return any one of them. If the array at `i` doesn't have a nearest larger integer, then return `null`. + +Follow-up: If you can preprocess the array, can you do this in constant time? + +[Solution](Solutions/144.py) + +--- + +### Problem 145 + +This problem was asked by Google. + +Given the head of a singly linked list, swap every two nodes and return its head. + +For example, given `1 -> 2 -> 3 -> 4`, return `2 -> 1 -> 4 -> 3`. + +[Solution](Solutions/145.py) + +--- + +### Problem 146 + +This question was asked by BufferBox. + +Given a binary tree where all nodes are either 0 or 1, prune the tree so that subtrees containing all 0s are removed. + +For example, given the following tree: + +``` + 0 + / \ + 1 0 + / \ + 1 0 + / \ + 0 0 +``` + +should be pruned to: + +``` + 0 + / \ + 1 0 + / + 1 +``` + +We do not remove the tree at the root or its left child because it still has a 1 as a descendant. + +[Solution](Solutions/146.py) + +--- + +### Problem 147 + +Given a list, sort it using this method: `reverse(lst, i, j)`, which sorts `lst` from `i` to `j`. + +[Solution](Solutions/147.py) + +--- + +### Problem 148 + +This problem was asked by Apple. + +Gray code is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions. + +Given a number of bits `n`, generate a possible gray code for it. + +For example, for `n = 2`, one gray code would be `[00, 01, 11, 10]`. + +[Solution](Solutions/148.py) + +--- + +### Problem 149 + +This problem was asked by Goldman Sachs. + +Given a list of numbers `L`, implement a method `sum(i, j)` which returns the sum from the sublist `L[i:j]` (including i, excluding j). + +For example, given `L = [1, 2, 3, 4, 5]`, `sum(1, 3)` should return `sum([2, 3])`, which is `5`. + +You can assume that you can do some pre-processing. `sum()` should be optimized over the pre-processing step. + +[Solution](Solutions/149.py) + +--- + +### Problem 150 + +This problem was asked by LinkedIn. + +Given a list of points, a central point, and an integer k, find the nearest k points from the central point. + +For example, given the list of points `[(0, 0), (5, 4), (3, 1)]`, the central point `(1, 2)`, and `k = 2`, return `[(0, 0), (3, 1)]`. + +[Solution](Solutions/150.py) + +--- + +### Problem 151 + +Given a 2-D matrix representing an image, a location of a pixel in the screen and a color C, replace the color of the given pixel and all adjacent same colored pixels with C. + +For example, given the following matrix, and location pixel of `(2, 2)`, and `'G'` for green: + +``` +B B W +W W W +W W W +B B B +``` + +Becomes + +``` +B B G +G G G +G G G +B B B +``` + +[Solution](Solutions/151.py) + +--- + +### Problem 152 + +This problem was asked by Triplebyte. + +You are given `n` numbers as well as `n` probabilities that sum up to `1`. Write a function to generate one of the numbers with its corresponding probability. + +For example, given the numbers `[1, 2, 3, 4]` and probabilities `[0.1, 0.5, 0.2, 0.2]`, your function should return `1` `10%` of the time, `2` `50%` of the time, and `3` and `4` `20%` of the time. + +You can generate random numbers between 0 and 1 uniformly. + +[Solution](Solutions/152.py) + +--- + +### Problem 153 + +Find an efficient algorithm to find the smallest distance (measured in number of words) between any two given words in a string. + +For example, given words "hello", and "world" and a text content of "dog cat hello cat dog dog hello cat world", return 1 because there's only one word "cat" in between the two words. + +[Solution](Solutions/153.py) + +--- + +### Problem 154 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 155 + +Given a list of elements, find the majority element, which appears more than half the times `(> floor(len(lst) / 2.0))`. + +You can assume that such an element exists. + +For example, given `[1, 2, 1, 1, 3, 4, 0]`, return `1`. + +[Solution](Solutions/155.py) + +--- + +### Problem 156 + +This problem was asked by Facebook. + +Given a positive integer `n`, find the smallest number of squared integers which sum to `n`. + +For example, given n = `13`, return `2` since `13 = 3^2 + 2^2 = 9 + 4`. + +Given `n = 27`, return `3` since `27 = 3^2 + 3^2 + 3^2 = 9 + 9 + 9`. + +[Solution](Solutions/156.py) + +--- + +### Problem 157 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 158 + +This problem was asked by Slack. + +You are given an `N * M` matrix of `0`s and `1`s. Starting from the top left corner, how many ways are there to reach the bottom right corner? + +You can only move right and down. `0` represents an empty space while `1` represents a wall you cannot walk through. + +For example, given the following matrix: + +``` +[[0, 0, 1], + [0, 0, 1], + [1, 0, 0]] +``` + +Return `2`, as there are only two ways to get to the bottom right: + +- `Right, down, down, right` +- `Down, right, down, right` + +The top left corner and bottom right corner will always be `0`. + +[Solution](Solutions/158.py) + +--- + +### Problem 159 + +This problem was asked by Google. + +Given a string, return the first recurring character in it, or `null` if there is no recurring chracter. + +For example, given the string `"acbbac"`, return `"b"`. Given the string `"abcdef"`, return `null`. + +[Solution](Solutions/159.py) + +--- + +### Problem 160 + +This problem was asked by Uber. + +Given a tree where each edge has a weight, compute the length of the longest path in the tree. + +For example, given the following tree: + +``` + a + /|\ + b c d + / \ + e f + / \ + g h +``` + +and the weights: `a-b: 3`, `a-c: 5`, `a-d: 8`, `d-e: 2`, `d-f: 4`, `e-g: 1`, `e-h: 1`, the longest path would be `c -> a -> d -> f`, with a length of `17`. + +The path does not have to pass through the root, and each node can have any amount of children. + +[Solution](Solutions/160.py) + +--- + +### Problem 161 + +This problem was asked by Facebook. + +Given a 32-bit integer, return the number with its bits reversed. + +For example, given the binary number `1111 0000 1111 0000 1111 0000 1111 0000`, return `0000 1111 0000 1111 0000 1111 0000 1111`. + +[Solution](Solutions/161.py) + +--- + +### Problem 162 + +This problem was asked by Square. + +Given a list of words, return the shortest unique prefix of each word. For example, given the list: + +- dog +- cat +- apple +- apricot +- fish + +Return the list: + +- d +- c +- app +- apr +- f + +[Solution](Solutions/162.py) + +--- + +### Problem 163 + +This problem was asked by Jane Street. + +Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it. + +The expression is given as a list of numbers and operands. For example: `[5, 3, '+']` should return `5 + 3 = 8`. + +For example, `[15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']` should return `5`, since it is equivalent to `((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5`. + +You can assume the given expression is always valid. + +[Solution](Solutions/163.py) + +--- + +### Problem 164 + +This problem was asked by Google. + +You are given an array of length n + 1 whose elements belong to the set `{1, 2, ..., n}`. By the pigeonhole principle, there must be a duplicate. Find it in linear time and space. + +[Solution](Solutions/164.py) + +--- + +### Problem 165 + +This problem was asked by Google. + +Given an array of integers, return a new array where each element in the new array is the number of smaller elements to the right of that element in the original input array. + +For example, given the array `[3, 4, 9, 6, 1]`, return `[1, 1, 2, 1, 0]`, since: + +- There is 1 smaller element to the right of `3` +- There is 1 smaller element to the right of `4` +- There are 2 smaller elements to the right of `9` +- There is 1 smaller element to the right of `6` +- There are no smaller elements to the right of `1` + +[Solution](Solutions/165.py) + +--- + +### Problem 166 + +This problem was asked by Uber. + +Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods: + +- `next()`: returns the next element in the array of arrays. If there are no more elements, raise an exception. +- `has_next()`: returns whether or not the iterator still has elements left. + +For example, given the input `[[1, 2], [3], [], [4, 5, 6]]`, calling `next()` repeatedly should output `1, 2, 3, 4, 5, 6`. + +Do not use flatten or otherwise clone the arrays. Some of the arrays can be empty. + +[Solution](Solutions/166.py) + +--- + +### Problem 167 + +This problem was asked by Airbnb. + +Given a list of words, find all pairs of unique indices such that the concatenation of the two words is a palindrome. + +For example, given the list `["code", "edoc", "da", "d"]`, return `[(0, 1), (1, 0), (2, 3)]`. + +[Solution](Solutions/167.py) + +--- + +### Problem 168 + +This problem was asked by Facebook. + +Given an N by N matrix, rotate it by 90 degrees clockwise. + +For example, given the following matrix: + +``` +[[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] +``` + +you should return: + +``` +[[7, 4, 1], + [8, 5, 2], + [9, 6, 3]] +``` + +Follow-up: What if you couldn't use any extra space? + +[Solution](Solutions/168.py) + +--- + +### Problem 169 + +This problem was asked by Google. + +Given a linked list, sort it in `O(n log n)` time and constant space. + +For example, the linked list `4 -> 1 -> -3 -> 99` should become `-3 -> 1 -> 4 -> 99`. + +[Solution](Solutions/169.py) + +--- + +### Problem 170 + +This problem was asked by Facebook. + +Given a start word, an end word, and a dictionary of valid words, find the shortest transformation sequence from start to end such that only one letter is changed at each step of the sequence, and each transformed word exists in the dictionary. If there is no possible transformation, return null. Each word in the dictionary have the same length as start and end and is lowercase. + +For example, given `start = "dog"`, `end = "cat"`, and `dictionary = {"dot", "dop", "dat", "cat"}`, return `["dog", "dot", "dat", "cat"]`. + +Given `start = "dog"`, `end = "cat"`, and `dictionary = {"dot", "tod", "dat", "dar"}`, return null as there is no possible transformation from dog to cat. + +[Solution](Solutions/170.py) + +--- + +### Problem 171 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 172 + +This problem was asked by Dropbox. + +Given a string `s` and a list of words `words`, where each word is the same length, find all starting indices of substrings in `s` that is a concatenation of every word in `words` exactly once. + +For example, given `s = "dogcatcatcodecatdog"` and `words = ["cat", "dog"]`, return `[0, 13]`, since `"dogcat"` starts at index `0` and `"catdog"` starts at index `13`. + +Given `s = "barfoobazbitbyte"` and `words = ["dog", "cat"]`, return `[]` since there are no substrings composed of `"dog"` and `"cat"` in `s`. + +The order of the indices does not matter. + +[Solution](Solutions/172.py) + +--- + +### Problem 173 + +This problem was asked by Stripe. + +Write a function to flatten a nested dictionary. Namespace the keys with a period. + +For example, given the following dictionary: + +``` +{ + "key": 3, + "foo": { + "a": 5, + "bar": { + "baz": 8 + } + } +} +``` + +it should become: + +``` +{ + "key": 3, + "foo.a": 5, + "foo.bar.baz": 8 +} +``` + +You can assume keys do not contain dots in them, i.e. no clobbering will occur. + +[Solution](Solutions/173.py) + +--- + +### Problem 174 + +This problem was asked by Microsoft. + +Describe and give an example of each of the following types of polymorphism: + +- Ad-hoc polymorphism +- Parametric polymorphism +- Subtype polymorphism + +[Solution](Solutions/174.md) + +--- + +### Problem 175 + +This problem was asked by Google. + +You are given a starting state start, a list of transition probabilities for a Markov chain, and a number of steps num_steps. Run the Markov chain starting from start for num_steps and compute the number of times we visited each state. + +For example, given the starting state `a`, number of steps `5000`, and the following transition probabilities: + +``` +[ + ('a', 'a', 0.9), + ('a', 'b', 0.075), + ('a', 'c', 0.025), + ('b', 'a', 0.15), + ('b', 'b', 0.8), + ('b', 'c', 0.05), + ('c', 'a', 0.25), + ('c', 'b', 0.25), + ('c', 'c', 0.5) +] +``` + +One instance of running this Markov chain might produce `{'a': 3012, 'b': 1656, 'c': 332 }`. + +[Solution](Solutions/175.py) + +--- + +### Problem 176 + +This problem was asked by Bloomberg. + +Determine whether there exists a one-to-one character mapping from one string `s1` to another `s2`. + +For example, given `s1 = abc` and `s2 = bcd`, return `true` since we can map `a` to `b`, `b` to `c`, and `c` to `d`. + +Given `s1 = foo` and `s2 = bar`, return `false` since the `o` cannot map to two characters. + +[Solution](Solutions/176.py) + +--- + +### Problem 177 + +This problem was asked by Airbnb. + +Given a linked list and a positive integer `k`, rotate the list to the right by `k` places. + +For example, given the linked list `7 -> 7 -> 3 -> 5` and `k = 2`, it should become `3 -> 5 -> 7 -> 7`. + +Given the linked list `1 -> 2 -> 3 -> 4 -> 5` and `k = 3`, it should become `3 -> 4 -> 5 -> 1 -> 2`. + +[Solution](Solutions/177.py) + +--- + +### Problem 178 + +This problem was asked by Two Sigma. + +Alice wants to join her school's Probability Student Club. Membership dues are computed via one of two simple probabilistic games. + +The first game: roll a die repeatedly. Stop rolling once you get a five followed by a six. Your number of rolls is the amount you pay, in dollars. + +The second game: same, except that the stopping condition is a five followed by a five. + +Which of the two games should Alice elect to play? Does it even matter? Write a program to simulate the two games and calculate their expected value. + +[Solution](Solutions/178.py) + +--- + +### Problem 179 + +This problem was asked by Google. + +Given the sequence of keys visited by a postorder traversal of a binary search tree, reconstruct the tree. + +For example, given the sequence `2, 4, 3, 8, 7, 5`, you should construct the following tree: + +``` + 5 + / \ + 3 7 + / \ \ +2 4 8 +``` + +[Solution](Solutions/179.py) + +--- + +### Problem 180 + +This problem was asked by Google. + +Given a stack of `N` elements, interleave the first half of the stack with the second half reversed using only one other queue. This should be done in-place. + +Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue. + +For example, if the stack is `[1, 2, 3, 4, 5]`, it should become `[1, 5, 2, 4, 3]`. If the stack is `[1, 2, 3, 4]`, it should become `[1, 4, 2, 3]`. + +Hint: Try working backwards from the end state. + +[Solution](Solutions/180.py) + +--- + +### Problem 181 + +This problem was asked by Google. + +Given a string, split it into as few strings as possible such that each string is a palindrome. + +For example, given the input string `"racecarannakayak"`, return `["racecar", "anna", "kayak"]`. + +Given the input string `"abc"`, return `["a", "b", "c"]`. + +[Solution](Solutions/181.py) + +--- + +### Problem 182 + +This problem was asked by Facebook. + +A graph is minimally-connected if it is connected and there is no edge that can be removed while still leaving the graph connected. For example, any binary tree is minimally-connected. + +Given an undirected graph, check if the graph is minimally-connected. You can choose to represent the graph as either an adjacency matrix or adjacency list. + +[Solution](Solutions/182.py) + +--- + +### Problem 183 + +This problem was asked by Twitch. + +Describe what happens when you type a URL into your browser and press Enter. + +[Solution](Solutions/183.md) + +--- + +### Problem 184 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 185 + +This problem was asked by Google. + +Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don't intersect, return `0`. + +For example, given the following rectangles: + +``` +{ + "top_left": (1, 4), + "dimensions": (3, 3) # width, height +} +``` + +and + +``` +{ + "top_left": (0, 5), + "dimensions" (4, 3) # width, height +} +``` + +return `6`. + +[Solution](Solutions/185.py) + +--- + +### Problem 186 + +This problem was asked by Microsoft. + +Given an array of positive integers, divide the array into two subsets such that the difference between the sum of the subsets is as small as possible. + +For example, given `[5, 10, 15, 20, 25]`, return the sets `{10, 25}` and `{5, 15, 20}`, which has a difference of `5`, which is the smallest possible difference. + +[Solution](Solutions/186.py) + +--- + +### Problem 187 + +This problem was asked by Google. + +You are given given a list of rectangles represented by min and max x- and y-coordinates. Compute whether or not a pair of rectangles overlap each other. If one rectangle completely covers another, it is considered overlapping. + +For example, given the following rectangles: + +``` +{ + "top_left": (1, 4), + "dimensions": (3, 3) # width, height +}, +{ + "top_left": (-1, 3), + "dimensions": (2, 1) +}, +{ + "top_left": (0, 5), + "dimensions": (4, 3) +} +``` + +return `true` as the first and third rectangle overlap each other. + +[Solution](Solutions/187.py) + +--- + +### Problem 188 + +This problem was asked by Google. + +What will this code print out? + +``` +def make_functions(): + flist = [] + + for i in [1, 2, 3]: + def print_i(): + print(i) + flist.append(print_i) + + return flist + +functions = make_functions() +for f in functions: + f() +``` + +How can we make it print out what we apparently want? + +[Solution](Solutions/188.py) + +--- + +### Problem 189 + +This problem was asked by Google. + +Given an array of elements, return the length of the longest subarray where all its elements are distinct. + +For example, given the array `[5, 1, 3, 5, 2, 3, 4, 1]`, return `5` as the longest subarray of distinct elements is `[5, 2, 3, 4, 1]`. + +[Solution](Solutions/189.py) + +--- + +### Problem 190 + +This problem was asked by Facebook. + +Given a circular array, compute its maximum subarray sum in `O(n)` time. + +For example, given `[8, -1, 3, 4]`, return `15` as we choose the numbers `3`, `4`, and `8` where the `8` is obtained from wrapping around. + +Given `[-4, 5, 1, 0]`, return `6` as we choose the numbers `5` and `1`. + +[Solution](Solutions/190.py) + +--- + +### Problem 191 + +This problem was asked by Stripe. + +Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. + +Intervals can "touch", such as `[0, 1]` and `[1, 2]`, but they won't be considered overlapping. + +For example, given the intervals `(7, 9), (2, 4), (5, 8)`, return `1` as the last interval can be removed and the first two won't overlap. + +The intervals are not necessarily sorted in any order. + +[Solution](Solutions/191.py) + +--- + +### Problem 192 + +This problem was asked by Google. + +You are given an array of nonnegative integers. Let's say you start at the beginning of the array and are trying to advance to the end. You can advance at most, the number of steps that you're currently on. Determine whether you can get to the end of the array. + +For example, given the array `[1, 3, 1, 2, 0, 1]`, we can go from indices `0 -> 1 -> 3 -> 5`, so return `true`. + +Given the array `[1, 2, 1, 0, 0]`, we can't reach the end, so return `false`. + +[Solution](Solutions/192.py) + +--- + +### Problem 193 + +This problem was asked by Affirm. + +Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock. You're also given a number fee that represents a transaction fee for each buy and sell transaction. + +You must buy before you can sell the stock, but you can make as many transactions as you like. + +For example, given `[1, 3, 2, 8, 4, 10]` and `fee = 2`, you should return `9`, since you could buy the stock at `$1`, and sell at `$8`, and then buy it at `$4` and sell it at `$10`. Since we did two transactions, there is a `$4` fee, so we have `7 + 6 = 13` profit minus `$4` of fees. + +[Solution](Solutions/193.py) + +--- + +### Problem 194 + +This problem was asked by Facebook. + +Suppose you are given two lists of n points, one list `p1, p2, ..., pn` on the line `y = 0` and the other list `q1, q2, ..., qn` on the line `y = 1`. Imagine a set of `n` line segments connecting each point `pi` to `qi`. Write an algorithm to determine how many pairs of the line segments intersect. + +[Solution](Solutions/194.py) + +--- + +### Problem 195 + +This problem was asked by Google. + +Let `M` be an `N` by `N` matrix in which every row and every column is sorted. No two elements of `M` are equal. + +Given `i1`, `j1`, `i2`, and `j2`, compute the number of elements of `M` smaller than `M[i1, j1]` and larger than `M[i2, j2]`. + +[Solution](Solutions/195.py) + +--- + +### Problem 196 + +This problem was asked by Apple. + +Given the root of a binary tree, find the most frequent subtree sum. The subtree sum of a node is the sum of all values under a node, including the node itself. + +For example, given the following tree: + +``` + 5 + / \ +2 -5 +``` + +Return `2` as it occurs twice: once as the left leaf, and once as the sum of `2 + 5 - 5.` + +[Solution](Solutions/196.py) + +--- + +### Problem 197 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 198 + +This problem was asked by Google. + +Given a set of distinct positive integers, find the largest subset such that every pair of elements in the subset `(i, j)` satisfies either `i % j = 0` or `j % i = 0`. + +For example, given the set `[3, 5, 10, 20, 21]`, you should return `[5, 10, 20]`. Given `[1, 3, 6, 24]`, return `[1, 3, 6, 24]`. + +[Solution](Solutions/198.py) + +--- + +### Problem 199 + +This problem was asked by Facebook. + +Given a string of parentheses, find the balanced string that can be produced from it using the minimum number of insertions and deletions. If there are multiple solutions, return any of them. + +For example, given `"(()"`, you could return `"(())"`. Given `"))()("`, you could return `"()()()()"`. + +[Solution](Solutions/199.py) + +--- + +### Problem 200 + +This problem was asked by Microsoft. + +Let `X` be a set of `n` intervals on the real line. We say that a set of points `P` "stabs" `X` if every interval in `X` contains at least one point in `P`. Compute the smallest set of points that stabs `X`. + +For example, given the intervals `[(1, 4), (4, 5), (7, 9), (9, 12)]`, you should return `[4, 9]`. + +[Solution](Solutions/200.py) + +--- + +### Problem 201 + +This problem was asked by Google. + +You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, `[[1], [2, 3], [1, 5, 1]]` represents the triangle: + +``` + 1 + 2 3 +1 5 1 +``` + +We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with an entry on the bottom row. For example, `1 -> 3 -> 5`. The weight of the path is the sum of the entries. + +Write a program that returns the weight of the maximum weight path. + +[Solution](Solutions/201.py) + +--- + +### Problem 202 + +This problem was asked by Palantir. + +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. Do not convert the integer into a string. + +[Solution](Solutions/202.py) + +--- + +### Problem 203 + +This problem was asked by Uber. + +Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. Find the minimum element in `O(log N)` time. You may assume the array does not contain duplicates. + +For example, given `[5, 7, 10, 3, 4]`, return `3`. + +[Solution](Solutions/203.py) + +--- + +### Problem 204 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 205 + +This problem was asked by IBM. + +Given an integer, find the next permutation of it in absolute order. For example, given `48975`, the next permutation would be `49578`. + +[Solution](Solutions/205.py) + +--- + +### Problem 206 + +This problem was asked by Twitter. + +A permutation can be specified by an array `P`, where `P[i]` represents the location of the element at `i` in the permutation. For example, `[2, 1, 0]` represents the permutation where elements at the index `0` and `2` are swapped. + +Given an array and a permutation, apply the permutation to the array. For example, given the array `["a", "b", "c"]` and the permutation `[2, 1, 0]`, return `["c", "b", "a"]`. + +[Solution](Solutions/206.py) + +--- + +### Problem 207 + +This problem was asked by Dropbox. + +Given an undirected graph `G`, check whether it is bipartite. Recall that a graph is bipartite if its vertices can be divided into two independent sets, `U` and `V`, such that no edge connects vertices of the same set. + +[Solution](Solutions/207.py) + +--- + +### Problem 208 + +This problem was asked by LinkedIn. + +Given a linked list of numbers and a pivot `k`, partition the linked list so that all nodes less than `k` come before nodes greater than or equal to `k`. + +For example, given the linked list `5 -> 1 -> 8 -> 0 -> 3` and `k = 3`, the solution could be `1 -> 0 -> 5 -> 8 -> 3`. + +[Solution](Solutions/208.py) + +--- + +### Problem 209 + +This problem was asked by YouTube. + +Write a program that computes the length of the longest common subsequence of three given strings. For example, given "epidemiologist", "refrigeration", and "supercalifragilisticexpialodocious", it should return `5`, since the longest common subsequence is "eieio". + +[Solution](Solutions/209.py) + +--- + +### Problem 210 + +This problem was asked by Apple. + +A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer: + +- If `n` is even, the next number in the sequence is `n / 2` +- If `n` is odd, the next number in the sequence is `3n + 1` + It is conjectured that every such sequence eventually reaches the number `1`. Test this conjecture. + +Bonus: What input `n <= 1000000` gives the longest sequence? + +[Solution](Solutions/210.py) + +--- + +### Problem 211 + +This problem was asked by Microsoft. + +Given a string and a pattern, find the starting indices of all occurrences of the pattern in the string. For example, given the string "abracadabra" and the pattern "abr", you should return `[0, 7]`. + +[Solution](Solutions/211.py) + +--- + +### Problem 212 + +This problem was asked by Dropbox. + +Spreadsheets often use this alphabetical encoding for its columns: "A", "B", "C", ..., "AA", "AB", ..., "ZZ", "AAA", "AAB", .... + +Given a column number, return its alphabetical column id. For example, given `1`, return "A". Given `27`, return "AA". + +[Solution](Solutions/212.py) + +--- + +### Problem 213 + +This problem was asked by Snapchat. + +Given a string of digits, generate all possible valid IP address combinations. + +IP addresses must follow the format `A.B.C.D`, where `A`, `B`, `C`, and `D` are numbers between `0` and `255`. Zero-prefixed numbers, such as `01` and `065`, are not allowed, except for `0` itself. + +For example, given "2542540123", you should return `['254.25.40.123', '254.254.0.123']`. + +[Solution](Solutions/213.py) + +--- + +### Problem 214 + +This problem was asked by Stripe. + +Given an integer `n`, return the length of the longest consecutive run of `1`s in its binary representation. + +For example, given `156`, you should return `3`. + +[Solution](Solutions/214.py) + +--- + +### Problem 215 + +This problem was asked by Yelp. + +The horizontal distance of a binary tree node describes how far left or right the node will be when the tree is printed out. + +More rigorously, we can define it as follows: + +- The horizontal distance of the root is `0`. +- The horizontal distance of a left child is `hd(parent) - 1`. +- The horizontal distance of a right child is `hd(parent) + 1`. + +For example, for the following tree, `hd(1) = -2`, and `hd(6) = 0`. + +``` + 5 + / \ + 3 7 + / \ / \ + 1 4 6 9 + / / + 0 8 +``` + +The bottom view of a tree, then, consists of the lowest node at each horizontal distance. If there are two nodes at the same depth and horizontal distance, either is acceptable. + +For this tree, for example, the bottom view could be `[0, 1, 3, 6, 8, 9]`. + +Given the root to a binary tree, return its bottom view. + +[Solution](Solutions/215.py) + +--- + +### Problem 216 + +This problem was asked by Facebook. + +Given a number in Roman numeral format, convert it to decimal. + +The values of Roman numerals are as follows: + +``` +{ + 'M': 1000, + 'D': 500, + 'C': 100, + 'L': 50, + 'X': 10, + 'V': 5, + 'I': 1 +} +``` + +In addition, note that the Roman numeral system uses subtractive notation for numbers such as `IV` and `XL`. + +For the input `XIV`, for instance, you should return `14`. + +[Solution](Solutions/216.py) + +--- + +### Problem 217 + +This problem was asked by Oracle. + +We say a number is sparse if there are no adjacent ones in its binary representation. For example, `21` (`10101`) is sparse, but `22` (`10110`) is not. For a given input `N`, find the smallest sparse number greater than or equal to `N`. + +Do this in faster than `O(N log N)` time. + +[Solution](Solutions/217.py) + +--- + +### Problem 218 + +This problem was asked by Yahoo. + +Write an algorithm that computes the reversal of a directed graph. For example, if a graph consists of `A -> B -> C`, it should become `A <- B <- C`. + +[Solution](Solutions/218.py) + +--- + +### Problem 219 + +This problem was asked by Salesforce. + +Connect 4 is a game where opponents take turns dropping red or black discs into a `7 x 6` vertically suspended grid. The game ends either when one player creates a line of four consecutive discs of their color (horizontally, vertically, or diagonally), or when there are no more spots left in the grid. + +Design and implement Connect 4. + +[Solution](Solutions/219.py) + +--- + +### Problem 220 + +This problem was asked by Square. + +In front of you is a row of N coins, with values `v_1, v_2, ..., v_n`. + +You are asked to play the following game. You and an opponent take turns choosing either the first or last coin from the row, removing it from the row, and receiving the value of the coin. + +Write a program that returns the maximum amount of money you can win with certainty, if you move first, assuming your opponent plays optimally. + +[Solution](Solutions/220.py) + +--- + +### Problem 221 + +This problem was asked by Zillow. + +Let's define a "sevenish" number to be one which is either a power of `7`, or the sum of unique powers of `7`. The first few sevenish numbers are `1, 7, 8, 49`, and so on. Create an algorithm to find the `n`th sevenish number. + +[Solution](Solutions/221.py) + +--- + +### Problem 222 + +This problem was asked by Quora. + +Given an absolute pathname that may have `.` or `..` as part of it, return the shortest standardized path. + +For example, given `/usr/bin/../bin/./scripts/../`, return `/usr/bin/`. + +[Solution](Solutions/222.py) + +--- + +### Problem 223 + +This problem was asked by Palantir. + +Typically, an implementation of in-order traversal of a binary tree has `O(h)` space complexity, where `h` is the height of the tree. Write a program to compute the in-order traversal of a binary tree using `O(1)` space. + +[Solution](Solutions/223.py) + +--- + +### Problem 224 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 225 + +This problem was asked by Bloomberg. + +There are `N` prisoners standing in a circle, waiting to be executed. The executions are carried out starting with the `k`th person, and removing every successive `k`th person going clockwise until there is no one left. + +Given `N` and `k`, write an algorithm to determine where a prisoner should stand in order to be the last survivor. + +For example, if `N = 5` and `k = 2`, the order of executions would be `[2, 4, 1, 5, 3]`, so you should return `3`. + +Bonus: Find an `O(log N)` solution if `k = 2`. + +[Solution](Solutions/225.py) + +--- + +### Problem 226 + +This problem was asked by Airbnb. + +You come across a dictionary of sorted words in a language you've never seen before. Write a program that returns the correct order of letters in this language. + +For example, given `['xww', 'wxyz', 'wxyw', 'ywx', 'ywz']`, you should return `['x', 'z', 'w', 'y']`. + +[Solution](Solutions/226.py) + +--- + +### Problem 227 + +This problem was asked by Facebook. + +Boggle is a game played on a `4 x 4` grid of letters. The goal is to find as many words as possible that can be formed by a sequence of adjacent letters in the grid, using each cell at most once. Given a game board and a dictionary of valid words, implement a Boggle solver. + +[Solution](Solutions/227.py) + +--- + +### Problem 228 + +This problem was asked by Twitter. + +Given a list of numbers, create an algorithm that arranges them in order to form the largest possible integer. For example, given `[10, 7, 76, 415]`, you should return `77641510`. + +[Solution](Solutions/228.py) + +--- + +### Problem 229 + +This problem was asked by Flipkart. + +Snakes and Ladders is a game played on a `10 x 10` board, the goal of which is get from square `1` to square `100`. On each turn players will roll a six-sided die and move forward a number of spaces equal to the result. If they land on a square that represents a snake or ladder, they will be transported ahead or behind, respectively, to a new square. + +Find the smallest number of turns it takes to play snakes and ladders. + +For convenience, here are the squares representing snakes and ladders, and their outcomes: + +``` +snakes = {16: 6, 48: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73, 95: 75, 98: 78} +ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100} +``` + +[Solution](Solutions/229.py) + +--- + +### Problem 230 + +This problem was asked by Goldman Sachs. + +You are given `N` identical eggs and access to a building with `k` floors. Your task is to find the lowest floor that will cause an egg to break, if dropped from that floor. Once an egg breaks, it cannot be dropped again. If an egg breaks when dropped from the `x`th floor, you can assume it will also break when dropped from any floor greater than `x`. + +Write an algorithm that finds the minimum number of trial drops it will take, in the worst case, to identify this floor. + +For example, if `N = 1` and `k = 5`, we will need to try dropping the egg at every floor, beginning with the first, until we reach the fifth floor, so our solution will be `5`. + +[Solution](Solutions/230.py) + +--- + +### Problem 231 + +This problem was asked by IBM. + +Given a string with repeated characters, rearrange the string so that no two adjacent characters are the same. If this is not possible, return None. + +For example, given "aaabbc", you could return "ababac". Given "aaab", return None. + +[Solution](Solutions/231.py) + +--- + +### Problem 232 + +This problem was asked by Google. + +Implement a PrefixMapSum class with the following methods: + +`insert(key: str, value: int)`: Set a given key's value in the map. If the key already exists, overwrite the value. +`sum(prefix: str)`: Return the sum of all values of keys that begin with a given prefix. +For example, you should be able to run the following code: + +``` +mapsum.insert("columnar", 3) +assert mapsum.sum("col") == 3 +``` + +``` +mapsum.insert("column", 2) +assert mapsum.sum("col") == 5 +``` + +[Solution](Solutions/232.py) + +--- + +### Problem 233 + +This problem was asked by Apple. + +Implement the function `fib(n)`, which returns the nth number in the Fibonacci sequence, using only `O(1)` space. + +[Solution](Solutions/233.py) + +--- + +### Problem 234 + +This problem was asked by Microsoft. + +Recall that the minimum spanning tree is the subset of edges of a tree that connect all its vertices with the smallest possible total edge weight. Given an undirected graph with weighted edges, compute the maximum weight spanning tree. + +[Solution](Solutions/234.py) + +--- + +### Problem 235 + +This problem was asked by Facebook. + +Given an array of numbers of length `N`, find both the minimum and maximum using less than `2 * (N - 2)` comparisons. + +[Solution](Solutions/235.py) + +--- + +### Problem 236 + +This problem was asked by Nvidia. + +You are given a list of N points `(x1, y1), (x2, y2), ..., (xN, yN)` representing a polygon. You can assume these points are given in order; that is, you can construct the polygon by connecting point 1 to point 2, point 2 to point 3, and so on, finally looping around to connect point N to point 1. + +Determine if a new point p lies inside this polygon. (If p is on the boundary of the polygon, you should return False). + +[Solution](Solutions/236.md) + +--- + +### Problem 237 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 238 + +This problem was asked by MIT. + +Blackjack is a two player card game whose rules are as follows: + +- The player and then the dealer are each given two cards. +- The player can then "hit", or ask for arbitrarily many additional cards, so long as their total does not exceed 21. +- The dealer must then hit if their total is 16 or lower, otherwise pass. +- Finally, the two compare totals, and the one with the greatest sum not exceeding 21 is the winner. + +For this problem, cards values are counted as follows: each card between 2 and 10 counts as their face value, face cards count as 10, and aces count as 1. + +Given perfect knowledge of the sequence of cards in the deck, implement a blackjack solver that maximizes the player's score (that is, wins minus losses). + +[Solution](Solutions/238.py) + +--- + +### Problem 239 + +This problem was asked by Uber. + +One way to unlock an Android phone is through a pattern of swipes across a 1-9 keypad. + +For a pattern to be valid, it must satisfy the following: + +All of its keys must be distinct. +It must not connect two keys by jumping over a third key, unless that key has already been used. +For example, `4 - 2 - 1 - 7` is a valid pattern, whereas `2 - 1 - 7` is not. + +Find the total number of valid unlock patterns of length N, where `1 <= N <= 9`. + +[Solution](Solutions/239.py) + +--- + +### Problem 240 + +This problem was asked by Spotify. + +There are `N` couples sitting in a row of length `2 * N`. They are currently ordered randomly, but would like to rearrange themselves so that each couple's partners can sit side by side. +What is the minimum number of swaps necessary for this to happen? + +[Solution](Solutions/240.md) + +--- + +### Problem 241 + +This problem was asked by Palantir. + +In academia, the h-index is a metric used to calculate the impact of a researcher's papers. It is calculated as follows: + +A researcher has index `h` if at least `h` of her `N` papers have `h` citations each. If there are multiple `h` satisfying this formula, the maximum is chosen. + +For example, suppose `N = 5`, and the respective citations of each paper are `[4, 3, 0, 1, 5]`. Then the h-index would be `3`, since the researcher has `3` papers with at least `3` citations. + +Given a list of paper citations of a researcher, calculate their h-index. + +[Solution](Solutions/241.py) + +--- + +### Problem 242 + +This problem was asked by Twitter. + +You are given an array of length 24, where each element represents the number of new subscribers during the corresponding hour. Implement a data structure that efficiently supports the following: + +- `update(hour: int, value: int)`: Increment the element at index hour by value. +- `query(start: int, end: int)`: Retrieve the number of subscribers that have signed up between start and end (inclusive). + You can assume that all values get cleared at the end of the day, and that you will not be asked for start and end values that wrap around midnight. + +[Solution](Solutions/242.py) + +--- + +### Problem 243 + +This problem was asked by Etsy. + +Given an array of numbers `N` and an integer `k`, your task is to split `N` into `k` partitions such that the maximum sum of any partition is minimized. Return this sum. + +For example, given `N = [5, 1, 2, 7, 3, 4]` and `k = 3`, you should return `8`, since the optimal partition is `[5, 1, 2], [7], [3, 4]`. + +[Solution](Solutions/243.py) + +--- + +### Problem 244 + +This problem was asked by Square. + +The Sieve of Eratosthenes is an algorithm used to generate all prime numbers smaller than N. The method is to take increasingly larger prime numbers, and mark their multiples as composite. + +For example, to find all primes less than 100, we would first mark `[4, 6, 8, ...]` (multiples of two), then `[6, 9, 12, ...]` (multiples of three), and so on. Once we have done this for all primes less than `N`, the unmarked numbers that remain will be prime. + +Implement this algorithm. + +Bonus: Create a generator that produces primes indefinitely (that is, without taking `N` as an input). + +[Solution](Solutions/244.py) + +--- + +### Problem 245 + +This problem was asked by Yelp. + +You are given an array of integers, where each element represents the maximum number of steps that can be jumped going forward from that element. Write a function to return the minimum number of jumps you must take in order to get from the start to the end of the array. + +For example, given `[6, 2, 4, 0, 5, 1, 1, 4, 2, 9]`, you should return `2`, as the optimal solution involves jumping from `6` to `5`, and then from `5` to `9`. + +[Solution](Solutions/245.py) + +--- + +### Problem 246 + +This problem was asked by Dropbox. + +Given a list of words, determine whether the words can be chained to form a circle. A word `X` can be placed in front of another word `Y` in a circle if the last character of `X` is same as the first character of `Y`. + +For example, the words `['chair', 'height', 'racket', 'touch', 'tunic']` can form the following circle: `chair -> racket -> touch -> height -> tunic -> chair`. + +[Solution](Solutions/246.py) + +--- + +### Problem 247 + +This problem was asked by PayPal. + +Given a binary tree, determine whether or not it is height-balanced. A height-balanced binary tree can be defined as one in which the heights of the two subtrees of any node never differ by more than one. + +[Solution](Solutions/247.py) + +--- + +### Problem 248 + +This problem was asked by Nvidia. + +Find the maximum of two numbers without using any if-else statements, branching, or direct comparisons. + +[Solution](Solutions/248.py) + +--- + +### Problem 249 + +This problem was asked by Salesforce. + +Given an array of integers, find the maximum XOR of any two elements. + +[Solution](Solutions/249.py) + +--- + +### Problem 250 + +This problem was asked by Google. + +A cryptarithmetic puzzle is a mathematical game where the digits of some numbers are represented by letters. Each letter represents a unique digit. + +For example, a puzzle of the form: + +``` + SEND ++ MORE +-------- + MONEY +``` + +may have the solution: + +`{'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2}` + +Given a three-word puzzle like the one above, create an algorithm that finds a solution. + +[Solution](Solutions/250.py) + +--- + +### Problem 251 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 252 + +This problem was asked by Palantir. + +The ancient Egyptians used to express fractions as a sum of several terms where each numerator is one. For example, `4 / 13` can be represented as `1 / (4 + 1 / (18 + (1 / 468)))`. + +Create an algorithm to turn an ordinary fraction `a / b`, where `a < b`, into an Egyptian fraction. + +[Solution](Solutions/252.py) + +--- + +### Problem 253 + +This problem was asked by PayPal. + +Given a string and a number of lines `k`, print the string in zigzag form. In zigzag, characters are printed out diagonally from top left to bottom right until reaching the kth line, then back up to top right, and so on. + +For example, given the sentence `"thisisazigzag"` and `k = 4`, you should print: + +``` +t a g + h s z a + i i i z + s g +``` + +[Solution](Solutions/253.py) + +--- + +### Problem 254 + +This problem was asked by Yahoo. + +Recall that a full binary tree is one in which each node is either a leaf node, or has two children. Given a binary tree, convert it to a full one by removing nodes with only one child. + +For example, given the following tree: + +``` + a + / \ + b c + / \ +d e + \ / \ + f g h +``` + +You should convert it to: + +``` + a + / \ +f e + / \ + g h +``` + +[Solution](Solutions/254.py) + +--- + +### Problem 255 + +This problem was asked by Microsoft. + +The transitive closure of a graph is a measure of which vertices are reachable from other vertices. It can be represented as a matrix `M`, where `M[i][j] == 1` if there is a path between vertices `i` and `j`, and otherwise `0`. + +For example, suppose we are given the following graph in adjacency list form: + +``` +graph = [ + [0, 1, 3], + [1, 2], + [2], + [3] +] +``` + +The transitive closure of this graph would be: + +``` +[1, 1, 1, 1] +[0, 1, 1, 0] +[0, 0, 1, 0] +[0, 0, 0, 1] +``` + +Given a graph, find its transitive closure. + +[Solution](Solutions/255.py) + +--- + +### Problem 256 + +This problem was asked by Fitbit. + +Given a linked list, rearrange the node values such that they appear in alternating `low -> high -> low -> high` ... form. For example, given `1 -> 2 -> 3 -> 4 -> 5`, you should return `1 -> 3 -> 2 -> 5 -> 4`. + +[Solution](Solutions/256.py) + +--- + +### Problem 257 + +This problem was asked by WhatsApp. + +Given an array of integers out of order, determine the bounds of the smallest window that must be sorted in order for the entire array to be sorted. For example, given `[3, 7, 5, 6, 9]`, you should return `(1, 3)`. + +[Solution](Solutions/257.py) + +--- + +### Problem 258 + +This problem was asked by Morgan Stanley. + +In Ancient Greece, it was common to write text with the first line going left to right, the second line going right to left, and continuing to go back and forth. This style was called "boustrophedon". + +Given a binary tree, write an algorithm to print the nodes in boustrophedon order. + +For example, given the following tree: + +``` + 1 + / \ + 2 3 + / \ / \ +4 5 6 7 +``` + +You should return `[1, 3, 2, 4, 5, 6, 7]`. + +[Solution](Solutions/258.py) + +--- + +### Problem 259 + +This problem was asked by Two Sigma. + +Ghost is a two-person word game where players alternate appending letters to a word. The first person who spells out a word, or creates a prefix for which there is no possible continuation, loses. Here is a sample game: + +``` +Player 1: g +Player 2: h +Player 1: o +Player 2: s +Player 1: t [loses] +``` + +Given a dictionary of words, determine the letters the first player should start with, such that with optimal play they cannot lose. + +For example, if the dictionary is `["cat", "calf", "dog", "bear"]`, the only winning start letter would be b. + +[Solution](Solutions/259.py) + +--- + +### Problem 260 + +This problem was asked by Pinterest. + +The sequence `[0, 1, ..., N]` has been jumbled, and the only clue you have for its order is an array representing whether each number is larger or smaller than the last. Given this information, reconstruct an array that is consistent with it. For example, given `[None, +, +, -, +]`, you could return `[1, 2, 3, 0, 4]`. + +[Solution](Solutions/260.py) + +--- + +### Problem 261 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 262 + +This problem was asked by Mozilla. + +A bridge in a connected (undirected) graph is an edge that, if removed, causes the graph to become disconnected. Find all the bridges in a graph. + +[Solution](Solutions/262.md) + +--- + +### Problem 263 + +This problem was asked by Nest. + +Create a basic sentence checker that takes in a stream of characters and determines whether they form valid sentences. If a sentence is valid, the program should print it out. + +We can consider a sentence valid if it conforms to the following rules: + +- The sentence must start with a capital letter, followed by a lowercase letter or a space. +- All other characters must be lowercase letters, separators `(,,;,:)` or terminal marks `(.,?,!,‽)`. +- There must be a single space between each word. +- The sentence must end with a terminal mark immediately following a word. + +[Solution](Solutions/263.py) + +--- + +### Problem 264 + +This problem was asked by LinkedIn. + +Given a set of characters `C` and an integer `k`, a De Bruijn sequence is a cyclic sequence in which every possible `k`-length string of characters in `C` occurs exactly once. + +For example, suppose `C = {0, 1}` and `k = 3`. Then our sequence should contain the substrings `{'000', '001', '010', '011', '100', '101', '110', '111'}`, and one possible solution would be `00010111`. + +Create an algorithm that finds a De Bruijn sequence. + +[Solution](Solutions/264.py) + +--- + +### Problem 265 + +This problem was asked by Atlassian. + +MegaCorp wants to give bonuses to its employees based on how many lines of codes they have written. They would like to give the smallest positive amount to each worker consistent with the constraint that if a developer has written more lines of code than their neighbor, they should receive more money. + +Given an array representing a line of seats of employees at MegaCorp, determine how much each one should get paid. + +For example, given `[10, 40, 200, 1000, 60, 30]`, you should return `[1, 2, 3, 4, 2, 1]`. + +[Solution](Solutions/265.py) + +--- + +### Problem 266 + +This problem was asked by Pivotal. + +A step word is formed by taking a given word, adding a letter, and anagramming the result. For example, starting with the word "APPLE", you can add an "A" and anagram to get "APPEAL". + +Given a dictionary of words and an input word, create a function that returns all valid step words. + +[Solution](Solutions/266.py) + +--- + +### Problem 267 + +This problem was asked by Oracle. + +You are presented with an 8 by 8 matrix representing the positions of pieces on a chess board. The only pieces on the board are the black king and various white pieces. Given this matrix, determine whether the king is in check. + +For details on how each piece moves, see [here](https://en.wikipedia.org/wiki/Chess_piece#Moves_of_the_pieces). + +For example, given the following matrix: + +``` +...K.... +........ +.B...... +......P. +.......R +..N..... +........ +.....Q.. +``` + +You should return `True`, since the bishop is attacking the king diagonally. + +[Solution](Solutions/267.py) + +--- + +### Problem 268 + +This problem was asked by Indeed. + +Given a 32-bit positive integer `N`, determine whether it is a power of four in faster than `O(log N)` time. + +[Solution](Solutions/268.py) + +--- + +### Problem 269 + +This problem was asked by Microsoft. + +You are given an string representing the initial conditions of some dominoes. Each element can take one of three values: + +- `L`, meaning the domino has just been pushed to the left, +- `R`, meaning the domino has just been pushed to the right, or +- `.`, meaning the domino is standing still. + +Determine the orientation of each tile when the dominoes stop falling. Note that if a domino receives a force from the left and right side simultaneously, it will remain upright. + +For example, given the string `.L.R....L`, you should return `LL.RRRLLL`. + +Given the string `..R...L.L`, you should return `..RR.LLLL`. + +[Solution](Solutions/269.py) + +--- + +### Problem 270 + +This problem was asked by Twitter. + +A network consists of nodes labeled `0` to `N`. You are given a list of edges `(a, b, t)`, describing the time `t` it takes for a message to be sent from node `a` to node `b`. Whenever a node receives a message, it immediately passes the message on to a neighboring node, if possible. + +Assuming all nodes are connected, determine how long it will take for every node to receive a message that begins at node `0`. + +For example, given `N = 5`, and the following edges: + +``` +edges = [ + (0, 1, 5), + (0, 2, 3), + (0, 5, 4), + (1, 3, 8), + (2, 3, 1), + (3, 5, 10), + (3, 4, 5) +] +``` + +You should return `9`, because propagating the message from `0 -> 2 -> 3 -> 4` will take that much time. + +[Solution](Solutions/270.py) + +--- + +### Problem 271 + +This problem was asked by Netflix. + +Given a sorted list of integers of length `N`, determine if an element `x` is in the list without performing any multiplication, division, or bit-shift operations. + +Do this in `O(log N)` time. + +[Solution](Solutions/271.py) + +--- + +### Problem 272 + +This problem was asked by Spotify. + +Write a function, `throw_dice(N, faces, total)`, that determines how many ways it is possible to throw `N` dice with some number of faces each to get a specific total. + +For example, `throw_dice(3, 6, 7)` should equal `15`. + +[Solution](Solutions/272.py) + +--- + +### Problem 273 + +This problem was asked by Apple. + +A fixed point in an array is an element whose value is equal to its index. Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return `False`. + +For example, given `[-6, 0, 2, 40]`, you should return `2`. Given `[1, 5, 7, 8]`, you should return `False`. + +[Solution](Solutions/273.py) + +--- + +### Problem 274 + +This problem was asked by Facebook. + +Given a string consisting of parentheses, single digits, and positive and negative signs, convert the string into a mathematical expression to obtain the answer. + +Don't use eval or a similar built-in parser. + +For example, given `'-1 + (2 + 3)'`, you should return `4`. + +[Solution](Solutions/274.py) + +--- + +### Problem 275 + +This problem was asked by Epic. + +The "look and say" sequence is defined as follows: beginning with the term `1`, each subsequent term visually describes the digits appearing in the previous term. The first few terms are as follows: + +``` +1 +11 +21 +1211 +111221 +``` + +As an example, the fourth term is `1211`, since the third term consists of one `2` and one `1`. + +Given an integer `N`, print the `Nth` term of this sequence. + +[Solution](Solutions/275.py) + +--- + +### Problem 276 + +This problem was asked by Dropbox. + +Implement an efficient string matching algorithm. + +That is, given a string of length `N` and a pattern of length `k`, write a program that searches for the pattern in the string with less than `O(N * k)` worst-case time complexity. + +If the pattern is found, return the start index of its location. If not, return `False`. + +[Solution](Solutions/276.py) + +--- + +### Problem 277 + +This problem was asked by Google. + +UTF-8 is a character encoding that maps each symbol to one, two, three, or four bytes. + +For example, the Euro sign, `€`, corresponds to the three bytes `11100010 10000010 10101100`. The rules for mapping characters are as follows: + +- For a single-byte character, the first bit must be zero. +- For an `n`-byte character, the first byte starts with `n` ones and a zero. The other `n - 1` bytes all start with `10`. + Visually, this can be represented as follows. + +``` + Bytes | Byte format +----------------------------------------------- + 1 | 0xxxxxxx + 2 | 110xxxxx 10xxxxxx + 3 | 1110xxxx 10xxxxxx 10xxxxxx + 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx +``` + +Write a program that takes in an array of integers representing byte values, and returns whether it is a valid UTF-8 encoding. + +[Solution](Solutions/277.py) + +--- + +### Problem 278 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 279 + +This problem was asked by Twitter. + +A classroom consists of N students, whose friendships can be represented in an adjacency list. For example, the following descibes a situation where `0` is friends with `1` and `2`, `3` is friends with `6`, and so on. + +``` +{ + 0: [1, 2], + 1: [0, 5], + 2: [0], + 3: [6], + 4: [], + 5: [1], + 6: [3] +} +``` + +Each student can be placed in a friend group, which can be defined as the transitive closure of that student's friendship relations. In other words, this is the smallest set such that no student in the group has any friends outside this group. For the example above, the friend groups would be `{0, 1, 2, 5}, {3, 6}, {4}`. + +Given a friendship list such as the one above, determine the number of friend groups in the class. + +[Solution](Solutions/279.py) + +--- + +### Problem 280 + +This problem was asked by Pandora. + +Given an undirected graph, determine if it contains a cycle. + +[Solution](Solutions/280.py) + +--- + +### Problem 281 + +This problem was asked by LinkedIn. + +A wall consists of several rows of bricks of various integer lengths and uniform height. Your goal is to find a vertical line going from the top to the bottom of the wall that cuts through the fewest number of bricks. If the line goes through the edge between two bricks, this does not count as a cut. + +For example, suppose the input is as follows, where values in each row represent the lengths of bricks in that row: + +``` +[[3, 5, 1, 1], + [2, 3, 3, 2], + [5, 5], + [4, 4, 2], + [1, 3, 3, 3], + [1, 1, 6, 1, 1]] +``` + +The best we can we do here is to draw a line after the eighth brick, which will only require cutting through the bricks in the third and fifth row. + +Given an input consisting of brick lengths for each row such as the one above, return the fewest number of bricks that must be cut to create a vertical line. + +[Solution](Solutions/281.py) + +--- + +### Problem 282 + +This problem was asked by Netflix. + +Given an array of integers, determine whether it contains a Pythagorean triplet. Recall that a Pythogorean triplet `(a, b, c)` is defined by the equation `a^2 + b^2 = c^2`. + +[Solution](Solutions/282.py) + +--- + +### Problem 283 + +This problem was asked by Google. + +A regular number in mathematics is defined as one which evenly divides some power of `60`. Equivalently, we can say that a regular number is one whose only prime divisors are `2`, `3`, and `5`. + +These numbers have had many applications, from helping ancient Babylonians keep time to tuning instruments according to the diatonic scale. + +Given an integer `N`, write a program that returns, in order, the first `N` regular numbers. + +[Solution](Solutions/283.py) + +--- + +### Problem 284 + +This problem was asked by Yext. + +Two nodes in a binary tree can be called cousins if they are on the same level of the tree but have different parents. For example, in the following diagram `4` and `6` are cousins. + +``` + 1 + / \ + 2 3 + / \ \ +4 5 6 +``` + +Given a binary tree and a particular node, find all cousins of that node. + +[Solution](Solutions/284.py) + +--- + +### Problem 285 + +This problem was asked by Mailchimp. + +You are given an array representing the heights of neighboring buildings on a city street, from east to west. The city assessor would like you to write an algorithm that returns how many of these buildings have a view of the setting sun, in order to properly value the street. + +For example, given the array `[3, 7, 8, 3, 6, 1]`, you should return `3`, since the top floors of the buildings with heights `8`, `6`, and `1` all have an unobstructed view to the west. + +Can you do this using just one forward pass through the array? + +[Solution](Solutions/285.py) + +--- + +### Problem 286 + +This problem was asked by VMware. + +The skyline of a city is composed of several buildings of various widths and heights, possibly overlapping one another when viewed from a distance. We can represent the buildings using an array of `(left, right, height)` tuples, which tell us where on an imaginary `x`-axis a building begins and ends, and how tall it is. The skyline itself can be described by a list of `(x, height)` tuples, giving the locations at which the height visible to a distant observer changes, and each new height. + +Given an array of buildings as described above, create a function that returns the skyline. + +For example, suppose the input consists of the buildings `[(0, 15, 3), (4, 11, 5), (19, 23, 4)]`. In aggregate, these buildings would create a skyline that looks like the one below. + +``` + ______ + | | ___ + ___| |___ | | +| | B | | | C | +| A | | A | | | +| | | | | | +------------------------ +``` + +As a result, your function should return `[(0, 3), (4, 5), (11, 3), (15, 0), (19, 4), (23, 0)]`. + +[Solution](Solutions/286.py) + +--- + +### Problem 287 + +This problem was asked by Quora. + +You are given a list of (website, user) pairs that represent users visiting websites. Come up with a program that identifies the top `k` pairs of websites with the greatest similarity. + +For example, suppose `k = 1`, and the list of tuples is: + +``` +[('a', 1), ('a', 3), ('a', 5), + ('b', 2), ('b', 6), + ('c', 1), ('c', 2), ('c', 3), ('c', 4), ('c', 5), + ('d', 4), ('d', 5), ('d', 6), ('d', 7), + ('e', 1), ('e', 3), ('e', 5), ('e', 6)] +``` + +Then a reasonable similarity metric would most likely conclude that `a` and `e` are the most similar, so your program should return `[('a', 'e')]`. + +[Solution](Solutions/287.py) + +--- + +### Problem 288 + +This problem was asked by Salesforce. + +The number `6174` is known as Kaprekar's contant, after the mathematician who discovered an associated property: for all four-digit numbers with at least two distinct digits, repeatedly applying a simple procedure eventually results in this value. The procedure is as follows: + +For a given input `x`, create two new numbers that consist of the digits in `x` in ascending and descending order. +Subtract the smaller number from the larger number. +For example, this algorithm terminates in three steps when starting from `1234`: + +``` +4321 - 1234 = 3087 +8730 - 0378 = 8352 +8532 - 2358 = 6174 +``` + +Write a function that returns how many steps this will take for a given input `N`. + +[Solution](Solutions/288.py) + +--- + +### Problem 289 + +This problem was asked by Google. + +The game of Nim is played as follows. Starting with three heaps, each containing a variable number of items, two players take turns removing one or more items from a single pile. The player who eventually is forced to take the last stone loses. For example, if the initial heap sizes are 3, 4, and 5, a game could be played as shown below: + +| A | B | C | +| --- | --- | --- | +| 3 | 4 | 5 | +| 3 | 1 | 5 | +| 3 | 1 | 3 | +| 0 | 1 | 3 | +| 0 | 1 | 0 | +| 0 | 0 | 0 | + +In other words, to start, the first player takes three items from pile `B`. The second player responds by removing two stones from pile `C`. The game continues in this way until player one takes last stone and loses. + +Given a list of non-zero starting values `[a, b, c]`, and assuming optimal play, determine whether the first player has a forced win. + +[Solution](Solutions/289.py) + +--- + +### Problem 290 + +This problem was asked by Facebook. + +On a mysterious island there are creatures known as Quxes which come in three colors: red, green, and blue. One power of the Qux is that if two of them are standing next to each other, they can transform into a single creature of the third color. + +Given N Quxes standing in a line, determine the smallest number of them remaining after any possible sequence of such transformations. + +For example, given the input `['R', 'G', 'B', 'G', 'B']`, it is possible to end up with a single Qux through the following steps: + +``` + Arrangement | Change +---------------------------------------- +['R', 'G', 'B', 'G', 'B'] | (R, G) -> B +['B', 'B', 'G', 'B'] | (B, G) -> R +['B', 'R', 'B'] | (R, B) -> G +['B', 'G'] | (B, G) -> R +['R'] | +``` + +[Solution](Solutions/290.py) + +--- + +### Problem 291 + +This problem was asked by Glassdoor. + +An imminent hurricane threatens the coastal town of Codeville. If at most two people can fit in a rescue boat, and the maximum weight limit for a given boat is `k`, determine how many boats will be needed to save everyone. + +For example, given a population with weights `[100, 200, 150, 80]` and a boat limit of `200`, the smallest number of boats required will be three. + +[Solution](Solutions/291.py) + +--- + +### Problem 292 + +This problem was asked by Twitter. + +A teacher must divide a class of students into two teams to play dodgeball. Unfortunately, not all the kids get along, and several refuse to be put on the same team as that of their enemies. + +Given an adjacency list of students and their enemies, write an algorithm that finds a satisfactory pair of teams, or returns `False` if none exists. + +For example, given the following enemy graph you should return the teams `{0, 1, 4, 5}` and `{2, 3}`. + +``` +students = { + 0: [3], + 1: [2], + 2: [1, 4], + 3: [0, 4, 5], + 4: [2, 3], + 5: [3] +} +``` + +On the other hand, given the input below, you should return `False`. + +``` +students = { + 0: [3], + 1: [2], + 2: [1, 3, 4], + 3: [0, 2, 4, 5], + 4: [2, 3], + 5: [3] +} +``` + +[Solution](Solutions/292.py) + +--- + +### Problem 293 + +This problem was asked by Uber. + +You have N stones in a row, and would like to create from them a pyramid. This pyramid should be constructed such that the height of each stone increases by one until reaching the tallest stone, after which the heights decrease by one. In addition, the start and end stones of the pyramid should each be one stone high. + +You can change the height of any stone by paying a cost of `1` unit to lower its height by `1`, as many times as necessary. Given this information, determine the lowest cost method to produce this pyramid. + +For example, given the stones `[1, 1, 3, 3, 2, 1]`, the optimal solution is to pay 2 to create `[0, 1, 2, 3, 2, 1]`. + +[Solution](Solutions/293.py) + +--- + +### Problem 294 + +This problem was asked by Square. + +A competitive runner would like to create a route that starts and ends at his house, with the condition that the route goes entirely uphill at first, and then entirely downhill. + +Given a dictionary of places of the form `{location: elevation}`, and a dictionary mapping paths between some of these locations to their corresponding distances, find the length of the shortest route satisfying the condition above. Assume the runner's home is location `0`. + +For example, suppose you are given the following input: + +``` +elevations = {0: 5, 1: 25, 2: 15, 3: 20, 4: 10} +paths = { + (0, 1): 10, + (0, 2): 8, + (0, 3): 15, + (1, 3): 12, + (2, 4): 10, + (3, 4): 5, + (3, 0): 17, + (4, 0): 10 +} +``` + +In this case, the shortest valid path would be `0 -> 2 -> 4 -> 0`, with a distance of `28`. + +[Solution](Solutions/294.py) + +--- + +### Problem 295 + +This problem was asked by Stitch Fix. + +Pascal's triangle is a triangular array of integers constructed with the following formula: + +The first row consists of the number 1. +For each subsequent row, each element is the sum of the numbers directly above it, on either side. +For example, here are the first few rows: + +``` + 1 + 1 1 + 1 2 1 + 1 3 3 1 +1 4 6 4 1 +``` + +Given an input `k`, return the `k`th row of Pascal's triangle. + +Bonus: Can you do this using only `O(k)` space? + +[Solution](Solutions/295.py) + +--- + +### Problem 296 + +This problem was asked by Etsy. + +Given a sorted array, convert it into a height-balanced binary search tree. + +[Solution](Solutions/296.py) + +--- + +### Problem 297 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 298 + +This problem was asked by Google. + +A girl is walking along an apple orchard with a bag in each hand. She likes to pick apples from each tree as she goes along, but is meticulous about not putting different kinds of apples in the same bag. + +Given an input describing the types of apples she will pass on her path, in order, determine the length of the longest portion of her path that consists of just two types of apple trees. + +For example, given the input `[2, 1, 2, 3, 3, 1, 3, 5]`, the longest portion will involve types `1` and `3`, with a length of four. + +[Solution](Solutions/298.py) + +--- + +### Problem 299 + +This problem was asked by Samsung. + +A group of houses is connected to the main water plant by means of a set of pipes. A house can either be connected by a set of pipes extending directly to the plant, or indirectly by a pipe to a nearby house which is otherwise connected. + +For example, here is a possible configuration, where A, B, and C are houses, and arrows represent pipes: +`A <--> B <--> C <--> plant` + +Each pipe has an associated cost, which the utility company would like to minimize. Given an undirected graph of pipe connections, return the lowest cost configuration of pipes such that each house has access to water. + +In the following setup, for example, we can remove all but the pipes from plant to A, plant to B, and B to C, for a total cost of 16. + +```python +pipes = { + 'plant': {'A': 1, 'B': 5, 'C': 20}, + 'A': {'C': 15}, + 'B': {'C': 10}, + 'C': {} +} +``` + +[Solution](Solutions/299.py) + +--- + +### Problem 300 + +This problem was asked by Uber. + +On election day, a voting machine writes data in the form `(voter_id, candidate_id)` to a text file. Write a program that reads this file as a stream and returns the top 3 candidates at any given time. If you find a voter voting more than once, report this as fraud. + +[Solution](Solutions/300/300.py) + +--- + +### Problem 301 + +This problem was asked by Triplebyte. + +Implement a data structure which carries out the following operations without resizing the underlying array: + +- `add(value)`: Add a value to the set of values. +- `check(value)`: Check whether a value is in the set. + +The check method may return occasional false positives (in other words, incorrectly identifying an element as part of the set), but should always correctly identify a true element. + +[Solution](Solutions/301.py) + +--- + +### Problem 302 + +This problem was asked by Uber. + +You are given a 2-d matrix where each cell consists of either `/`, `\`, or an empty space. Write an algorithm that determines into how many regions the slashes divide the space. + +For example, suppose the input for a three-by-six grid is the following: + +``` +\ / + \ / + \/ +``` + +Considering the edges of the matrix as boundaries, this divides the grid into three triangles, so you should return `3`. + +[Solution](Solutions/302.py) + +--- + +### Problem 303 + +This problem was asked by Microsoft. + +Given a clock time in `hh:mm` format, determine, to the nearest degree, the angle between the hour and the minute hands. + +Bonus: When, during the course of a day, will the angle be zero? + +[Solution](Solutions/303.py) + +--- + +### Problem 304 + +This problem was asked by Two Sigma. + +A knight is placed on a given square on an `8 x 8` chessboard. It is then moved randomly several times, where each move is a standard knight move. If the knight jumps off the board at any point, however, it is not allowed to jump back on. + +After `k` moves, what is the probability that the knight remains on the board? + +[Solution](Solutions/304.py) + +--- + +### Problem 305 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 306 + +This problem was asked by Palantir. + +You are given a list of N numbers, in which each number is located at most k places away from its sorted position. For example, if `k = 1`, a given element at index `4` might end up at indices `3`, `4`, or `5`. + +Come up with an algorithm that sorts this list in `O(N log k)` time. + +[Solution](Solutions/306.py) + +--- + +### Problem 307 + +This problem was asked by Oracle. + +Given a binary search tree, find the floor and ceiling of a given integer. The floor is the highest element in the tree less than or equal to an integer, while the ceiling is the lowest element in the tree greater than or equal to an integer. + +If either value does not exist, return None. + +[Solution](Solutions/307.py) + +--- + +### Problem 308 + +This problem was asked by Quantcast. + +You are presented with an array representing a Boolean expression. The elements are of two kinds: + +- `T` and `F`, representing the values `True` and `False`. +- `&`, `|`, and `^`, representing the bitwise operators for `AND`, `OR`, and `XOR`. + +Determine the number of ways to group the array elements using parentheses so that the entire expression evaluates to `True`. + +For example, suppose the input is `['F', '|', 'T', '&', 'T']`. In this case, there are two acceptable groupings: `(F | T) & T` and `F | (T & T)`. + +[Solution](Solutions/308.py) + +--- + +### Problem 309 + +This problem was asked by Walmart Labs. + +There are `M` people sitting in a row of `N` seats, where `M < N`. Your task is to redistribute people such that there are no gaps between any of them, while keeping overall movement to a minimum. + +For example, suppose you are faced with an input of `[0, 1, 1, 0, 1, 0, 0, 0, 1]`, where `0` represents an empty seat and `1` represents a person. In this case, one solution would be to place the person on the right in the fourth seat. We can consider the cost of a solution to be the sum of the absolute distance each person must move, so that the cost here would be `5`. + +Given an input such as the one above, return the lowest possible cost of moving people to remove all gaps. + +[Solution](Solutions/309.py) + +--- + +### Problem 310 + +This problem was asked by Pivotal. + +Write an algorithm that finds the total number of set bits in all integers between `1` and `N`. + +[Solution](Solutions/310.py) + +--- + +### Problem 311 + +This problem was asked by Sumo Logic. + +Given an unsorted array, in which all elements are distinct, find a "peak" element in `O(log N)` time. + +An element is considered a peak if it is greater than both its left and right neighbors. It is guaranteed that the first and last elements are lower than all others. + +[Solution](Solutions/311.py) + +--- + +### Problem 312 + +This problem was asked by Wayfair. + +You are given a `2 x N` board, and instructed to completely cover the board with the following shapes: + +- Dominoes, or `2 x 1` rectangles. +- Trominoes, or L-shapes. + +For example, if `N = 4`, here is one possible configuration, where A is a domino, and B and C are trominoes. + +``` +A B B C +A B C C +``` + +Given an integer N, determine in how many ways this task is possible. + +[Solution](Solutions/312.py) + +--- + +### Problem 313 + +This problem was asked by Citrix. + +You are given a circular lock with three wheels, each of which display the numbers `0` through `9` in order. Each of these wheels rotate clockwise and counterclockwise. + +In addition, the lock has a certain number of "dead ends", meaning that if you turn the wheels to one of these combinations, the lock becomes stuck in that state and cannot be opened. + +Let us consider a "move" to be a rotation of a single wheel by one digit, in either direction. Given a lock initially set to `000`, a target combination, and a list of dead ends, write a function that returns the minimum number of moves required to reach the target state, or `None` if this is impossible. + +[Solution](Solutions/313.py) + +--- + +### Problem 314 + +This problem was asked by Spotify. + +You are the technical director of WSPT radio, serving listeners nationwide. For simplicity's sake we can consider each listener to live along a horizontal line stretching from `0` (west) to `1000` (east). + +Given a list of `N` listeners, and a list of `M` radio towers, each placed at various locations along this line, determine what the minimum broadcast range would have to be in order for each listener's home to be covered. + +For example, suppose `listeners = [1, 5, 11, 20]`, and `towers = [4, 8, 15]`. In this case the minimum range would be `5`, since that would be required for the tower at position `15` to reach the listener at position `20`. + +[Solution](Solutions/314.py) + +--- + +### Problem 315 + +This problem was asked by Google. + +In linear algebra, a Toeplitz matrix is one in which the elements on any given diagonal from top left to bottom right are identical. + +Here is an example: + +``` +1 2 3 4 8 +5 1 2 3 4 +4 5 1 2 3 +7 4 5 1 2 +``` + +Write a program to determine whether a given input is a Toeplitz matrix. + +[Solution](Solutions/315.py) + +--- + +### Problem 316 + +This problem was asked by Snapchat. + +You are given an array of length `N`, where each element `i` represents the number of ways we can produce `i` units of change. For example, `[1, 0, 1, 1, 2]` would indicate that there is only one way to make `0`, `2`, or `3` units, and two ways of making `4` units. + +Given such an array, determine the denominations that must be in use. In the case above, for example, there must be coins with value `2`, `3`, and `4`. + +[Solution](Solutions/316.py) + +--- + +### Problem 317 + +This problem was asked by Yahoo. + +Write a function that returns the bitwise `AND` of all integers between `M` and `N`, inclusive. + +[Solution](Solutions/317.py) + +--- + +### Problem 318 + +This problem was asked by Apple. + +You are going on a road trip, and would like to create a suitable music playlist. The trip will require `N` songs, though you only have `M` songs downloaded, where `M < N`. A valid playlist should select each song at least once, and guarantee a buffer of `B` songs between repeats. + +Given `N`, `M`, and `B`, determine the number of valid playlists. + +[Solution](Solutions/318.py) + +--- + +### Problem 319 + +This problem was asked by Airbnb. + +An 8-puzzle is a game played on a `3 x 3` board of tiles, with the ninth tile missing. The remaining tiles are labeled `1` through `8` but shuffled randomly. Tiles may slide horizontally or vertically into an empty space, but may not be removed from the board. + +Design a class to represent the board, and find a series of steps to bring the board to the state `[[1, 2, 3], [4, 5, 6], [7, 8, None]]`. + +[Solution](Solutions/319.py) + +--- + +### Problem 320 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 321 + +This problem was asked by PagerDuty. + +Given a positive integer `N`, find the smallest number of steps it will take to reach `1`. + +There are two kinds of permitted steps: + +- You may decrement `N` to `N - 1`. +- If `a * b = N`, you may decrement `N` to the larger of `a` and `b`. + +For example, given `100`, you can reach `1` in five steps with the following route: `100 -> 10 -> 9 -> 3 -> 2 -> 1`. + +[Solution](Solutions/321.py) + +--- + +### Problem 322 + +This problem was asked by Flipkart. + +Starting from `0` on a number line, you would like to make a series of jumps that lead to the integer `N`. + +On the `i`th jump, you may move exactly `i` places to the left or right. + +Find a path with the fewest number of jumps required to get from `0` to `N`. + +[Solution](Solutions/322.py) + +--- + +### Problem 323 + +This problem was asked by Dropbox. + +Create an algorithm to efficiently compute the approximate median of a list of numbers. + +More precisely, given an unordered list of `N` numbers, find an element whose rank is between `N / 4` and `3 * N / 4`, with a high level of certainty, in less than `O(N)` time. + +[Solution](Solutions/323.py) + +--- + +### Problem 324 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 325 + +This problem was asked by Jane Street. + +The United States uses the imperial system of weights and measures, which means that there are many different, seemingly arbitrary units to measure distance. There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on. + +Create a data structure that can efficiently convert a certain quantity of one unit to the correct amount of any other unit. You should also allow for additional units to be added to the system. + +[Solution](Solutions/325.py) + +--- + +### Problem 326 + +This problem was asked by Netflix. + +A Cartesian tree with sequence `S` is a binary tree defined by the following two properties: + +It is heap-ordered, so that each parent value is strictly less than that of its children. +An in-order traversal of the tree produces nodes with values that correspond exactly to `S`. +For example, given the sequence `[3, 2, 6, 1, 9]`, the resulting Cartesian tree would be: + +``` + 1 + / \ + 2 9 + / \ +3 6 +``` + +Given a sequence S, construct the corresponding Cartesian tree. + +[Solution](Solutions/326.py) + +--- + +### Problem 327 + +This problem was asked by Salesforce. + +Write a program to merge two binary trees. Each node in the new tree should hold a value equal to the sum of the values of the corresponding nodes of the input trees. + +If only one input tree has a node in a given position, the corresponding node in the new tree should match that input node. + +[Solution](Solutions/327.py) + +--- + +### Problem 328 + +This problem was asked by Facebook. + +In chess, the Elo rating system is used to calculate player strengths based on game results. + +A simplified description of the Elo system is as follows. Every player begins at the same score. For each subsequent game, the loser transfers some points to the winner, where the amount of points transferred depends on how unlikely the win is. For example, a 1200-ranked player should gain much more points for beating a 2000-ranked player than for beating a 1300-ranked player. + +Implement this system. + +[Solution](Solutions/328.py) + +--- + +### Problem 329 + +**THE PROBLEM & THE SOLUTION WAS TAKEN DOWN DUE TO AMAZON'S COPYRIGHTS INFRINGEMENT** + +--- + +### Problem 330 + +This problem was asked by Dropbox. + +A Boolean formula can be said to be satisfiable if there is a way to assign truth values to each variable such that the entire formula evaluates to true. + +For example, suppose we have the following formula, where the symbol `¬` is used to denote negation: + +``` +(¬c OR b) AND (b OR c) AND (¬b OR c) AND (¬c OR ¬a) +``` + +One way to satisfy this formula would be to let `a = False`, `b = True`, and `c = True`. + +This type of formula, with AND statements joining tuples containing exactly one OR, is known as 2-CNF. + +Given a 2-CNF formula, find a way to assign truth values to satisfy it, or return `False` if this is impossible. + +[Solution](Solutions/330.py) + +--- + +### Problem 331 + +This problem was asked by LinkedIn. + +You are given a string consisting of the letters `x` and `y`, such as `xyxxxyxyy`. In addition, you have an operation called flip, which changes a single `x` to `y` or vice versa. + +Determine how many times you would need to apply this operation to ensure that all `x`'s come before all `y`'s. In the preceding example, it suffices to flip the second and sixth characters, so you should return `2`. + +[Solution](Solutions/331.py) + +--- + +### Problem 332 + +This problem was asked by Jane Street. + +Given integers `M` and `N`, write a program that counts how many positive integer pairs `(a, b)` satisfy the following conditions: + +``` +a + b = M +a XOR b = N +``` + +[Solution](Solutions/332.py) + +--- + +### Problem 333 + +This problem was asked by Pinterest. + +At a party, there is a single person who everyone knows, but who does not know anyone in return (the "celebrity"). To help figure out who this is, you have access to an `O(1)` method called `knows(a, b)`, which returns `True` if person `a` knows person `b`, else `False`. + +Given a list of `N` people and the above operation, find a way to identify the celebrity in `O(N)` time. + +[Solution](Solutions/333.py) + +--- + +### Problem 334 + +This problem was asked by Twitter. + +The `24` game is played as follows. You are given a list of four integers, each between `1` and `9`, in a fixed order. By placing the operators `+`, `-`, `*`, and `/` between the numbers, and grouping them with parentheses, determine whether it is possible to reach the value `24`. + +For example, given the input `[5, 2, 7, 8]`, you should return True, since `(5 * 2 - 7) * 8 = 24`. + +Write a function that plays the `24` game. + +[Solution](Solutions/334.py) + +--- + +### Problem 335 + +This problem was asked by Google. + +PageRank is an algorithm used by Google to rank the importance of different websites. While there have been changes over the years, the central idea is to assign each site a score based on the importance of other pages that link to that page. + +More mathematically, suppose there are `N` sites, and each site `i` has a certain count `Ci` of outgoing links. Then the score for a particular site `Sj` is defined as : + +``` +score(Sj) = (1 - d) / N + d * (score(Sx) / Cx+ score(Sy) / Cy+ ... + score(Sz) / Cz)) +``` + +Here, `Sx, Sy, ..., Sz` denote the scores of all the other sites that have outgoing links to `Sj`, and `d` is a damping factor, usually set to around `0.85`, used to model the probability that a user will stop searching. + +Given a directed graph of links between various websites, write a program that calculates each site's page rank. + +[Solution](Solutions/335.py) + +--- + +### Problem 336 + +This problem was asked by Microsoft. + +Write a program to determine how many distinct ways there are to create a max heap from a list of `N` given integers. + +For example, if `N = 3`, and our integers are `[1, 2, 3]`, there are two ways, shown below. + +``` + 3 3 + / \ / \ +1 2 2 1 +``` + +[Solution](Solutions/336.py) + +--- + +### Problem 337 + +This problem was asked by Apple. + +Given a linked list, uniformly shuffle the nodes. What if we want to prioritize space over time? + +[Solution](Solutions/337.py) + +--- + +### Problem 338 + +This problem was asked by Facebook. + +Given an integer `n`, find the next biggest integer with the same number of `1`-bits on. For example, given the number `6` (`0110` in binary), return `9` (`1001`). + +[Solution](Solutions/338.py) + +--- + +### Problem 339 + +This problem was asked by Microsoft. + +Given an array of numbers and a number `k`, determine if there are three entries in the array which add up to the specified number `k`. For example, given `[20, 303, 3, 4, 25]` and `k = 49`, return true as `20 + 4 + 25 = 49`. + +[Solution](Solutions/339.py) + +--- + +### Problem 340 + +This problem was asked by Google. + +Given a set of points `(x, y)` on a 2D cartesian plane, find the two closest points. For example, given the points `[(1, 1), (-1, -1), (3, 4), (6, 1), (-1, -6), (-4, -3)]`, return `[(-1, -1), (1, 1)]`. + +[Solution](Solutions/340.py) + +--- + +### Problem 341 + +This problem was asked by Google. + +You are given an N by N matrix of random letters and a dictionary of words. Find the maximum number of words that can be packed on the board from the given dictionary. + +A word is considered to be able to be packed on the board if: + +- It can be found in the dictionary +- It can be constructed from untaken letters by other words found so far on the board +- The letters are adjacent to each other (vertically and horizontally, not diagonally). +- Each tile can be visited only once by any word. + +For example, given the following dictionary: + +``` +{ 'eat', 'rain', 'in', 'rat' } +``` + +and matrix: + +``` +[['e', 'a', 'n'], + ['t', 't', 'i'], + ['a', 'r', 'a']] +``` + +Your function should return 3, since we can make the words 'eat', 'in', and 'rat' without them touching each other. We could have alternatively made 'eat' and 'rain', but that would be incorrect since that's only 2 words. + +[Solution](Solutions/341.py) + +--- + +### Problem 342 + +This problem was asked by Stripe. + +`reduce` (also known as `fold`) is a function that takes in an array, a combining function, and an initial value and builds up a result by calling the combining function on each element of the array, left to right. For example, we can write `sum()` in terms of reduce: + +```python +def add(a, b): + return a + b +``` + +```python +def sum(lst): + return reduce(lst, add, 0) +``` + +This should call add on the initial value with the first element of the array, and then the result of that with the second element of the array, and so on until we reach the end, when we return the sum of the array. + +Implement your own version of reduce. + +[Solution](Solutions/342.py) + +--- + +### Problem 343 + +This problem was asked by Google. + +Given a binary search tree and a range `[a, b]` (inclusive), return the sum of the elements of the binary search tree within the range. + +For example, given the following tree: + +``` + 5 + / \ + 3 8 + / \ / \ +2 4 6 10 +``` + +and the range `[4, 9]`, return `23 (5 + 4 + 6 + 8)`. + +[Solution](Solutions/343.py) + +--- + +### Problem 344 + +This problem was asked by Adobe. + +You are given a tree with an even number of nodes. Consider each connection between a parent and child node to be an "edge". You would like to remove some of these edges, such that the disconnected subtrees that remain each have an even number of nodes. + +For example, suppose your input was the following tree: + +``` + 1 + / \ + 2 3 + / \ + 4 5 + / | \ +6 7 8 +``` + +In this case, removing the edge `(3, 4)` satisfies our requirement. + +Write a function that returns the maximum number of edges you can remove while still satisfying this requirement. + +[Solution](Solutions/344.py) + +--- + +### Problem 345 + +This problem was asked by Google. + +You are given a set of synonyms, such as `(big, large)` and `(eat, consume)`. Using this set, determine if two sentences with the same number of words are equivalent. + +For example, the following two sentences are equivalent: + +- "He wants to eat food." +- "He wants to consume food." + +Note that the synonyms `(a, b)` and `(a, c)` do not necessarily imply `(b, c)`: consider the case of `(coach, bus)` and `(coach, teacher)`. + +Follow-up: what if we can assume that `(a, b)` and `(a, c)` do in fact imply `(b, c)`? + +[Solution](Solutions/345.py) + +--- + +### Problem 346 + +This problem was asked by Airbnb. + +You are given a huge list of airline ticket prices between different cities around the world on a given day. These are all direct flights. Each element in the list has the format `(source_city, destination, price)`. + +Consider a user who is willing to take up to `k` connections from their origin city `A` to their destination `B`. Find the cheapest fare possible for this journey and print the itinerary for that journey. + +For example, our traveler wants to go from JFK to LAX with up to 3 connections, and our input flights are as follows: + +``` +[ + ('JFK', 'ATL', 150), + ('ATL', 'SFO', 400), + ('ORD', 'LAX', 200), + ('LAX', 'DFW', 80), + ('JFK', 'HKG', 800), + ('ATL', 'ORD', 90), + ('JFK', 'LAX', 500), +] +``` + +Due to some improbably low flight prices, the cheapest itinerary would be JFK -> ATL -> ORD -> LAX, costing \$440. + +[Solution](Solutions/346.py) + +--- + +### Problem 347 + +This problem was asked by Yahoo. + +You are given a string of length `N` and a parameter `k`. The string can be manipulated by taking one of the first `k` letters and moving it to the end. + +Write a program to determine the lexicographically smallest string that can be created after an unlimited number of moves. + +For example, suppose we are given the string `daily` and `k = 1`. The best we can create in this case is `ailyd`. + +[Solution](Solutions/347.py) + +--- + +### Problem 348 + +This problem was asked by Zillow. + +A ternary search tree is a trie-like data structure where each node may have up to three children. Here is an example which represents the words `code`, `cob`, `be`, `ax`, `war`, and `we`. + +``` + c + / | \ + b o w + / | | | +a e d a +| / | | \ +x b e r e +``` + +The tree is structured according to the following rules: + +- left child nodes link to words lexicographically earlier than the parent prefix +- right child nodes link to words lexicographically later than the parent prefix +- middle child nodes continue the current word + +For instance, since code is the first word inserted in the tree, and `cob` lexicographically precedes `cod`, `cob` is represented as a left child extending from `cod`. + +Implement insertion and search functions for a ternary search tree. + +[Solution](Solutions/348.py) + +--- + +### Problem 349 + +This problem was asked by Grammarly. + +Soundex is an algorithm used to categorize phonetically, such that two names that sound alike but are spelled differently have the same representation. + +Soundex maps every name to a string consisting of one letter and three numbers, like `M460`. + +One version of the algorithm is as follows: + +- Remove consecutive consonants with the same sound (for example, change `ck -> c`). +- Keep the first letter. The remaining steps only apply to the rest of the string. +- Remove all vowels, including `y`, `w`, and `h`. +- Replace all consonants with the following digits: + ``` + b, f, p, v -> 1 + c, g, j, k, q, s, x, z -> 2 + d, t -> 3 + l -> 4 + m, n -> 5 + r -> 6 + ``` + +If you don't have three numbers yet, append zeros until you do. Keep the first three numbers. +Using this scheme, `Jackson` and `Jaxen` both map to `J250`. + +Implement Soundex. + +[Solution](Solutions/349.py) + +--- + +### Problem 350 + +This problem was asked by Uber. + +Write a program that determines the smallest number of perfect squares that sum up to `N`. + +Here are a few examples: + +- Given `N = 4`, return `1` `(4)` +- Given `N = 17`, return `2` `(16 + 1)` +- Given `N = 18`, return `2` `(9 + 9)` + +[Solution](Solutions/350.py) + +--- + +### Problem 351 + +This problem was asked by Quora. + +Word sense disambiguation is the problem of determining which sense a word takes on in a particular setting, if that word has multiple meanings. For example, in the sentence "I went to get money from the bank", bank probably means the place where people deposit money, not the land beside a river or lake. + +Suppose you are given a list of meanings for several words, formatted like so: + +``` +{ + "word_1": ["meaning one", "meaning two", ...], + ... + "word_n": ["meaning one", "meaning two", ...] +} +``` + +Given a sentence, most of whose words are contained in the meaning list above, create an algorithm that determines the likely sense of each possibly ambiguous word. + +[Solution](Solutions/351.md) + +--- + +### Problem 352 + +This problem was asked by Palantir. + +A typical American-style crossword puzzle grid is an `N x N` matrix with black and white squares, which obeys the following rules: + +- Every white square must be part of an "across" word and a "down" word. +- No word can be fewer than three letters long. +- Every white square must be reachable from every other white square. + +The grid is rotationally symmetric (for example, the colors of the top left and bottom right squares must match). +Write a program to determine whether a given matrix qualifies as a crossword grid. + +[Solution](Solutions/352.md) + +--- + +### Problem 353 + +This problem was asked by Square. + +You are given a histogram consisting of rectangles of different heights. These heights are represented in an input list, such that `[1, 3, 2, 5]` corresponds to the following diagram: + +``` + x + x + x x + x x x +x x x x +``` + +Determine the area of the largest rectangle that can be formed only from the bars of the histogram. For the diagram above, for example, this would be six, representing the `2 x 3` area at the bottom right. + +[Solution](Solutions/353.py) + +--- + +### Problem 354 + +This problem was asked by Google. + +Design a system to crawl and copy all of Wikipedia using a distributed network of machines. + +More specifically, suppose your server has access to a set of client machines. Your client machines can execute code you have written to access Wikipedia pages, download and parse their data, and write the results to a database. + +Some questions you may want to consider as part of your solution are: + +- How will you reach as many pages as possible? +- How can you keep track of pages that have already been visited? +- How will you deal with your client machines being blacklisted? +- How can you update your database when Wikipedia pages are added or updated? + +[Solution](Solutions/354.md) + +--- + +### Problem 355 + +This problem was asked by Airbnb. + +You are given an array `X` of floating-point numbers `x1, x2, ... xn`. These can be rounded up or down to create a corresponding array `Y` of integers `y1, y2, ... yn`. + +Write an algorithm that finds an appropriate `Y` array with the following properties: + +- The rounded sums of both arrays should be equal. +- The absolute pairwise difference between elements is minimized. In other words, `|x1- y1| + |x2- y2| + ... + |xn- yn|` should be as small as possible. + +For example, suppose your input is `[1.3, 2.3, 4.4]`. In this case you cannot do better than `[1, 2, 5]`, which has an absolute difference of `|1.3 - 1| + |2.3 - 2| + |4.4 - 5| = 1`. + +[Solution](Solutions/355.py) + +--- + +### Problem 356 + +This problem was asked by Netflix. + +Implement a queue using a set of fixed-length arrays. + +The queue should support `enqueue`, `dequeue`, and `get_size` operations. + +[Solution](Solutions/356.py) + +--- + +### Problem 357 + +This problem was asked by LinkedIn. + +You are given a binary tree in a peculiar string representation. Each node is written in the form `(lr)`, where `l` corresponds to the left child and `r` corresponds to the right child. + +If either `l` or `r` is null, it will be represented as a zero. Otherwise, it will be represented by a new `(lr)` pair. + +Here are a few examples: + +- A root node with no children: `(00)` +- A root node with two children: `((00)(00))` +- An unbalanced tree with three consecutive left children: `((((00)0)0)0)` + +Given this representation, determine the depth of the tree. + +[Solution](Solutions/357.py) + +--- + +### Problem 358 + +This problem was asked by Dropbox. + +Create a data structure that performs all the following operations in `O(1)` time: + +- `plus`: Add a key with value 1. If the key already exists, increment its value by one. +- `minus`: Decrement the value of a key. If the key's value is currently 1, remove it. +- `get_max`: Return a key with the highest value. +- `get_min`: Return a key with the lowest value. + +[Solution](Solutions/358.py) + +--- + +### Problem 359 + +This problem was asked by Slack. + +You are given a string formed by concatenating several words corresponding to the integers zero through nine and then anagramming. + +For example, the input could be 'niesevehrtfeev', which is an anagram of 'threefiveseven'. Note that there can be multiple instances of each integer. + +Given this string, return the original integers in sorted order. In the example above, this would be `357`. + +[Solution](Solutions/359.py) + +--- + +### Problem 360 + +This problem was asked by Spotify. + +You have access to ranked lists of songs for various users. Each song is represented as an integer, and more preferred songs appear earlier in each list. For example, the list `[4, 1, 7]` indicates that a user likes song `4` the best, followed by songs `1` and `7`. + +Given a set of these ranked lists, interleave them to create a playlist that satisfies everyone's priorities. + +For example, suppose your input is `{[1, 7, 3], [2, 1, 6, 7, 9], [3, 9, 5]}`. In this case a satisfactory playlist could be `[2, 1, 6, 7, 3, 9, 5]`. + +[Solution](Solutions/360.py) + +--- + +### Problem 361 + +This problem was asked by Facebook. + +Mastermind is a two-player game in which the first player attempts to guess the secret code of the second. In this version, the code may be any six-digit number with all distinct digits. + +Each turn the first player guesses some number, and the second player responds by saying how many digits in this number correctly matched their location in the secret code. For example, if the secret code were `123456`, then a guess of `175286` would score two, since `1` and `6` were correctly placed. + +Write an algorithm which, given a sequence of guesses and their scores, determines whether there exists some secret code that could have produced them. + +For example, for the following scores you should return `True`, since they correspond to the secret code `123456`: +`{175286: 2, 293416: 3, 654321: 0}` + +However, it is impossible for any key to result in the following scores, so in this case you should return `False`: +`{123456: 4, 345678: 4, 567890: 4}` + +[Solution](Solutions/361.py) + +--- + +### Problem 362 + +This problem was asked by Twitter. + +A strobogrammatic number is a positive number that appears the same after being rotated `180` degrees. For example, `16891` is strobogrammatic. + +Create a program that finds all strobogrammatic numbers with N digits. + +[Solution](Solutions/362.py) + +--- + +### Problem 363 + +Write a function, add_subtract, which alternately adds and subtracts curried arguments. Here are some sample operations: + +``` +add_subtract(7) -> 7 +add_subtract(1)(2)(3) -> 1 + 2 - 3 -> 0 +add_subtract(-5)(10)(3)(9) -> -5 + 10 - 3 + 9 -> 11 +``` + +[Solution](Solutions/363.py) + +--- + +### Problem 364 + +This problem was asked by Facebook. + +Describe an algorithm to compute the longest increasing subsequence of an array of numbers in `O(n log n)` time. + +[Solution](Solutions/364.py) + +--- + +### Problem 365 + +This problem was asked by Google. + +A quack is a data structure combining properties of both stacks and queues. It can be viewed as a list of elements written left to right such that three operations are possible: + +- `push(x)`: add a new item `x` to the left end of the list +- `pop()`: remove and return the item on the left end of the list +- `pull()`: remove the item on the right end of the list. + +Implement a quack using three stacks and `O(1)` additional memory, so that the amortized time for any push, pop, or pull operation is `O(1)`. + +[Solution](Solutions/365.py) + +--- diff --git a/Solutions/001.py b/Solutions/001.py new file mode 100644 index 0000000..72ed948 --- /dev/null +++ b/Solutions/001.py @@ -0,0 +1,34 @@ +""" +Problem: + +Given a list of numbers, return whether any two sums to k. For example, given +[10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. + +Bonus: Can you do this in one pass? +""" + +from typing import List + + +def check_target_sum(arr: List[int], target: int) -> bool: + # using hash list to store the previously seen values to get access to them in O(1) + previous = set() + for elem in arr: + if (target - elem) in previous: + return True + previous.add(elem) + return False + + +if __name__ == "__main__": + print(check_target_sum([], 17)) + print(check_target_sum([10, 15, 3, 7], 17)) + print(check_target_sum([10, 15, 3, 4], 17)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/002.py b/Solutions/002.py new file mode 100644 index 0000000..92d9800 --- /dev/null +++ b/Solutions/002.py @@ -0,0 +1,43 @@ +""" +Problem: + +Given an array of integers, return a new array such that each element at index i of the +new array is the product of all the numbers in the original array except the one at i. + +For example, if our input was [1, 2, 3, 4, 5], the expected output would be +[120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be +[2, 3, 6]. + +Follow-up: what if you can't use division? +""" + +from typing import List + + +def product_of_arr_except_ith_elem(arr: List[int]) -> int: + length = len(arr) + result = [1 for _ in range(length)] + # multiplying all the elements on the left of the ith element in the 1st pass + # and all the elements on the right of the ith element in the 2nd pass + prod = 1 + for i in range(length): + result[i] *= prod + prod *= arr[i] + prod = 1 + for i in range(length - 1, -1, -1): + result[i] *= prod + prod *= arr[i] + return result + + +if __name__ == "__main__": + print(product_of_arr_except_ith_elem([1, 2, 3, 4, 5])) + print(product_of_arr_except_ith_elem([3, 2, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/003.py b/Solutions/003.py new file mode 100644 index 0000000..8487f18 --- /dev/null +++ b/Solutions/003.py @@ -0,0 +1,92 @@ +""" +Problem: + +Write a program to serialize a tree into a string and deserialize a string into a tree. +""" + +from DataStructures.Queue import Queue +from DataStructures.Tree import Node, BinaryTree + + +def serialize_helper(node: Node) -> str: + # helper function to serialize a binary tree (uses prefix traversal) + # data is padded with single quotes (') and comma (,) is used as a delimiter + if node.right is None and node.left is None: + return f"'{node.val}','None','None'" + elif node.left is not None and node.right is None: + return f"'{node.val}',{serialize_helper(node.left)},'None'" + elif node.left is None and node.right is not None: + return f"'{node.val}','None',{serialize_helper(node.right)}" + elif node.left is not None and node.right is not None: + return ( + f"'{node.val}'," + + f"{serialize_helper(node.left)}," + + f"{serialize_helper(node.right)}" + ) + + +def serialize(tree: BinaryTree) -> str: + return serialize_helper(tree.root) + + +def deserialize_helper(node: Node, queue: Queue) -> Node: + # helper function to deserialize a string into a Binary Tree + # data is a queue containing the data as a prefix notation can be easily decoded + # using a queue + left = queue.dequeue().strip("'") + if left != "None": + # if the left child exists, its added to the tree + node.left = Node(left) + node.left = deserialize_helper(node.left, queue) + + right = queue.dequeue().strip("'") + if right != "None": + # if the right child exists, its added to the tree + node.right = Node(right) + node.right = deserialize_helper(node.right, queue) + return node + + +def deserialize(string: str) -> BinaryTree: + # the string needs to have the same format as the binary tree serialization + # eg: data is padded with single quotes (') and comma (,) is used as a delimiter + data = string.split(",") + queue = Queue() + for node in data: + queue.enqueue(node) + tree = BinaryTree() + tree.root = Node(queue.dequeue().strip("'")) + deserialize_helper(tree.root, queue) + return tree + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = Node("root") + + tree.root.left = Node("left") + tree.root.right = Node("right") + + tree.root.left.left = Node("left.left") + + print(serialize(tree)) + + generated_tree = deserialize( + "'root','left','left.left','None','None','None','right','None','None'" + ) + + print(serialize(generated_tree)) + + +""" +SPECS: + +SERIALIZE: (n = Number of Nodes) +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) + +DESERIALIZE: (n = Number of Characters in the String) +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/004.py b/Solutions/004.py new file mode 100644 index 0000000..b1957cc --- /dev/null +++ b/Solutions/004.py @@ -0,0 +1,49 @@ +""" +Problem: + +Given an array of integers, find the first missing positive integer in linear time and +constant space. 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. + +For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. + +You can modify the input array in-place. +""" + +from typing import List + + +def first_missing_positive_integer(arr: List[int]) -> int: + # placing the positive elements (< length) in their proper position + # proper position index = element - 1 + # if after the palcement is complete, index of the 1st element not in its proper + # position is the answer + length = len(arr) + for i in range(length): + correctPos = arr[i] - 1 + while 1 <= arr[i] <= length and arr[i] != arr[correctPos]: + arr[i], arr[correctPos] = arr[correctPos], arr[i] + correctPos = arr[i] - 1 + # finding the first missing positive integer + for i in range(length): + if i + 1 != arr[i]: + return i + 1 + return length + 1 + + +if __name__ == "__main__": + print(first_missing_positive_integer([3, 4, 2, 1])) + print(first_missing_positive_integer([3, 4, -1, 1])) + print(first_missing_positive_integer([1, 2, 5])) + print(first_missing_positive_integer([-1, -2])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) + +NOTE: Even though there is a nested loop it is a O(n) algorithm as the cap on the + maximum iterations is 2 * n [Amortised analysis] +""" diff --git a/Solutions/005.py b/Solutions/005.py new file mode 100644 index 0000000..3dbe776 --- /dev/null +++ b/Solutions/005.py @@ -0,0 +1,56 @@ +""" +Problem: + +cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last +element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) +returns 4. + +Given this implementation of cons: + +def cons(a, b): + def pair(f): + return f(a, b) + return pair +""" + +from typing import Callable + + +# given implementation of cons: +def cons(a, b): + def pair(f): + return f(a, b) + + return pair + + +# car implementation +def car(f: Callable) -> int: + z = lambda x, y: x + return f(z) + + +# cdr implementation +def cdr(f: Callable) -> int: + z = lambda x, y: y + return f(z) + + +if __name__ == "__main__": + pair = cons(1, 3) + + print(car(pair)) + print(cdr(pair)) + + +""" +SPECS: + +car: +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) + +cdr: +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/006.py b/Solutions/006.py new file mode 100644 index 0000000..5adb586 --- /dev/null +++ b/Solutions/006.py @@ -0,0 +1,95 @@ +""" +Problem: + +An XOR linked list is a more memory efficient doubly linked list. Instead of each node +holding next and prev fields, it holds a field named both, which is an XOR of the next +node and the previous node. Implement an XOR linked list; it has an add(element) which +adds the element to the end, and a get(index) which returns the node at index. + +If using a language that has no pointers (such as Python), you can assume you have +access to get_pointer and dereference_pointer functions that converts between nodes +and memory addresses. +""" + + +# Solution copied from: +# https://github.com/r1cc4rdo/daily_coding_problem/blob/master/problems/06 + + +""" +An XOR linked list is a more memory efficient doubly linked list. +Instead of each node holding next and prev fields, it holds a field named both, which +is a XOR of the next node and the previous node. Implement a XOR linked list; it has an +add(element) which adds the element to the end, and a get(index) which returns the node +at index. + +NOTE: python does not have actual pointers (id() exists but it is not an actual pointer +in all implementations). For this reason, we use a python list to simulate memory. +Indexes are the addresses in memory. This has the unfortunate consequence that the +travel logic needs to reside in the List class rather than the Node one. +""" + +from typing import Tuple + + +class XORLinkedListNode: + def __init__(self, val: int, prev: int, next: int) -> None: + self.val = val + self.both = prev ^ next + + def next_node(self, prev_idx: int) -> int: + return self.both ^ prev_idx + + def prev_node(self, next_idx: int) -> int: + return self.both ^ next_idx + + +class XORLinkedList: + def __init__(self) -> None: + self.memory = [XORLinkedListNode(None, -1, -1)] + + def head(self) -> Tuple[int, int, XORLinkedListNode]: + # head node index, prev node index, head node + return 0, -1, self.memory[0] + + def add(self, val: int) -> None: + current_node_index, previous_node_index, current_node = self.head() + while True: + # walk down the list until the end is found + next_node_index = current_node.next_node(previous_node_index) + if next_node_index == -1: + # the end is reached + break + previous_node_index, current_node_index = ( + current_node_index, + next_node_index, + ) + current_node = self.memory[next_node_index] + # allocation + new_node_index = len(self.memory) + current_node.both = previous_node_index ^ new_node_index + self.memory.append(XORLinkedListNode(val, current_node_index, -1)) + + def get(self, index: int) -> int: + current_index, previous_index, current_node = self.head() + for _ in range(index + 1): + previous_index, current_index = ( + current_index, + current_node.next_node(previous_index), + ) + current_node = self.memory[current_index] + return current_node.val + + +if __name__ == "__main__": + xor_linked_list = XORLinkedList() + + xor_linked_list.add(1) + xor_linked_list.add(2) + xor_linked_list.add(3) + xor_linked_list.add(4) + + print(xor_linked_list.get(0)) + print(xor_linked_list.get(1)) + print(xor_linked_list.get(2)) + print(xor_linked_list.get(3)) diff --git a/Solutions/007.py b/Solutions/007.py new file mode 100644 index 0000000..665996c --- /dev/null +++ b/Solutions/007.py @@ -0,0 +1,47 @@ +""" +Problem: + +Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of +ways it can be decoded. + +For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', +and 'ak'. + +You can assume that the messages are decodable. For example, '001' is not allowed. +""" + + +def count_decoding(digits: str) -> int: + len_digits = len(digits) + # dynamic Programming table + count = [0 for _ in range(len_digits + 1)] + # base cases + count[0] = 1 + count[1] = 1 + + for i in range(2, len_digits + 1): + count[i] = 0 + # if the last digit is not 0, then last digit must add to the number of words + if digits[i - 1] > "0": + count[i] = count[i - 1] + # if the number formed by the last 2 digits is less than 26, its a valid + # character + if digits[i - 2] == "1" or (digits[i - 2] == "2" and digits[i - 1] < "7"): + count[i] += count[i - 2] + return count[len_digits] + + +if __name__ == "__main__": + print(count_decoding("81")) + print(count_decoding("11")) + print(count_decoding("111")) + print(count_decoding("1311")) + print(count_decoding("1111")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/008.py b/Solutions/008.py new file mode 100644 index 0000000..d41659f --- /dev/null +++ b/Solutions/008.py @@ -0,0 +1,89 @@ +""" +Problem: + +A unival tree (which stands for "universal value") is a tree where all nodes under it +have the same value. + +Given the root to a binary tree, count the number of unival subtrees. + +For example, the following tree has 5 unival subtrees: + + 0 + / \ + 1 0 + / \ + 1 0 + / \ + 1 1 +""" + +from typing import Tuple + +from DataStructures.Tree import Node, BinaryTree + + +def num_universal_helper(node: Node, val: int, acc: int = 0) -> Tuple[int, bool]: + # base case for recursion [leaf node] + if node.left is None and node.right is None: + if node.val == val: + return (acc + 1), True + return (acc + 1), False + # if the value matches the parent's value, its children are also checked + elif node.val == val: + if node.left: + acc, res1 = num_universal_helper(node.left, val, acc) + else: + res1 = True + if node.right: + acc, res2 = num_universal_helper(node.right, val, acc) + else: + res2 = True + if res1 and res2: + acc += 1 + # If the value doesn't match the parent's value, its children are checked with the + # new value (value of the current node) + else: + if node.left: + acc, res1 = num_universal_helper(node.left, node.val, acc) + else: + res1 = True + if node.right: + acc, res2 = num_universal_helper(node.right, node.val, acc) + else: + res2 = True + if res1 and res2: + acc += 1 + return acc, (node.val == val) + + +def num_universal(tree: BinaryTree) -> int: + if not tree.root: + return 0 + result, _ = num_universal_helper(tree.root, tree.root.val) + return result + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = Node(0) + tree.root.left = Node(1) + tree.root.right = Node(0) + + tree.root.right.left = Node(1) + tree.root.right.right = Node(0) + + tree.root.right.left.left = Node(1) + tree.root.right.left.right = Node(1) + + print(tree) + + print(num_universal(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) [call stack] +""" diff --git a/Solutions/009.py b/Solutions/009.py new file mode 100644 index 0000000..ede0d39 --- /dev/null +++ b/Solutions/009.py @@ -0,0 +1,35 @@ +""" +Problem: + +Given a list of integers, write a function that returns the largest sum of non-adjacent +numbers. Numbers can be 0 or negative. + +For example, [2, 4, 6, 8] should return 12, since we pick 4 and 8. [5, 1, 1, 5] should +return 10, since we pick 5 and 5. +""" + +from typing import List + + +def max_nonadjacent_sum(arr: List[int]) -> int: + including = 0 + excluding = 0 + for elem in arr: + # updating maximum sum including and excluding the current element + including, excluding = max(excluding + elem, elem), max(excluding, including) + return max(including, excluding) + + +if __name__ == "__main__": + print(max_nonadjacent_sum([2, 4, 6, 8])) + print(max_nonadjacent_sum([5, 1, 1, 5])) + print(max_nonadjacent_sum([-5, 1, 1, -5])) + print(max_nonadjacent_sum([5, 5, 10, 100, 10, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/010.py b/Solutions/010.py new file mode 100644 index 0000000..55ebc02 --- /dev/null +++ b/Solutions/010.py @@ -0,0 +1,29 @@ +""" +Problem: + +Implement a job scheduler which takes in a function f and an integer n, and calls f +after n milliseconds. +""" + +from time import sleep +from typing import Callable + + +def get_seconds_from_milliseconds(time_mil: int) -> float: + return time_mil / 1000 + + +def job_scheduler(function: Callable, delay: int) -> None: + sleep(get_seconds_from_milliseconds(delay)) + function() + + +# function to test the job scheduler +def print_hello() -> None: + print("Hello!") + + +if __name__ == "__main__": + job_scheduler(print_hello, 1) + job_scheduler(print_hello, 500) + job_scheduler(print_hello, 1000) diff --git a/Solutions/011.py b/Solutions/011.py new file mode 100644 index 0000000..5c48e95 --- /dev/null +++ b/Solutions/011.py @@ -0,0 +1,39 @@ +""" +Problem: + +Implement an autocomplete system. That is, given a query string s and a set of all +possible query strings, return all strings in the set that have s as a prefix. + +For example, given the query string de and the set of strings [dog, deer, deal], return +[deer, deal]. + +Hint: Try preprocessing the dictionary into a more efficient data structure to speed up +queries. +""" + +from typing import List + +from DataStructures.Trie import Trie + + +def get_suggestion(word_list: List[str], prefix: str) -> List[str]: + # using trie data structure to get the suggestions (for deatils, check + # ./DataStructres/Trie) + trie = Trie() + trie.add_words(word_list) + prefix_match = trie.get_suggestions(prefix) + # type casting the result to list as the return type is a set + return list(prefix_match) + + +if __name__ == "__main__": + print(get_suggestion(["deer", "dog", "deal"], "de")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = total number of characters (all words)] +""" diff --git a/Solutions/014.py b/Solutions/014.py new file mode 100644 index 0000000..7be7f68 --- /dev/null +++ b/Solutions/014.py @@ -0,0 +1,41 @@ +""" +Problem: + +The area of a circle is defined as r^2. Estimate pi to 3 decimal places using a Monte +Carlo method. + +Hint: The basic equation of a circle is x^2 + y^2 = r^2. +""" + +from random import random +from typing import Tuple + + +def coordinate_gen() -> Tuple[float, float]: + # Helper function to generate a random coordinate in the square bounded by + # x = -1, x = 1 and y = -1, y = 1 + return random(), random() + + +def pi_approx(iterations: int = 1_000_000) -> float: + circle_area = 0 + for _ in range(iterations): + x, y = coordinate_gen() + if pow(x, 2) + pow(y, 2) <= 1: + circle_area += 1 + # Using Monte Carlo approximation [pi = 4 x (Area of circle / Area of square)] + # [Area of circle = number of points in circle, + # Area of square = total number of points] + return round(4 * circle_area / iterations, 3) + + +if __name__ == "__main__": + print(pi_approx()) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/015.py b/Solutions/015.py new file mode 100644 index 0000000..9673430 --- /dev/null +++ b/Solutions/015.py @@ -0,0 +1,44 @@ +""" +Problem: + +Given a stream of elements too large to store in memory, pick a random element from the +stream with uniform probability. +""" + +from random import randint +import matplotlib.pyplot as plt +from typing import Generator + + +def element_stream() -> Generator[int, None, None]: + # generator function to simulate a stream of elements too large to store in memory + while True: + yield randint(1, 10_000) + + +def random_selector(generator: Generator[int, None, None]) -> int: + # getting 10 elements from the stream of elements + arr = [next(generator) for i in range(10)] + # selecting a random element from the array of 10 elements + pos = randint(0, 9) + return arr[pos] + + +if __name__ == "__main__": + generator = element_stream() + # storing the selected elements for plotting a graph + values = [] + for i in range(100_000): + values.append(random_selector(generator)) + # plotting the histogram of frequencies of the selected elements (not stated in + # problem, added to display the uniform distribution) + plt.hist(values, edgecolor="black") + plt.show() + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/016.py b/Solutions/016.py new file mode 100644 index 0000000..006fb9c --- /dev/null +++ b/Solutions/016.py @@ -0,0 +1,45 @@ +""" +Problem: + +You run an e-commerce website and want to record the last N order ids in a log. +Implement a data structure to accomplish this, with the following API: + +record(order_id): adds the order_id to the log get_last(i): gets the ith last element +from the log. i is guaranteed to be smaller than or equal to N. You should be as +efficient with time and space as possible. +""" + + +class Order_Log: + def __init__(self, N: int) -> None: + self.circular_buffer = [None for _ in range(N)] + self.N = N + self.pos = 0 + + def record(self, order_id: int) -> None: + # adding the order_id to the log + self.circular_buffer[self.pos] = order_id + self.pos += 1 + if self.pos == self.N: + self.pos = 0 + + def get_last(self, i: int) -> int: + # getting the ith last element from the log + position = self.pos - i + return self.circular_buffer[position] + + +if __name__ == "__main__": + log = Order_Log(10) + + for id in range(20): + log.record(id) + + print(log.get_last(1)) + print(log.get_last(5)) + + log.record(20) + log.record(21) + + print(log.get_last(1)) + print(log.get_last(3)) diff --git a/Solutions/017.py b/Solutions/017.py new file mode 100644 index 0000000..080558d --- /dev/null +++ b/Solutions/017.py @@ -0,0 +1,84 @@ +""" +Problem: + +Suppose we represent our file system by a string in the following manner: + +The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: + +dir + subdir1 + subdir2 + file.ext +The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 +containing a file file.ext. + +The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n +\t\t\tfile2.ext" represents: + +dir + subdir1 + file1.ext + subsubdir1 + subdir2 + subsubdir2 + file2.ext +The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a +file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a +second-level sub-directory subsubdir2 containing a file file2.ext. + +We are interested in finding the longest (number of characters) absolute path to a file +within our file system. For example, in the second example above, the longest absolute +path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the +double quotes). + +Given a string representing the file system in the above format, return the length of +the longest absolute path to a file in the abstracted file system. If there is no file +in the system, return 0. +""" + + +def count_tabs(string: str) -> int: + return string.count("\t") + + +def longest_dir(string: str) -> int: + dir_list = string.split("\n") + length = len(dir_list) + longest_directory_length = 0 + # calculating the length of the longest absolute path + for i in range(length - 1, -1, -1): + temp = dir_list[i] + temp_dir = temp.lstrip("\t") + # skipping calculation if it is not a file + if temp_dir.find(".") == -1: + continue + # counting the number of tabs to check the location + # (0 tabs = root, 1 tab = sub-directory, 2 tabs = sub-sub-directory, ...) + count = count_tabs(temp) + # moving back through the list to recreate the entire directory + for j in range(i, -1, -1): + if count_tabs(dir_list[j]) < count: + temp_dir = dir_list[j].lstrip("\t") + "/" + temp_dir + temp = dir_list[j] + count = count_tabs(temp) + # storing the longest directory path length + longest_directory_length = max(longest_directory_length, len(temp_dir)) + return longest_directory_length + + +if __name__ == "__main__": + print(longest_dir("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext")) + print( + longest_dir( + "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2" + + "\n\t\t\tfile2.ext" + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/018.py b/Solutions/018.py new file mode 100644 index 0000000..b91be81 --- /dev/null +++ b/Solutions/018.py @@ -0,0 +1,60 @@ +""" +Problem: + +Given an array of integers and a number k, where 1 <= k <= length of the array, compute +the maximum values of each subarray of length k. + +For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], +since: + +10 = max(10, 5, 2) +7 = max(5, 2, 7) +8 = max(2, 7, 8) +8 = max(7, 8, 7) +Do this in O(n) time and O(k) space. You can modify the input array in-place and you do +not need to store the results. You can simply print them out as you compute them. +""" + +from collections import deque +from typing import List + + +def calc_max_per_k_elems(arr: List[int], k: int) -> List[int]: + length = len(arr) + if not arr: + return None + if length <= k: + return max(arr) + # storing results (even though the problem states it can be directly printed) + result = [] + dq = deque() + # calculating the 1st element + for i in range(k): + while dq and arr[dq[-1]] < arr[i]: + dq.pop() + dq.append(i) + result.append(arr[dq[0]]) + # generating the rest of the resultant elements + for i in range(k, length): + # removing all elements apart from the last k elements + while dq and dq[0] <= i - k: + dq.popleft() + # removing the elements smaller than the current element + while dq and arr[dq[-1]] < arr[i]: + dq.pop() + dq.append(i) + result.append(arr[dq[0]]) + return result + + +if __name__ == "__main__": + print(calc_max_per_k_elems([10, 5, 2, 7, 8, 7], 3)) + print(calc_max_per_k_elems([1, 91, 17, 46, 45, 36, 9], 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(k) +""" diff --git a/Solutions/019.py b/Solutions/019.py new file mode 100644 index 0000000..12f5bba --- /dev/null +++ b/Solutions/019.py @@ -0,0 +1,62 @@ +""" +Problem: + +A builder is looking to build a row of N houses that can be of K different colors. He +has a goal of minimizing cost while ensuring that no two neighboring houses are of the +same color. + +Given an N by K matrix where the nth row and kth column represents the cost to build +the nth house with kth color, return the minimum cost which achieves this goal. +""" + +from typing import List + +Matrix = List[List[int]] + + +def minimize_color_cost_helper( + color_matrix: Matrix, + results: List, + curr_house: int, + prev_color: int, + curr_cost: int, + n: int, + k: int, +): + if curr_house == n: + results.append(curr_cost) + return + # generating all the possible combinations + for curr_color in range(k): + # avoiding two neighboring houses having the same color + if curr_color != prev_color: + minimize_color_cost_helper( + color_matrix, + results, + curr_house + 1, + curr_color, + curr_cost + color_matrix[curr_house][curr_color], + n, + k, + ) + + +def minimize_color_cost(color_matrix: Matrix) -> int: + sequence = [] + n, k = len(color_matrix), len(color_matrix[0]) + minimize_color_cost_helper(color_matrix, sequence, 0, -1, 0, n, k) + # returning the minimum cost + return min(sequence) + + +if __name__ == "__main__": + print(minimize_color_cost([[1, 5, 2], [2, 3, 1], [7, 3, 5], [6, 2, 3]])) + print(minimize_color_cost([[1, 5, 2], [2, 3, 1], [7, 3, 5], [6, 3, 2]])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x k!) +SPACE COMPLEXITY: O(n x k!) +""" diff --git a/Solutions/020.py b/Solutions/020.py new file mode 100644 index 0000000..d3b83e2 --- /dev/null +++ b/Solutions/020.py @@ -0,0 +1,83 @@ +""" +Problem: + +Given 2 Linked List, find out whether they share a common node. If there is a common +node, find the common node. +""" + +from typing import Optional + +from DataStructures.LinkedList import Node, LinkedList + + +def common_node(ll1: LinkedList, ll2: LinkedList) -> bool: + # traversing to the end of the Linked Lists and comparing the nodes + pos1 = ll1.head + while pos1.next != None: + pos1 = pos1.next + pos2 = ll2.head + while pos2.next != None: + pos2 = pos2.next + # if the location of the last nodes of the lists are same, then they must share a + # common node + return pos1 is pos2 + + +def common_node_pos(ll1: LinkedList, ll2: LinkedList) -> Optional[Node]: + if common_node(ll1, ll2): + len1, len2 = len(ll1), len(ll2) + pos1, pos2 = ll1.head, ll2.head + smaller_len = min(len1, len2) + # traversing to the position where the intersection may occour in the longer + # Linked List + if len1 < len2: + pos = len2 - len1 + for _ in range(pos): + pos2 = pos2.next + elif len1 > len2: + pos = len1 - len2 + for _ in range(pos): + pos1 = pos1.next + # checking for intersecting node + for _ in range(smaller_len): + if pos1 is pos2: + return pos1 + pos1 = pos1.next + pos2 = pos2.next + # no intersection + return None + + +if __name__ == "__main__": + ll1 = LinkedList() + ll1.add(5) + ll1.add(6) + ll1.add(7) + ll1.add(8) + + ll2 = LinkedList() + ll2.add(1) + ll2.add(2) + ll2.add(3) + ll2.add(4) + + ll3 = LinkedList() + ll3.add(9) + ll3.rear.next = ll1.head.next.next + ll3.rear = ll3.rear.next.next + ll3.length = 3 + + print("Linked List 1:", ll1) + print("Linked List 2:", ll2) + print("Linked List 3:", ll3) + + print(common_node_pos(ll1, ll2)) + print(common_node_pos(ll1, ll3).val) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/021.py b/Solutions/021.py new file mode 100644 index 0000000..ee02245 --- /dev/null +++ b/Solutions/021.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given an array of time intervals (start, end) for classroom lectures (possibly +overlapping), find the minimum number of rooms required. + +For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. +""" + +from typing import List, Tuple + + +def minimum_rooms_required(intervals: List[Tuple[int, int]]) -> int: + delta_room_map = {} + max_rooms = 0 + curr_rooms = 0 + # updating time map + for start, end in intervals: + if start not in delta_room_map: + delta_room_map[start] = 0 + delta_room_map[start] += 1 + if end not in delta_room_map: + delta_room_map[end] = 0 + delta_room_map[end] -= 1 + # generating the minimum number of rooms required + sorted_events = sorted(delta_room_map.items(), key=lambda x: x[0]) + for _, rooms in sorted_events: + curr_rooms += rooms + max_rooms = max(max_rooms, curr_rooms) + return max_rooms + + +if __name__ == "__main__": + print(minimum_rooms_required([(30, 75), (0, 50), (60, 150)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/022.py b/Solutions/022.py new file mode 100644 index 0000000..5ba0862 --- /dev/null +++ b/Solutions/022.py @@ -0,0 +1,53 @@ +""" +Problem: + +Given a dictionary of words and a string made up of those words (no spaces), return the +original sentence in a list. If there is more than one possible reconstruction, return +any of them. If there is no possible reconstruction, then return null. + +For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string +"thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. + +Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string +"bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or +['bedbath', 'and', 'beyond']. +""" + +from typing import List + + +def get_sentence_split(word_list: List[str], string: str) -> List[str]: + word_set = set() + buffer = "" + words_found = [] + # populating the set with the words for O(1) access + for word in word_list: + word_set.add(word) + # searching for words in the string + for char in string: + buffer += char + if buffer in word_set: + words_found.append(buffer) + buffer = "" + + if len(words_found) == 0: + return None + return words_found + + +if __name__ == "__main__": + print(get_sentence_split(["quick", "brown", "the", "fox"], "thequickbrownfox")) + print( + get_sentence_split( + ["bed", "bath", "bedbath", "and", "beyond"], "bedbathandbeyond" + ) + ) + print(get_sentence_split(["quick", "brown", "the", "fox"], "bedbathandbeyond")) + + +""" +SPECS: + +TIME COMPLEXITY: O(characters_in_input_string) +SPACE COMPLEXITY: O(words) +""" diff --git a/Solutions/023.py b/Solutions/023.py new file mode 100644 index 0000000..8a41cba --- /dev/null +++ b/Solutions/023.py @@ -0,0 +1,125 @@ +""" +Problem: + +You are given an M by N matrix consisting of booleans that represents a board. Each +True boolean represents a wall. Each False boolean represents a tile you can walk on. + +Given this matrix, a start coordinate, and an end coordinate, return the minimum number +of steps required to reach the end coordinate from the start. If there is no possible +path, then return null. You can move up, left, down, and right. You cannot move through +walls. You cannot wrap around the edges of the board. + +For example, given the following board: + +[[f, f, f, f], + [t, t, f, t], + [f, f, f, f], + [f, f, f, f]] +and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of +steps required to reach the end is 7, since we would need to go through (1, 2) because +there is a wall everywhere else on the second row. +""" + +from numpy import array +from sys import maxsize +from typing import List, Tuple, Union + + +Matrix_str = List[List[str]] +Matrix = List[List[Union[int, str]]] + + +def get_neighbours(pos: Tuple[int, int], n: int, m: int) -> List[Tuple[int, int]]: + i, j = pos + neighbours = [ + (i - 1, j), + (i + 1, j), + (i, j + 1), + (i, j - 1), + ] + valid_neighbours = [] + for neighbour in neighbours: + y, x = neighbour + if 0 <= y < n and 0 <= x < m: + valid_neighbours.append(neighbour) + return valid_neighbours + + +def transform_matrix(matrix: Matrix_str, n: int, m: int) -> None: + # helper function to transform Matrix_str to Matrix type + for i in range(n): + for j in range(m): + if matrix[i][j] == "f": + matrix[i][j] = 0 + + +def get_min_steps_helper(matrix: Matrix, pos: Tuple[int, int], n: int, m: int) -> None: + # helper function to calculate the distance of position from the source + i, j = pos + unexplored_positions = [] + neighbours = get_neighbours(pos, n, m) + # calculate the distance for the neighbours + for neighbour in neighbours: + y, x = neighbour + if matrix[y][x] != "t": + if matrix[y][x] != 0: + curr_value = matrix[y][x] + else: + curr_value = maxsize + unexplored_positions.append(neighbour) + matrix[y][x] = min(curr_value, matrix[i][j] + 1) + # exploring unexplored positions + for position in unexplored_positions: + get_min_steps_helper(matrix, position, n, m) + + +def get_min_steps( + matrix: Matrix_str, start: Tuple[int, int], end: Tuple[int, int] +) -> int: + n = len(matrix) + m = len(matrix[0]) + transform_matrix(matrix, n, m) + # offseting start by 1 (as 0 represents unvisited positions) + i, j = start + matrix[i][j] = 1 + # calculating the distance for each position from the start + neighbours = get_neighbours(start, n, m) + # updating the value of neighbours (hard-coded to 2 as the starting position value + # is 1) + for neighbour in neighbours: + y, x = neighbour + if matrix[y][x] == 0: + matrix[y][x] = 2 + # using helper to calculate the distance for the rest of the matrix + for neighbour in neighbours: + y, x = neighbour + if matrix[y][x] == 2: + get_min_steps_helper(matrix, neighbour, n, m) + # matrix[y][x] - 1 is returned as initially the value was offsetted by +1 + y, x = end + if matrix[y][x] == "t" or matrix[y][x] == 0: + return None + return matrix[y][x] - 1 + + +if __name__ == "__main__": + mat = [ + ["f", "f", "f", "f"], + ["t", "t", "f", "t"], + ["f", "f", "f", "f"], + ["f", "f", "f", "f"], + ] + start = (3, 0) + end = (0, 0) + + print(array(mat)) + print(get_min_steps(mat, start, end)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) [unexplored_positions can have at most 2 entries (repeated +n x m times)] +""" diff --git a/Solutions/024.py b/Solutions/024.py new file mode 100644 index 0000000..519c2d4 --- /dev/null +++ b/Solutions/024.py @@ -0,0 +1,124 @@ +""" +Problem: + +Implement locking in a binary tree. A binary tree node can be locked or unlocked only +if all of its descendants or ancestors are not locked. + +Design a binary tree node class with the following methods: + +is_locked, which returns whether the node is locked. lock, which attempts to lock the +node. If it cannot be locked, then it should return false. Otherwise, it should lock it +and return true. unlock, which unlocks the node. If it cannot be unlocked, then it +should return false. Otherwise, it should unlock it and return true. You may augment +the node to add parent pointers or any other property you would like. You may assume +the class is used in a single-threaded program, so there is no need for actual locks or +mutexes. Each method should run in O(h), where h is the height of the tree. +""" + +from DataStructures.Tree import Node, BinaryTree + + +class NodeWithLock(Node): + """ + Binary Tree Node with locking mechanism + + Functions: + is_locked: check if the current node is locked + lock: locks the current node + unlock: unlocks the current node + _is_any_parent_unlocked: helper function to check if any parent is unlocked + _is_any_descendant_unlocked: helper function to check if any of the descendant is + unlocked + """ + + def __init__(self, val: int) -> None: + Node.__init__(self, val) + self.locked = False + self.parent = None + + def __str__(self) -> str: + curr_node = f"{self.val}, {'locked' if self.locked else 'unlocked'}" + left, right = "", "" + if self.left: + left = f"{self.left} " + if self.right: + right = f" {self.right}" + return f"({left} {curr_node} {right})" + + def is_locked(self) -> bool: + return self.locked + + def lock(self) -> bool: + is_any_parent_unlocked = self._is_any_parent_unlocked() + is_any_descendant_unlocked = self._is_any_descendant_unlocked() + if is_any_parent_unlocked or is_any_descendant_unlocked: + self.locked = True + return True + return False + + def unlock(self) -> bool: + is_any_parent_unlocked = self._is_any_parent_unlocked() + is_any_descendant_unlocked = self._is_any_descendant_unlocked() + if is_any_parent_unlocked or is_any_descendant_unlocked: + self.locked = False + return True + return False + + def _is_any_parent_unlocked(self) -> bool: + # time complexity: O(log(n)) + node = self + while node.parent: + if not node.is_locked(): + return True + node = node.parent + return False + + def _is_any_descendant_unlocked(self) -> bool: + # time complexity: O(log(n)) + if not self.is_locked(): + return True + + if self.left: + left = self.left._is_any_descendant_unlocked() + else: + left = False + if self.right: + right = self.right._is_any_descendant_unlocked() + else: + right = False + return left or right + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = NodeWithLock(5) + + tree.root.left = NodeWithLock(3) + tree.root.left.parent = tree.root + tree.root.right = NodeWithLock(18) + tree.root.right.parent = tree.root + + tree.root.left.left = NodeWithLock(0) + tree.root.left.left.parent = tree.root.left + + print(tree) + + print() + print(tree.root.left.left.lock()) + print(tree.root.left.lock()) + print(tree.root.lock()) + print() + + print(tree) + + print() + print(tree.root.left.unlock()) + print() + + print(tree) + + print() + print(tree.root.unlock()) + print() + + print(tree) diff --git a/Solutions/025.py b/Solutions/025.py new file mode 100644 index 0000000..d45e12f --- /dev/null +++ b/Solutions/025.py @@ -0,0 +1,53 @@ +""" +Problem: + +Implement regular expression matching with the following special characters: + +. (period) which matches any single character +* (asterisk) which matches zero or more of the preceding element That is, implement a +function that takes in a string and a valid regular expression and returns whether or +not the string matches the regular expression. +For example, given the regular expression "ra." and the string "ray", your function +should return true. The same regular expression on the string "raymond" should return +false. + +Given the regular expression ".*at" and the string "chat", your function should return +true. The same regular expression on the string "chats" should return false. +""" + + +def is_regex_match(pattern: str, text: str) -> bool: + n, m = len(text), len(pattern) + dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] + dp[0][0] = True + # populating the 1st row of the lookup table + for i in range(1, m + 1): + if pattern[i - 1] == "*": + dp[0][i] = dp[0][i - 2] + # populating the remaining lookup table + for i in range(1, n + 1): + for j in range(1, m + 1): + if pattern[j - 1] == "." or pattern[j - 1] == text[i - 1]: + dp[i][j] = dp[i - 1][j - 1] + elif pattern[j - 1] == "*": + dp[i][j] = dp[i][j - 2] + if pattern[j - 2] == "." or pattern[j - 2] == text[i - 1]: + dp[i][j] = dp[i][j] | dp[i - 1][j] + return dp[n][m] + + +if __name__ == "__main__": + print(is_regex_match("r.y", "ray")) + print(is_regex_match("ra.", "rays")) + print(is_regex_match(".*at", "chat")) + print(is_regex_match(".*at", "chats")) + print(is_regex_match(".*", "random-word")) + print(is_regex_match(".*a", "random-word")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) +""" diff --git a/Solutions/026.py b/Solutions/026.py new file mode 100644 index 0000000..0edf66e --- /dev/null +++ b/Solutions/026.py @@ -0,0 +1,71 @@ +""" +Problem: + +Given a singly linked list and an integer k, remove the kth last element from the list. +k is guaranteed to be smaller than the length of the list. + +The list is very long, so making more than one pass is prohibitively expensive. + +Do this in constant space and in one pass. +""" + +from DataStructures.LinkedList import Node, LinkedList + + +def delete_kth_last_node(ll: LinkedList, k: int) -> None: + # case for head node removal + if k == len(ll): + temp = ll.head + if len(ll) == 1: + ll.head = None + ll.rear = None + else: + ll.head = temp.next + temp.next = None + ll.length -= 1 + del temp + return + # generic node removal + ptr_end = ll.head + ptr_k = ll.head + # moving the ptr_end up by k nodes + for _ in range(k + 1): + if ptr_end is None: + raise ValueError(f"Linked list contains less than {k} nodes") + ptr_end = ptr_end.next + # searching for the end of the linked list + # ptr_k is trailing the ptr_end up by k nodes, when end pointer reaches the end, + # ptr_k is k nodes away from the end + while ptr_end is not None: + ptr_end = ptr_end.next + ptr_k = ptr_k.next + # removing the required element + temp = ptr_k.next + ptr_k.next = temp.next + temp.next = None + ll.length -= 1 + del temp + + +if __name__ == "__main__": + ll1 = LinkedList() + for i in range(1, 10): + ll1.add(i) + print(ll1) + delete_kth_last_node(ll1, 5) + print(ll1) + + ll2 = LinkedList() + for i in range(1, 4): + ll2.add(i) + print(ll2) + delete_kth_last_node(ll2, 3) + print(ll2) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/027.py b/Solutions/027.py new file mode 100644 index 0000000..7cdd81e --- /dev/null +++ b/Solutions/027.py @@ -0,0 +1,48 @@ +""" +Problem: + +Given a string of round, curly, and square open and closing brackets, return whether +the brackets are balanced (well-formed). + +For example, given the string "([])", you should return true. + +Given the string "([)]" or "((()", you should return false. +""" + +from typing import Dict + +from DataStructures.Stack import Stack + + +def is_parenthesis_balanced( + string: str, parenthesis_map: Dict[str, str] = {"{": "}", "[": "]", "(": ")"} +) -> bool: + open_parenthesis_set = set(parenthesis_map.keys()) + stack = Stack() + # iterating through the string and checking if its balanced + for char in string: + if char in open_parenthesis_set: + stack.push(char) + elif not stack.is_empty() and parenthesis_map[stack.peek()] == char: + stack.pop() + else: + return False + # the string is balanced only if the stack is empty (equal number of opening and + # closing parenthesis) + return stack.is_empty() + + +if __name__ == "__main__": + print(is_parenthesis_balanced("([])")) + print(is_parenthesis_balanced("((([{}])))")) + print(is_parenthesis_balanced("([])[]({})")) + print(is_parenthesis_balanced("([)]")) + print(is_parenthesis_balanced("((()")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/028.py b/Solutions/028.py new file mode 100644 index 0000000..b84ef8a --- /dev/null +++ b/Solutions/028.py @@ -0,0 +1,103 @@ +""" +Problem: + +Write an algorithm to justify text. Given a sequence of words and an integer line +length k, return a list of strings which represents each line, fully justified. + +More specifically, you should have as many words as possible in each line. There should +be at least one space between each word. Pad extra spaces when necessary so that each +line has exactly length k. Spaces should be distributed as equally as possible, with +the extra spaces, if any, distributed starting from the left. + +If you can only fit one word on a line, then you should pad the right-hand side with +spaces. + +Each word is guaranteed not to be longer than k. + +For example, given the list of words +["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you +should return the following: + +["the quick brown", # 1 extra space on the left "fox jumps over", # 2 extra spaces +distributed evenly "the lazy dog" # 4 extra spaces distributed evenly] +""" + +from typing import List + + +def add_word_handler( + result: List[str], temp: List[str], curr_string_length: int, k: int +) -> None: + # helper function to handle adding a new word to the result + extra_spaces = k - curr_string_length + words_in_current_line = len(temp) + if words_in_current_line == 1: + # only 1 word is present, extra padding is added to the right + word = temp.pop() + result.append(word + " " * extra_spaces) + elif extra_spaces % (words_in_current_line - 1) == 0: + # space can be equally distributed + full_string = (" " * (extra_spaces // (words_in_current_line - 1) + 1)).join( + temp + ) + result.append(full_string) + else: + # the space cannot be equally distributed + # extra spaces are added betweens the words, starting from the left + extra_uneven_spaces = extra_spaces % (words_in_current_line - 1) + regular = extra_spaces // (words_in_current_line - 1) + 1 + temp_str = "" + for i in temp: + temp_str += i + " " * regular + if extra_uneven_spaces: + temp_str += " " + extra_uneven_spaces -= 1 + result.append(temp_str.rstrip()) + + +def justify_text(word_list: List[str], k: int) -> List[str]: + result = [] + temp = [] + curr_string_length = 0 + # iterating through the given words + for word in word_list: + curr_word_length = len(word) + if temp == []: + # no word added to the current string + temp.append(word) + curr_string_length = curr_word_length + elif curr_word_length + curr_string_length + 1 <= k: + # adding the current word doesn't cause overflow + temp.append(word) + curr_string_length += curr_word_length + 1 + else: + # adding the current word does cause overflow + add_word_handler(result, temp, curr_string_length, k) + # updating temp and length (only in case of overflow) + temp = [word] + curr_string_length = len(word) + if temp != []: + # if the last line caused an overflow + add_word_handler(result, temp, curr_string_length, k) + return result + + +if __name__ == "__main__": + for string in justify_text( + ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"], 16 + ): + print("'" + string + "'") + + for string in justify_text(["done"], 16): + print("'" + string + "'") + + # NOTE: Using the "'"s is not important, used it to denote the start and end of the + # string (helpful in case of 1 word in 1 line) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/030.py b/Solutions/030.py new file mode 100644 index 0000000..2cb13d6 --- /dev/null +++ b/Solutions/030.py @@ -0,0 +1,58 @@ +""" +Problem: + +You are given an array of non-negative integers that represents a two-dimensional +elevation map where each element is unit-width wall and the integer is the height. +Suppose it will rain and all spots between two walls get filled up. + +Compute how many units of water remain trapped on the map in O(N) time and O(1) space. + +For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle. + +Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the +second, and 3 in the fourth index (we cannot hold 5 since it would run off to the +left), so we can trap 8 units of water. +""" + +from typing import List + + +def water(arr: List[int]) -> int: + length = len(arr) + # check if there is enough walls to store water + if length < 3: + return 0 + + left, right = 0, length - 1 + left_max, right_max = 0, 0 + total_water = 0 + # calculating the amount of water that can be stored (using 2 pointers method) + while left <= right: + if arr[left] < arr[right]: + if arr[left] > left_max: + left_max = arr[left] + else: + total_water += left_max - arr[left] + left += 1 + else: + if arr[right] > right_max: + right_max = arr[right] + else: + total_water += right_max - arr[right] + right -= 1 + return total_water + + +if __name__ == "__main__": + print(water([2, 1, 2])) + print(water([3, 0, 1, 3, 0, 5])) + print(water([5, 3, 5, 3, 4])) + print(water([5, 1, 1, 1, 0])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/031.py b/Solutions/031.py new file mode 100644 index 0000000..4ae7f35 --- /dev/null +++ b/Solutions/031.py @@ -0,0 +1,50 @@ +""" +Problem: + +The edit distance between two strings refers to the minimum number of character +insertions, deletions, and substitutions required to change one string to the other. +For example, the edit distance between "kitten" and "sitting" is three: substitute the +"k" for "s", substitute the "e" for "i", and append a "g". + +Given two strings, compute the edit distance between them. +""" + + +def get_string_distance(str1: str, str2: str) -> int: + n = len(str1) + m = len(str2) + dp = [[0 for x in range(m + 1)] for x in range(n + 1)] + # generating the look-up table in bottom up manner + for i in range(n + 1): + for j in range(m + 1): + # str1 empty (insert all characters of second string) + if i == 0: + dp[i][j] = j + # str2 empty (remove all characters of second string) + elif j == 0: + dp[i][j] = i + # last characters are same (ignore last char and recurse for remaining + # string) + elif str1[i - 1] == str2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + # last character are different (consider all possibilities and select the + # minimum) + else: + dp[i][j] = 1 + min( + dp[i][j - 1], # insertion + dp[i - 1][j], # deletion + dp[i - 1][j - 1], # replacement + ) + return dp[n][m] + + +if __name__ == "__main__": + print(get_string_distance("kitten", "sitting")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) +""" diff --git a/Solutions/032.py b/Solutions/032.py new file mode 100644 index 0000000..5c1dd3d --- /dev/null +++ b/Solutions/032.py @@ -0,0 +1,53 @@ +""" +Problem: + +Suppose you are given a table of currency exchange rates, represented as a 2D array. +Determine whether there is a possible arbitrage: that is, whether there is some +sequence of trades you can make, starting with some amount A of any currency, so that +you can end up with some amount greater than A of that currency. + +There are no transaction costs and you can trade fractional quantities. +""" + +# Solution copied from: +# https://github.com/vineetjohn/daily-coding-problem/blob/master/solutions/problem_032.py + +from math import log +from typing import Union + +number = Union[int, float] + + +def arbitrage(table: number) -> bool: + transformed_graph = [[-log(edge) for edge in row] for row in table] + # Pick any source vertex -- we can run Bellman-Ford from any vertex and + # get the right result + source = 0 + n = len(transformed_graph) + min_dist = [float("inf")] * n + min_dist[source] = 0 + # Relax edges |V - 1| times + for _ in range(n - 1): + for v in range(n): + for w in range(n): + if min_dist[w] > min_dist[v] + transformed_graph[v][w]: + min_dist[w] = min_dist[v] + transformed_graph[v][w] + # If we can still relax edges, then we have a negative cycle + for v in range(n): + for w in range(n): + if min_dist[w] > min_dist[v] + transformed_graph[v][w]: + return True + return False + + +if __name__ == "__main__": + print(arbitrage([[1, 2], [0.5, 1]])) + print(arbitrage([[1, 3, 4], [2, 1, 3], [5, 2, 1]])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 3) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/033.py b/Solutions/033.py new file mode 100644 index 0000000..970c189 --- /dev/null +++ b/Solutions/033.py @@ -0,0 +1,57 @@ +""" +Problem: + +Compute the running median of a sequence of numbers. That is, given a stream of +numbers, print out the median of the list so far on each new element. + +Recall that the median of an even-numbered list is the average of the two middle +numbers. + +For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out: + +2 +1.5 +2 +3.5 +2 +2 +2 +""" + +from typing import List + + +from DataStructures.Heap import MaxHeap, MinHeap + + +def get_running_medians(arr: List[int]) -> List[int]: + min_heap = MinHeap() + max_heap = MaxHeap() + medians = [] + for elem in arr: + # current median value generation + min_heap.insert(elem) + if len(min_heap) > len(max_heap) + 1: + smallest_large_element = min_heap.extract_min() + max_heap.insert(smallest_large_element) + if len(min_heap) == len(max_heap): + median = (min_heap.peek_min() + max_heap.peek_max()) / 2 + else: + median = min_heap.peek_min() + medians.append(median) + return medians + + +if __name__ == "__main__": + print(get_running_medians([])) + print(get_running_medians([2, 5])) + print(get_running_medians([3, 3, 3, 3])) + print(get_running_medians([2, 1, 5, 7, 2, 0, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/034.py b/Solutions/034.py new file mode 100644 index 0000000..aec3390 --- /dev/null +++ b/Solutions/034.py @@ -0,0 +1,47 @@ +""" +Problem: + +Given a string, find the palindrome that can be made by inserting the fewest number of +characters as possible anywhere in the word. If there is more than one palindrome of +minimum length that can be made, return the lexicographically earliest one (the first +one alphabetically). + +For example, given the string "race", you should return "ecarace", since we can add +three letters to it (which is the smallest amount to make a palindrome). There are +seven other palindromes that can be made from "race" by adding three letters, but +"ecarace" comes first alphabetically. + +As another example, given the string "google", you should return "elgoogle". +""" + + +def get_nearest_palindrome(string: str) -> str: + if string[::-1] == string: + return string + # generating the closest palindrome possible + length = len(string) + if string[0] == string[-1]: + return string[0] + get_nearest_palindrome(string[1 : length - 1]) + string[0] + # incase the 1st characters are different, strings using both the characters are + # generated + pal_1 = string[0] + get_nearest_palindrome(string[1:]) + string[0] + pal_2 = string[-1] + get_nearest_palindrome(string[: length - 1]) + string[-1] + # if one of the string is shorter, it is returned + if len(pal_1) != len(pal_2): + return min(pal_1, pal_2, key=lambda x: len(x)) + # if both strings have the same length, the lexicographically earliest one is + # returned + return min(pal_1, pal_2) + + +if __name__ == "__main__": + print(get_nearest_palindrome("race")) + print(get_nearest_palindrome("google")) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/035.py b/Solutions/035.py new file mode 100644 index 0000000..cba3030 --- /dev/null +++ b/Solutions/035.py @@ -0,0 +1,43 @@ +""" +Problem: + +Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of +the array so that all the Rs come first, the Gs come second, and the Bs come last. You +can only swap elements of the array. + +Do this in linear time and in-place. + +For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become +['R', 'R', 'R', 'G', 'G', 'B', 'B']. +""" + +from typing import List + + +def segregate(arr: List[str]) -> None: + length = len(arr) + pos = 0 + # pass for segregating "R"s + for i in range(length): + if arr[i] == "R": + arr[i], arr[pos] = arr[pos], arr[i] + pos += 1 + # pass for segregating "G"s + for i in range(pos, length): + if arr[i] == "G": + arr[i], arr[pos] = arr[pos], arr[i] + pos += 1 + + +if __name__ == "__main__": + arr = ["G", "B", "R", "R", "B", "R", "G"] + segregate(arr) + print(arr) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/036.py b/Solutions/036.py new file mode 100644 index 0000000..dd94121 --- /dev/null +++ b/Solutions/036.py @@ -0,0 +1,59 @@ +""" +Problem: + +Given the root to a binary search tree, find the second largest node in the tree. +""" + +from typing import Optional, Tuple + +from DataStructures.Tree import Node, BinarySearchTree + + +def get_largest_pair_from_current_node(node: Node) -> Tuple[Optional[Node], Node]: + parent = None + while node.right: + parent = node + node = node.right + # both the parent and the node is returned + return parent, node + + +def get_second_largest(tree: BinarySearchTree) -> Optional[int]: + if tree.root is None: + return None + + parent_of_largest, largest = get_largest_pair_from_current_node(tree.root) + # if the largest node has a left node, the largest child of the left node is the + # 2nd largest node (BST property) + if largest.left: + _, second_largest_node = get_largest_pair_from_current_node(largest.left) + return second_largest_node.val + # if the left node and the parent is absent (the tree contains only 1 node), + # None is returned + elif parent_of_largest is None: + return None + # if the largest parent is present its the 2nd largest node if no left node is + # present (BST property) + return parent_of_largest.val + + +if __name__ == "__main__": + tree = BinarySearchTree() + + tree.add(5) + tree.add(3) + tree.add(8) + tree.add(2) + tree.add(4) + tree.add(7) + tree.add(9) + + print(get_second_largest(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/037.py b/Solutions/037.py new file mode 100644 index 0000000..1cbf84f --- /dev/null +++ b/Solutions/037.py @@ -0,0 +1,40 @@ +""" +Problem: + +The power set of a set is the set of all its subsets. Write a function that, given a +set, generates its power set. + +For example, given the set {1, 2, 3}, it should return +{{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}. + +You may also use a list or array to represent a set. +""" + +from typing import List + + +def get_power_set(arr: List[int]) -> List[List[int]]: + power_set = [[]] + # generating the power set + for elem in arr: + # generating the new sets + additional_sets = [] + for subset in power_set: + subset_copy = [subset_elem for subset_elem in subset] + subset_copy.append(elem) + additional_sets.append(subset_copy) + # adding the new sets to the power set + power_set.extend(additional_sets) + return power_set + + +if __name__ == "__main__": + print(get_power_set([1, 2, 3])) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(2 ^ n) +""" diff --git a/Solutions/038.py b/Solutions/038.py new file mode 100644 index 0000000..0ff17c1 --- /dev/null +++ b/Solutions/038.py @@ -0,0 +1,50 @@ +""" +Problem: + +You have an N by N board. Write a function that, given N, returns the number of +possible arrangements of the board where N queens can be placed on the board without +threatening each other, i.e. no two queens share the same row, column, or diagonal. +""" + +from typing import List + + +def n_queens(n: int, queen_positions: List[int] = []) -> int: + # N Queen solution using backtracking + if n == len(queen_positions): + return 1 + + count = 0 + for col in range(n): + queen_positions.append(col) + if is_valid(queen_positions): + count += n_queens(n, queen_positions) + queen_positions.pop() + return count + + +def is_valid(queen_positions: List[int]) -> bool: + # check to see if any queen is threatening the current queen + current_queen_row, current_queen_col = len(queen_positions) - 1, queen_positions[-1] + for row, col in enumerate(queen_positions[:-1]): + diff = abs(current_queen_col - col) + if ( + diff == 0 # same row + or diff == current_queen_row - row # same diagonal + ): + return False + return True + + +if __name__ == "__main__": + print(n_queens(1)) + print(n_queens(4)) + print(n_queens(5)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/039.py b/Solutions/039.py new file mode 100644 index 0000000..4e6b38d --- /dev/null +++ b/Solutions/039.py @@ -0,0 +1,146 @@ +""" +Problem: + +Conway's Game of Life takes place on an infinite two-dimensional board of square cells. +Each cell is either dead or alive, and at each tick, the following rules apply: + +Any live cell with less than two live neighbours dies. Any live cell with two or three +live neighbours remains living. Any live cell with more than three live neighbours +dies. Any dead cell with exactly three live neighbours becomes a live cell. A cell +neighbours another cell if it is horizontally, vertically, or diagonally adjacent. + +Implement Conway's Game of Life. It should be able to be initialized with a starting +list of live cell coordinates and the number of steps it should run for. Once +initialized, it should print out the board state at each step. Since it's an infinite +board, print out only the relevant coordinates, i.e. from the top-leftmost live cell to +bottom-rightmost live cell. + +You can represent a live cell with an asterisk (*) and a dead cell with a dot (.). +""" + +from __future__ import annotations +from sys import maxsize +from typing import Any, List, Set + + +class Coordinate: + def __init__(self, x: int, y: int) -> None: + self.x = x + self.y = y + + def __eq__(self, other: Any) -> bool: + if type(other) != Coordinate: + return False + return self.x == other.x and self.y == other.y + + def __hash__(self) -> int: + return hash((self.x, self.y)) + + def __repr__(self) -> str: + return f"({self.x}, {self.y})" + + def get_neighbours(self) -> List[Coordinate]: + return [ + Coordinate(self.x - 1, self.y), + Coordinate(self.x - 1, self.y + 1), + Coordinate(self.x, self.y + 1), + Coordinate(self.x + 1, self.y + 1), + Coordinate(self.x + 1, self.y), + Coordinate(self.x + 1, self.y - 1), + Coordinate(self.x, self.y - 1), + Coordinate(self.x - 1, self.y - 1), + ] + + +def show_board(alive_cells: Set[Coordinate]) -> None: + x_max, x_min = -maxsize, maxsize + y_max, y_min = -maxsize, maxsize + # generating bounds + for cell in alive_cells: + x, y = cell.x, cell.y + x_min, x_max = min(x_min, x), max(x_max, x) + y_min, y_max = min(y_min, y), max(y_max, y) + # displaying the board + for x in range(x_min, x_max + 1): + for y in range(y_min, y_max + 1): + if Coordinate(x, y) in alive_cells: + print("*", end=" ") + else: + print(".", end=" ") + print() + print() + + +def play_game(board: List[Coordinate], n: int) -> None: + alive_cells = set(board) + print("Initail Board of Game of Life:") + show_board(alive_cells) + + for i in range(1, n + 1): + # alive cells cells cannot be modified inside the loop, using dead and alice + # lists to track changes + dead = [] + alive = [] + for cell in alive_cells: + alive_neighbours = 0 + neighbours = cell.get_neighbours() + for neighbour in neighbours: + # checking how many live neighbours the cell has + if neighbour in alive_cells: + alive_neighbours += 1 + # checking how many live neighbours the cell (neighbour) has + if neighbour not in alive_cells: + neighbours_of_neighbour = neighbour.get_neighbours() + alive_neighbours_of_neighbour = 0 + for neighbour_of_neighbour in neighbours_of_neighbour: + if neighbour_of_neighbour in alive_cells: + alive_neighbours_of_neighbour += 1 + if alive_neighbours_of_neighbour == 3: + alive.append(neighbour) + if alive_neighbours < 2 or alive_neighbours > 3: + dead.append(cell) + + # removing dead cells + for cell in dead: + alive_cells.remove(cell) + # adding new live cells + for cell in alive: + alive_cells.add(cell) + # displaying board + print(f"Iteration {i}:") + show_board(alive_cells) + + +if __name__ == "__main__": + board_0 = [Coordinate(0, 0), Coordinate(1, 0), Coordinate(1, 1), Coordinate(1, 5)] + play_game(board_0, 3) + + board_1 = [ + Coordinate(0, 0), + Coordinate(1, 0), + Coordinate(1, 1), + Coordinate(1, 5), + Coordinate(2, 5), + Coordinate(2, 6), + ] + play_game(board_1, 4) + + board_2 = [ + Coordinate(0, 0), + Coordinate(1, 0), + Coordinate(1, 1), + Coordinate(2, 5), + Coordinate(2, 6), + Coordinate(3, 9), + Coordinate(4, 8), + Coordinate(5, 10), + ] + play_game(board_2, 4) + + +""" +SPECS: + +TIME COMPLEXITY: O((alive cells ^ 2) x n) +SPACE COMPLEXITY: O(alive cells) +""" diff --git a/Solutions/040.py b/Solutions/040.py new file mode 100644 index 0000000..2783fb2 --- /dev/null +++ b/Solutions/040.py @@ -0,0 +1,54 @@ +""" +Problem: + +Given an array of integers where every integer occurs three times except for one +integer, which only occurs once, find and return the non-duplicated integer. + +For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19. + +Do this in O(N) time and O(1) space. +""" + +from typing import List + + +def get_unique(arr: List[int]) -> int: + # Sum the bits in same positions for all the numbers modulo with 3 provides the + # unique number's bit + unique_elem = 0 + mask = 1 + # iterate through all the bits (considering a 64 bit integer) + for _ in range(64): + sum_i_pos_bits = 0 + # calculating the sum of the bits in the current position + for elem in arr: + if elem & mask != 0: + sum_i_pos_bits = sum_i_pos_bits + 1 + # updating the unique element + if sum_i_pos_bits % 3 == 1: + unique_elem = unique_elem | mask + # updating mask + mask = mask << 1 + return unique_elem + + +if __name__ == "__main__": + arr = [3, 3, 2, 3] + print(get_unique(arr)) + + arr = [13, 19, 13, 13] + print(get_unique(arr)) + + arr = [6, 1, 3, 3, 3, 6, 6] + print(get_unique(arr)) + + arr = [12, 1, 3, 1, 1, 2, 3, 2, 2, 3] + print(get_unique(arr)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/041.py b/Solutions/041.py new file mode 100644 index 0000000..cea884a --- /dev/null +++ b/Solutions/041.py @@ -0,0 +1,65 @@ +""" +Problem: + +Given an unordered list of flights taken by someone, each represented as +(origin, destination) pairs, and a starting airport, compute the person's itinerary. If +no such itinerary exists, return null. If there are multiple possible itineraries, +return the lexicographically smallest one. All flights must be used in the itinerary. + +For example, given the list of flights +[('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')] and starting airport +'YUL', you should return the list ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD']. + +Given the list of flights [('SFO', 'COM'), ('COM', 'YYZ')] and starting airport 'COM', +you should return null. + +Given the list of flights [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')] and starting +airport 'A', you should return the list ['A', 'B', 'C', 'A', 'C'] even though +['A', 'C', 'A', 'B', 'C'] is also a valid itinerary. However, the first one is +lexicographically smaller. +""" + +from typing import List, Optional, Tuple + + +def get_itinerary( + flights: List[Tuple[str, str]], + current_position: str, + current_itinerary: List[str] = [], +) -> Optional[List[str]]: + if not flights and current_itinerary: + return current_itinerary + [current_position] + elif not flights: + return None + + resulatant_itinerary = None + # generating the itinerary + for index, (src, dest) in enumerate(flights): + # the is constructed using the current position (using DFS) + if current_position == src: + child_itinerary = get_itinerary( + flights[:index] + flights[index + 1 :], dest, current_itinerary + [src] + ) + if child_itinerary and ( + not resulatant_itinerary or child_itinerary < resulatant_itinerary + ): + resulatant_itinerary = child_itinerary + return resulatant_itinerary + + +if __name__ == "__main__": + print( + get_itinerary( + [("SFO", "HKO"), ("YYZ", "SFO"), ("YUL", "YYZ"), ("HKO", "ORD")], "YUL" + ) + ) + print(get_itinerary([("SFO", "COM"), ("COM", "YYZ")], "COM")) + print(get_itinerary([("A", "B"), ("A", "C"), ("B", "C"), ("C", "A")], "A")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 3) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/042.py b/Solutions/042.py new file mode 100644 index 0000000..cb536d1 --- /dev/null +++ b/Solutions/042.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a list of integers S and a target number k, write a function that returns a +subset of S that adds up to k. If such a subset cannot be made, then return null. + +Integers can appear more than once in the list. You may assume all numbers in the list +are positive. + +For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it +sums up to 24. +""" + +from typing import List, Optional + + +def target_sum(arr: List[int], k: int) -> Optional[List[int]]: + if not arr: + return None + elem = arr[0] + if elem == k: + return [elem] + # generating the subset + possible_subset = target_sum(arr[1:], k - elem) + if possible_subset is not None: + return [elem] + possible_subset + return target_sum(arr[1:], k) + + +if __name__ == "__main__": + print(target_sum([12, 1, 61, 5, 9, 2], 24)) + print(target_sum([12, 1, 61, 5, 9, 2], 61)) + print(target_sum([12, 1, 61, 5, -108, 2], -106)) + print(target_sum([12, 1, 61, 5, -108, 2], 1006)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 3) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/044.py b/Solutions/044.py new file mode 100644 index 0000000..b7f983a --- /dev/null +++ b/Solutions/044.py @@ -0,0 +1,74 @@ +""" +Problem: + +We can determine how "out of order" an array A is by counting the number of inversions +it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, +a smaller element appears after a larger element. + +Given an array, count the number of inversions it has. Do this faster than O(N^2) time. + +You may assume each element in the array is distinct. + +For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three +inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: +every distinct pair forms an inversion. +""" + +from typing import List, Tuple + + +def merge(part_a: List[int], part_b: List[int]) -> Tuple[List[int], int]: + # helper function for merge sort + i, j = 0, 0 + merged_array = [] + a, a_inv = part_a + b, b_inv = part_b + inversions = a_inv + b_inv + length_a, length_b = len(a), len(b) + # merging the arrays + while i < length_a and j < length_b: + if a[i] < b[j]: + merged_array.append(a[i]) + i += 1 + else: + merged_array.append(b[j]) + inversions += length_a - i + j += 1 + while i < length_a: + merged_array.append(a[i]) + i += 1 + while j < length_b: + merged_array.append(b[j]) + j += 1 + return merged_array, inversions + + +def merge_sort(arr: List[int]) -> Tuple[List[int], int]: + length = len(arr) + if length in (0, 1): + return arr, 0 + + mid = length // 2 + merged_array, inversions = merge(merge_sort(arr[:mid]), merge_sort(arr[mid:])) + return merged_array, inversions + + +def count_inversions(arr: List[int]) -> int: + _, inversions = merge_sort(arr) + return inversions + + +if __name__ == "__main__": + print(count_inversions([1, 2, 3, 4, 5])) + print(count_inversions([2, 1, 3, 4, 5])) + print(count_inversions([2, 4, 1, 3, 5])) + print(count_inversions([2, 6, 1, 3, 7])) + print(count_inversions([5, 4, 3, 2, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/045.py b/Solutions/045.py new file mode 100644 index 0000000..0c8daf2 --- /dev/null +++ b/Solutions/045.py @@ -0,0 +1,45 @@ +""" +Problem: + +Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform +probability, implement a function rand7() that returns an integer from 1 to 7 +(inclusive). +""" + +from random import randint +import matplotlib.pyplot as plt + +# rand5 implementation +def rand5() -> int: + return randint(1, 5) + + +def rand7() -> int: + # generating 2 numbers between 1 and 5 + temp1 = rand5() + temp2 = rand5() + # generating a number temp between 1 and 25 + temp = 5 * temp1 + temp2 - 5 + # if the number is NOT in the range[1, 21], rand7 is called again + # mod 7 over 1 to 21, yield all numbers from 0 to 6 with EQUAL probability + if temp <= 21: + return (temp % 7) + 1 + return rand7() + + +if __name__ == "__main__": + results = [] + # executing rand7 100,000 times (for plotting on a graph) + for _ in range(100_000): + results.append(rand7()) + # plotting the distribution + plt.hist(results, 7, edgecolor="black") + plt.show() + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/047.py b/Solutions/047.py new file mode 100644 index 0000000..de587c1 --- /dev/null +++ b/Solutions/047.py @@ -0,0 +1,41 @@ +""" +Problem: + +Given a array of numbers representing the stock prices of a company in chronological +order, write a function that calculates the maximum profit you could have made from +buying and selling that stock once. You must buy before you can sell it. + +For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the +stock at 5 dollars and sell it at 10 dollars. +""" + +from typing import List, Optional + + +def get_max_profit(arr: List[int]) -> Optional[int]: + length = len(arr) + if length < 2: + return None + + min_element = arr[0] + profit = max(0, arr[1] - arr[0]) + # generating the maximum profit + for i in range(1, length): + min_element = min(min_element, arr[i]) + profit = max(profit, arr[i] - min_element) + return profit + + +if __name__ == "__main__": + print(get_max_profit([9, 11, 8, 5, 7, 10])) + print(get_max_profit([1, 2, 3, 4, 5])) + print(get_max_profit([5, 4, 3, 2, 1])) + print(get_max_profit([1000])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/048.py b/Solutions/048.py new file mode 100644 index 0000000..5e4fb7c --- /dev/null +++ b/Solutions/048.py @@ -0,0 +1,68 @@ +""" +Problem: + +Given pre-order and in-order traversals of a binary tree, write a function to reconstruct the tree. + +For example, given the following preorder traversal: + +[a, b, d, e, c, f, g] +And the following inorder traversal: + +[d, b, e, a, f, c, g] +You should return the following tree: + + a + / \ + b c + / \ / \ +d e f g +""" + +from typing import List + +from DataStructures.Tree import BinaryTree, Node + + +def generate_tree(preorder: List[int], inorder: List[int]) -> BinaryTree: + length = len(preorder) + if length != len(inorder): + raise RuntimeError + if length == 0: + return BinaryTree() + # generating the root + root = preorder[0] + tree = BinaryTree() + tree.root = Node(root) + # generating the rest of the tree + if length > 1: + i = inorder.index(root) + # partitioning the nodes as per the branch + inorder_left, preorder_left = (inorder[:i], preorder[1 : i + 1]) + inorder_right, preorder_right = (inorder[i + 1 :], preorder[i + 1 :]) + # creating a tree for each branch + tree_left = generate_tree(preorder_left, inorder_left) + tree_right = generate_tree(preorder_right, inorder_right) + # attaching the sub-tree to their respective branch + tree.root.left = tree_left.root + tree.root.right = tree_right.root + return tree + + +if __name__ == "__main__": + test1 = generate_tree( + ["a", "b", "d", "e", "c", "f", "g"], ["d", "b", "e", "a", "f", "c", "g"] + ) + print(test1) + + test2 = generate_tree( + ["a", "b", "d", "e", "c", "f"], ["d", "b", "e", "a", "f", "c"] + ) + print(test2) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/050.py b/Solutions/050.py new file mode 100644 index 0000000..2464d1d --- /dev/null +++ b/Solutions/050.py @@ -0,0 +1,84 @@ +""" +Problem: + +Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and +each internal node is one of '+', '−', '∗', or '/'. + +Given the root to such a tree, write a function to evaluate it. + +For example, given the following tree: + + * + / \ + + + + / \ / \ +3 2 4 5 +You should return 45, as it is (3 + 2) * (4 + 5). +""" + +from __future__ import annotations +from typing import Callable, Optional, Union + +from DataStructures.Tree import BinaryTree, Node + + +# symbol to function map +OPERATIONS_DICT = { + "+": lambda num1, num2: num1 + num2, + "-": lambda num1, num2: num1 - num2, + "*": lambda num1, num2: num1 * num2, + "/": lambda num1, num2: num1 / num2, +} + + +class ExpressionTreeNode(Node): + def __init__( + self, + val: Union[int, float, str, Callable], + left: Optional[ExpressionTreeNode] = None, + right: Optional[ExpressionTreeNode] = None, + ) -> None: + Node.__init__(self, val, left, right) + + def transform_helper(self) -> None: + if self.val in OPERATIONS_DICT: + self.val = OPERATIONS_DICT[self.val] + self.left.transform_helper() + self.right.transform_helper() + + def calculate_helper(self) -> Union[int, float]: + if callable(self.val): + return self.val(self.left.calculate_helper(), self.right.calculate_helper()) + return self.val + + +def calculate_expression_tree(tree: BinaryTree) -> Union[int, float]: + root = tree.root + if root: + root.transform_helper() + return root.calculate_helper() + return None + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = ExpressionTreeNode("*") + tree.root.left = ExpressionTreeNode("+") + tree.root.right = ExpressionTreeNode("+") + + tree.root.left.left = ExpressionTreeNode(3) + tree.root.left.right = ExpressionTreeNode(2) + + tree.root.right.left = ExpressionTreeNode(4) + tree.root.right.right = ExpressionTreeNode(5) + + print(calculate_expression_tree(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/051.py b/Solutions/051.py new file mode 100644 index 0000000..5d91dba --- /dev/null +++ b/Solutions/051.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a function that generates perfectly random numbers between 1 and k (inclusive), +where k is an input, write a function that shuffles a deck of cards represented as an +array using only swaps. + +It should run in O(N) time. + +Hint: Make sure each one of the 52! permutations of the deck is equally likely. +""" + +from random import randint +from typing import List + +# implementation of a function that generates perfectly random numbers between 1 and k +def generate_random_number_in_range(k: int) -> int: + return randint(1, k) + + +def swap() -> List[int]: + # generating the card list + cards = [card_no for card_no in range(1, 53)] + # shuffling the cards + for i in range(52): + swap_position = generate_random_number_in_range(52) - 1 + cards[i], cards[swap_position] = cards[swap_position], cards[i] + return cards + + +if __name__ == "__main__": + print(*swap()) + print(*swap()) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +[n = 52 (constant)] +""" diff --git a/Solutions/052.py b/Solutions/052.py new file mode 100644 index 0000000..6223a8c --- /dev/null +++ b/Solutions/052.py @@ -0,0 +1,106 @@ +""" +Problem: + +Implement an LRU (Least Recently Used) cache. It should be able to be initialized with +a cache size n, and contain the following methods: + +set(key, value): sets key to value. If there are already n items in the cache and we +are adding a new item, then it should also remove the least recently used item. +get(key): gets the value at key. If no such key exists, return null. Each operation +should run in O(1) time. +""" + +from __future__ import annotations +from typing import Optional + + +class DoubleLinkedListNode: + def __init__(self, key: int, val: int) -> None: + self.key = key + self.val = val + self.next = None + self.prev = None + + +class DoubleLinkedList: + def __init__(self) -> None: + self.head = DoubleLinkedListNode(None, None) + self.rear = DoubleLinkedListNode(None, None) + self.head.next, self.rear.prev = self.rear, self.head + + def add_node(self, node: DoubleLinkedListNode) -> None: + temp = self.rear.prev + temp.next, node.prev = node, temp + self.rear.prev, node.next = node, self.rear + + def remove_node(self, node: DoubleLinkedListNode) -> DoubleLinkedListNode: + temp_last, temp_next = node.prev, node.next + node.prev, node.next = None, None + temp_last.next, temp_next.prev = temp_next, temp_last + return node + + +class LRUCache: + def __init__(self, capacity: int) -> None: + self.list = DoubleLinkedList() + self.capacity = capacity + self.num_keys = 0 + self.hits = 0 + self.miss = 0 + self.cache = {} + + def __repr__(self) -> str: + return ( + f"CacheInfo(hits={self.hits}, misses={self.miss}, " + f"capacity={self.capacity}, current size={self.num_keys})" + ) + + def get(self, key: int) -> Optional[int]: + if key in self.cache: + self.hits += 1 + # placing the node at the proper position in the linked list in case of + # cache hit + self.list.add_node(self.list.remove_node(self.cache[key])) + return self.cache[key].val + self.miss += 1 + return None + + def set(self, key: int, value: int) -> None: + if key not in self.cache: + if self.num_keys >= self.capacity: + # replacement algorithm in case the cache is full + key_to_delete = self.list.head.next.key + self.list.remove_node(self.cache[key_to_delete]) + del self.cache[key_to_delete] + self.num_keys -= 1 + self.cache[key] = DoubleLinkedListNode(key, value) + self.list.add_node(self.cache[key]) + self.num_keys += 1 + return + # if the key is already present, its value is updated + node = self.list.remove_node(self.cache[key]) + node.val = value + self.list.add_node(node) + + +if __name__ == "__main__": + cache = LRUCache(3) + + print(cache.get("a")) + + cache.set("a", 1) + cache.set("b", 2) + cache.set("c", 3) + + print(cache.get("a")) + + cache.set("d", 4) + cache.set("e", 5) + + print(cache.get("a")) + print(cache.get("b")) + print(cache.get("c")) + print(cache.get("d")) + print(cache.get("e")) + + print(cache) diff --git a/Solutions/053.py b/Solutions/053.py new file mode 100644 index 0000000..b5dc434 --- /dev/null +++ b/Solutions/053.py @@ -0,0 +1,65 @@ +""" +Problem: + +Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) +data structure with the following methods: enqueue, which inserts an element into the +queue, and dequeue, which removes it. +""" + +from DataStructures.Stack import Stack + + +class Queue: + def __init__(self) -> None: + self.stack1 = Stack() + self.stack2 = Stack() + + def __str__(self) -> str: + return str(self.stack2[::-1] + self.stack1[::]) + + def enqueue(self, val: int) -> None: + self._transfer_to_stack1() + self.stack1.push(val) + + def dequeue(self) -> int: + self._transfer_to_stack2() + if len(self.stack2) == 0: + raise RuntimeError("Cannot dequeue from a empty queue") + return self.stack2.pop() + + def _transfer_to_stack2(self) -> None: + # helper function to transfer all items to the stack 1 from stack 2 + while not self.stack1.is_empty(): + self.stack2.push(self.stack1.pop()) + + def _transfer_to_stack1(self) -> None: + # helper function to transfer all items to the stack 2 from stack 1 + while not self.stack2.is_empty(): + self.stack1.push(self.stack1.pop()) + + +if __name__ == "__main__": + queue = Queue() + + print(queue) + + queue.enqueue(1) + queue.enqueue(5) + queue.enqueue(9) + queue.enqueue(3) + queue.enqueue(4) + queue.enqueue(0) + + print(queue) + + print(queue.dequeue()) + print(queue.dequeue()) + + print(queue) + + print(queue.dequeue()) + print(queue.dequeue()) + print(queue.dequeue()) + print(queue.dequeue()) + + print(queue) diff --git a/Solutions/054.py b/Solutions/054.py new file mode 100644 index 0000000..87e7609 --- /dev/null +++ b/Solutions/054.py @@ -0,0 +1,102 @@ +""" +Problem: + +Sudoku is a puzzle where you're given a partially-filled 9 by 9 grid with digits. The +objective is to fill the grid with the constraint that every row, column, and box +(3 by 3 subgrid) must contain all of the digits from 1 to 9. + +Implement an efficient sudoku solver. +""" + +from typing import List, Optional, Tuple + +Board = List[List[int]] +Position = Tuple[int, int] + + +def print_board(board: Board) -> None: + for i in range(len(board)): + if i % 3 == 0 and i != 0: + print("- - - - - - - - - - - -") + for j in range(len(board[0])): + if j % 3 == 0 and j != 0: + print(" | ", end="") + if board[i][j] != 0: + print(board[i][j], end=" ") + else: + print(".", end=" ") + print() + + +def find_empty_position(board: Board) -> Optional[Position]: + for i in range(len(board)): + for j in range(len(board[0])): + if board[i][j] == 0: + return (i, j) + return None + + +def check_conflict(board: Board, position: Position, num: int) -> bool: + y, x = position + # row check + for i in range(len(board[0])): + if board[y][i] == num: + return False + # column check + for i in range(len(board)): + if board[i][x] == num: + return False + # sub-section check + sec_row = y // 3 + sec_col = x // 3 + for i in range((sec_row * 3), (sec_row * 3) + 3): + for j in range((sec_col * 3), (sec_col * 3) + 3): + if board[i][j] == num: + return False + return True + + +def sudoku_solver(board: Board) -> bool: + position = find_empty_position(board) + if not position: + return True + y, x = position + # solving the board using backtracking + for num in range(1, 10): + if check_conflict(board, position, num): + board[y][x] = num + if sudoku_solver(board): + return True + board[y][x] = 0 + return False + + +if __name__ == "__main__": + board = [ + [7, 8, 0, 4, 0, 0, 1, 2, 0], + [6, 0, 0, 0, 7, 5, 0, 0, 9], + [0, 0, 0, 6, 0, 1, 0, 7, 8], + [0, 0, 7, 0, 4, 0, 2, 6, 0], + [0, 0, 1, 0, 5, 0, 9, 3, 0], + [9, 0, 4, 0, 6, 0, 0, 0, 5], + [0, 7, 0, 3, 0, 0, 0, 1, 2], + [1, 2, 0, 0, 0, 7, 4, 0, 0], + [0, 4, 9, 2, 0, 6, 0, 0, 7], + ] + + print("Initial Board:") + print_board(board) + + sudoku_solver(board) + + print("\nFinal Board:") + print_board(board) + + +""" +SPECS: + +TIME COMPLEXITY: O(m ^ (n ^ 2)) +SPACE COMPLEXITY: O(m) [in the call stack] +[m = number of unfilled positions, n = dimension of the board] +""" diff --git a/Solutions/055.py b/Solutions/055.py new file mode 100644 index 0000000..03734e3 --- /dev/null +++ b/Solutions/055.py @@ -0,0 +1,42 @@ +""" +Problem: + +Implement a URL shortener with the following methods: + +shorten(url), which shortens the url into a six-character alphanumeric string, such as +zLg6wl. +restore(short), which expands the shortened string into the original url. If no such +shortened string exists, return null. +Hint: What if we enter the same URL twice? +""" + +from hashlib import sha224 +from typing import Optional + + +class URL_Shortner: + def __init__(self, prefix: str = "http://short_url.in/") -> None: + self.shortened_url_map = {} + self.url_prefix = prefix + + def shorten(self, url: str) -> str: + shortened_url_hash = sha224(url.encode()).hexdigest()[:6] + if shortened_url_hash not in self.shortened_url_map: + self.shortened_url_map[shortened_url_hash] = url + return self.url_prefix + shortened_url_hash + + def restore(self, short: str) -> Optional[str]: + if short[-6:] in self.shortened_url_map: + return self.shortened_url_map[short[-6:]] + return None + + +if __name__ == "__main__": + us = URL_Shortner() + + url = "https://www.google.com/" + shortened_url = us.shorten(url) + print(shortened_url) + + print(us.restore(shortened_url)) + print(us.restore("http://short_url.in/64f827")) diff --git a/Solutions/056.py b/Solutions/056.py new file mode 100644 index 0000000..86223e7 --- /dev/null +++ b/Solutions/056.py @@ -0,0 +1,41 @@ +""" +Problem: + +Given an undirected graph represented as an adjacency matrix and an integer k, write a +function to determine whether each vertex in the graph can be colored such that no two +adjacent vertices share the same color using at most k colors. +""" + +from typing import List + + +def can_color(adjacency_matrix: List[List[int]], k: int) -> bool: + minimum_colors_required = 0 + vertices = len(adjacency_matrix) + # generating the minimum number of colors required to color the graph + for vertex in range(vertices): + colors_required_for_current_vertex = sum(adjacency_matrix[vertex]) + 1 + minimum_colors_required = max( + minimum_colors_required, colors_required_for_current_vertex + ) + return minimum_colors_required <= k + + +if __name__ == "__main__": + adjacency_matrix = [ + [0, 1, 1, 1], + [1, 0, 1, 1], + [1, 1, 0, 1], + [1, 1, 1, 0], + ] + + print(can_color(adjacency_matrix, 4)) + print(can_color(adjacency_matrix, 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/059.py b/Solutions/059.py new file mode 100644 index 0000000..ec4e1e9 --- /dev/null +++ b/Solutions/059.py @@ -0,0 +1,144 @@ +""" +Problem: + +Implement a file syncing algorithm for two computers over a low-bandwidth network. +What if we know the files in the two computers are mostly the same? +""" + +from __future__ import annotations +from hashlib import sha256 + +hash_func = sha256 + + +class MerkleNode: + def __init__(self, name: str) -> None: + self.parent = None + self.node_hash = None + self.name = name + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, other: MerkleNode) -> bool: + if type(other) != MerkleNode: + return False + return self.node_hash == other.node_hash + + +class MerkleDirectory(MerkleNode): + def __init__(self, name: str) -> None: + MerkleNode.__init__(self, name) + self.children = set() + self.is_dir = True + # creating a file on directory initialize and calculating hash + new_file = MerkleFile("dir_init") + new_file.add_to_directory(self) + + def __repr__(self) -> str: + return f"Name: {self.name}, Children: {self.children}, Hash: {self.node_hash}" + + def add_to_directory(self, directory: MerkleDirectory) -> None: + # adding the node + self.parent = directory + directory.children.add(self) + # recalculating hash for all anscestors + while directory is not None: + directory.recalculate_hash() + directory = directory.parent + + def recalculate_hash(self) -> None: + # concatinating all hashes and recalculating on the cumulative hash + cumulative_hash = "" + for child in self.children: + cumulative_hash += child.node_hash + self.node_hash = hash_func(cumulative_hash.encode()).hexdigest() + + def synchronize(self, other: MerkleDirectory) -> None: + # if the directories have the same hash, they are already synchronized + if self.node_hash == other.node_hash: + return + # updating other using self + for node in self.children: + if not node in other.children: + type(node)(node.add_to_directory(other)) + # updating self using other + for node in other.children: + if not node in self.children: + type(node)(node.add_to_directory(self)) + + +class MerkleFile(MerkleNode): + def __init__(self, name: str) -> None: + MerkleNode.__init__(self, name) + self.node_contents = "" + self.is_dir = False + self.node_hash = hash_func(self.node_contents.encode()).hexdigest() + + def __repr__(self) -> str: + return ( + f"[ Name: {self.name}, Content: " + + f"{self.node_contents if self.node_contents else 'null'}, " + + f"Hash: {self.node_hash} ]" + ) + + def add_to_directory(self, directory: MerkleDirectory) -> None: + # adding the node + self.parent = directory + directory.children.add(self) + # recalculating hash for all anscestors + while directory is not None: + directory.recalculate_hash() + directory = directory.parent + + def update_contents(self, new_contents: str) -> None: + # contents updated and hash recaculated + self.node_hash = hash_func(new_contents.encode()).hexdigest() + self.node_contents = new_contents + if self.parent: + self.parent.recalculate_hash() + + +class Computer: + def __init__(self): + self.root = MerkleDirectory("root") + + def __repr__(self) -> str: + return str(self.root) + + def synchronize(self, new_comp: Computer) -> None: + print("Syncing computers...") + self.root.synchronize(new_comp.root) + print("Sync successful!\n") + + +if __name__ == "__main__": + c1 = Computer() + c2 = Computer() + + print("COMPUTER 1:") + print(c1) + print("COMPUTER 2:") + print(c2) + print() + + new_file = MerkleFile("check_file") + new_file.update_contents("Check") + new_file.add_to_directory(c1.root) + + new_dir = MerkleDirectory("check_dir") + new_dir.add_to_directory(c2.root) + + print("COMPUTER 1:") + print(c1) + print("COMPUTER 2:") + print(c2) + print() + + c1.synchronize(c2) + + print("COMPUTER 1:") + print(c1) + print("COMPUTER 2:") + print(c2) + print() diff --git a/Solutions/060.py b/Solutions/060.py new file mode 100644 index 0000000..f9cd52e --- /dev/null +++ b/Solutions/060.py @@ -0,0 +1,52 @@ +""" +Problem: + +Given a multiset of integers, return whether it can be partitioned into two subsets +whose sums are the same. + +For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, +since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55. + +Given the multiset {15, 5, 20, 10, 35}, it would return false, since we can't split it +up into two subsets that add up to the same sum. +""" + +from typing import List + + +def equal_sum_split_check_helper( + arr: List[int], start: int, stop: int, sum_inner: int, sum_outer: int +) -> bool: + if start >= stop: + return False + elif sum_inner == sum_outer: + return True + # checking for all possible splits + return equal_sum_split_check_helper( + arr, start + 1, stop, sum_inner - arr[start], sum_outer + arr[start] + ) or equal_sum_split_check_helper( + arr, start, stop - 1, sum_inner - arr[stop], sum_outer + arr[stop] + ) + + +def equal_sum_split_check(arr: List[int]) -> bool: + # cases where the array cannot be split + total_sum = sum(arr) + if not arr or total_sum % 2 == 1: + return False + # sorting the array (pre-requisite for split_helper) + arr.sort() + return equal_sum_split_check_helper(arr, 0, len(arr) - 1, total_sum, 0) + + +if __name__ == "__main__": + print(equal_sum_split_check([15, 5, 20, 10, 35, 15, 10])) + print(equal_sum_split_check([15, 5, 20, 10, 35])) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) [recursion depth] +""" diff --git a/Solutions/061.py b/Solutions/061.py new file mode 100644 index 0000000..d8ce040 --- /dev/null +++ b/Solutions/061.py @@ -0,0 +1,32 @@ +""" +Problem: + +Implement integer exponentiation. That is, implement the pow(x, y) function, where x +and y are integers and returns x^y. + +Do this faster than the naive method of repeated multiplication. + +For example, pow(2, 10) should return 1024. +""" + + +def pow(base: int, power: int) -> int: + if power == 0: + return 1 + + if power % 2 != 0: + return pow((base * base), power // 2) * base + return pow((base * base), power // 2) + + +if __name__ == "__main__": + print(pow(2, 10)) + print(pow(3, 4)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) [recursion depth] +""" diff --git a/Solutions/062.py b/Solutions/062.py new file mode 100644 index 0000000..7ecd7fd --- /dev/null +++ b/Solutions/062.py @@ -0,0 +1,36 @@ +""" +Problem: + +There is an N by M matrix of zeroes. Given N and M, write a function to count the +number of ways of starting at the top-left corner and getting to the bottom-right +corner. You can only move right or down. + +For example, given a 2 by 2 matrix, you should return 2, since there are two ways to +get to the bottom-right: + +Right, then down +Down, then right +Given a 5 by 5 matrix, there are 70 ways to get to the bottom-right. +""" + + +def get_num_ways(n: int, m: int) -> int: + matrix = [[(1 if (i == 0 or j == 0) else 0) for i in range(m)] for j in range(n)] + + for i in range(1, n): + for j in range(1, m): + matrix[i][j] = matrix[i - 1][j] + matrix[i][j - 1] + return matrix[n - 1][m - 1] + + +if __name__ == "__main__": + print(get_num_ways(2, 2)) + print(get_num_ways(5, 5)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) +""" diff --git a/Solutions/063.py b/Solutions/063.py new file mode 100644 index 0000000..3a31847 --- /dev/null +++ b/Solutions/063.py @@ -0,0 +1,57 @@ +""" +Problem: + +Given a 2D matrix of characters and a target word, write a function that returns +whether the word can be found in the matrix by going left-to-right, or up-to-down. + +For example, given the following matrix: + +[['F', 'A', 'C', 'I'], + ['O', 'B', 'Q', 'P'], + ['A', 'N', 'O', 'B'], + ['M', 'A', 'S', 'S']] +and the target word 'FOAM', you should return true, since it's the leftmost column. +Similarly, given the target word 'MASS', you should return true, since it's the last +row. +""" + +from typing import List + + +def check_word_occorance(matrix: List[List[str]], word: str) -> bool: + n = len(matrix) + m = len(matrix[0]) + # check for word occourance in the rows + for i in range(n): + row_string = "".join(matrix[i]) + if word in row_string: + return True + # check for word occourance in the columns + for j in range(m): + column_string = "" + for i in range(n): + column_string += matrix[i][j] + if word in column_string: + return True + return False + + +if __name__ == "__main__": + matrix = [ + ["F", "A", "C", "I"], + ["O", "B", "Q", "P"], + ["A", "N", "O", "B"], + ["M", "A", "S", "S"], + ] + + print(check_word_occorance(matrix, "FOAM")) + print(check_word_occorance(matrix, "MASS")) + print(check_word_occorance(matrix, "FORM")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n + m) +""" diff --git a/Solutions/064.py b/Solutions/064.py new file mode 100644 index 0000000..9021d5f --- /dev/null +++ b/Solutions/064.py @@ -0,0 +1,77 @@ +""" +Problem: + +A knight's tour is a sequence of moves by a knight on a chessboard such that all +squares are visited once. + +Given N, write a function to return the number of knight's tours on an N by N +chessboard. +""" + +from typing import List, Tuple + +Board = List[List[int]] + + +def get_valid_moves(position: Tuple[int, int], n: int) -> Tuple[int, int]: + y, x = position + positions = [ + (y + 1, x + 2), + (y - 1, x + 2), + (y + 1, x - 2), + (y - 1, x - 2), + (y + 2, x + 1), + (y + 2, x - 1), + (y - 2, x + 1), + (y - 2, x - 1), + ] + valid_moves = [ + (y_test, x_test) + for (y_test, x_test) in positions + if 0 <= y_test < n and 0 <= x_test < n + ] + return valid_moves + + +def is_board_complete(board: Board) -> bool: + for row in board: + for elem in row: + if elem == 0: + return False + return True + + +def solver_helper(board: Board, position: Tuple[int, int], count: int) -> int: + if is_board_complete(board): + count += 1 + return count + for move in get_valid_moves(position, len(board)): + y, x = move + if board[y][x] == 0: + board[y][x] = 1 + count += solver_helper(board, move, 0) + board[y][x] = 0 + return count + + +def solve(n: int) -> int: + board = [[0 for i in range(n)] for j in range(n)] + board[0][0] = 1 + count = solver_helper(board, (0, 0), 0) + return count + + +if __name__ == "__main__": + print(solve(1)) + print(solve(2)) + print(solve(3)) + print(solve(4)) + print(solve(5)) + + +""" +SPECS: + +TIME COMPLEXITY: O(8 ^ (n ^ 2)) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/066.py b/Solutions/066.py new file mode 100644 index 0000000..e6d8fbb --- /dev/null +++ b/Solutions/066.py @@ -0,0 +1,55 @@ +""" +Problem: + +Assume you have access to a function toss_biased() which returns 0 or 1 with a +probability that's not 50-50 (but also not 0-100 or 100-0). You do not know the bias of +the coin. + +Write a function to simulate an unbiased coin toss. +""" + +from random import random +import matplotlib.pyplot as plt + + +def toss_biased(): + # toss with 30-70 bias + value = random() + if value < 0.3: + return 0 + return 1 + + +def toss_unbiased(): + # getting the biased toss value twice + toss1 = toss_biased() + toss2 = toss_biased() + # as long as we dont get different values, we keep tossing + while toss1 == toss2: + toss1 = toss_biased() + toss2 = toss_biased() + return toss1 + + +if __name__ == "__main__": + biased = [toss_biased() for i in range(100_000)] + unbiased = [toss_unbiased() for i in range(100_000)] + + # displaying biased distribution + plt.title("Biased Distribution") + plt.hist(biased, bins=2, edgecolor="black") + plt.show() + + # displaying unbiased distribution + plt.title("Unbiased Distribution") + plt.hist(unbiased, bins=2, edgecolor="black") + plt.show() + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +[for toss_unbiased function] +""" diff --git a/Solutions/067.py b/Solutions/067.py new file mode 100644 index 0000000..4b14513 --- /dev/null +++ b/Solutions/067.py @@ -0,0 +1,114 @@ +""" +Problem: + +Implement an LFU (Least Frequently Used) cache. It should be able to be initialized +with a cache size n, and contain the following methods: + +set(key, value): sets key to value. If there are already n items in the cache and we +are adding a new item, then it should also remove the least frequently used item. If +there is a tie, then the least recently used key should be removed. +get(key): gets the value at key. If no such key exists, return null. +Each operation should run in O(1) time. +""" + +from typing import Callable, Optional + + +class DoubleLinkedListNode: + def __init__(self, key: int, val: int) -> None: + self.key = key + self.val = val + self.freq = 0 + self.next = None + self.prev = None + + +class DoubleLinkedList: + def __init__(self) -> None: + self.head = DoubleLinkedListNode(None, None) + self.rear = DoubleLinkedListNode(None, None) + self.head.next, self.rear.prev = self.rear, self.head + + def add(self, node: DoubleLinkedListNode) -> None: + temp = self.rear.prev + self.rear.prev, node.next = node, self.rear + temp.next, node.prev = node, temp + node.freq += 1 + self._position_node(node) + + def remove(self, node: DoubleLinkedListNode) -> DoubleLinkedListNode: + temp_last, temp_next = node.prev, node.next + node.prev, node.next = None, None + temp_last.next, temp_next.prev = temp_next, temp_last + return node + + def _position_node(self, node: DoubleLinkedListNode) -> None: + while node.prev.key and node.prev.freq > node.freq: + node1, node2 = node, node.prev + node1.prev, node2.next = node2.prev, node1.prev + node1.next, node2.prev = node2, node1 + + +class LFUCache: + def __init__(self, capacity: int) -> None: + self.list = DoubleLinkedList() + self.capacity = capacity + self.num_keys = 0 + self.hits = 0 + self.miss = 0 + self.cache = {} + + def __repr__(self) -> str: + return ( + f"CacheInfo(hits={self.hits}, misses={self.miss}, " + f"capacity={self.capacity}, current_size={self.num_keys})" + ) + + def __contains__(self, key: int) -> bool: + return key in self.cache + + def get(self, key: int) -> Optional[int]: + if key in self.cache: + self.hits += 1 + self.list.add(self.list.remove(self.cache[key])) + return self.cache[key].val + self.miss += 1 + return None + + def set(self, key: int, value: int) -> None: + if key not in self.cache: + if self.num_keys >= self.capacity: + key_to_delete = self.list.head.next.key + self.list.remove(self.cache[key_to_delete]) + del self.cache[key_to_delete] + self.num_keys -= 1 + self.cache[key] = DoubleLinkedListNode(key, value) + self.list.add(self.cache[key]) + self.num_keys += 1 + else: + node = self.list.remove(self.cache[key]) + node.val = value + self.list.add(node) + + +if __name__ == "__main__": + cache = LFUCache(3) + + print(cache.get("a")) + + cache.set("a", 1) + cache.set("b", 2) + cache.set("c", 3) + + print(cache.get("a")) + + cache.set("d", 4) + cache.set("e", 5) + + print(cache.get("a")) + print(cache.get("b")) + print(cache.get("c")) + print(cache.get("d")) + print(cache.get("e")) + + print(cache) diff --git a/Solutions/068.py b/Solutions/068.py new file mode 100644 index 0000000..165dd3f --- /dev/null +++ b/Solutions/068.py @@ -0,0 +1,72 @@ +""" +Problem: + +On our special chessboard, two bishops attack each other if they share the same +diagonal. This includes bishops that have another bishop located between them, i.e. +bishops can attack through pieces. + +You are given N bishops, represented as (row, column) tuples on a M by M chessboard. +Write a function to count the number of pairs of bishops that attack each other. The +ordering of the pair doesn't matter: (1, 2) is considered the same as (2, 1). + +For example, given M = 5 and the list of bishops: + +(0, 0) +(1, 2) +(2, 2) +(4, 0) +The board would look like this: + +[b 0 0 0 0] +[0 0 b 0 0] +[0 0 b 0 0] +[0 0 0 0 0] +[b 0 0 0 0] +You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and +4. +""" + +from typing import List, Set, Tuple + +Position = Tuple[int, int] + + +def generate_diagonals(position: Position, board_size: int) -> Set[Position]: + row, col = position + diagonals = set() + # upper left diagonal + for i, j in zip(range(row - 1, -1, -1), range(col - 1, -1, -1)): + diagonals.add((i, j)) + # lower left diagonal + for i, j in zip(range(row + 1, board_size), range(col - 1, -1, -1)): + diagonals.add((i, j)) + # upper right diagonal + for i, j in zip(range(row - 1, -1, -1), range(col + 1, board_size)): + diagonals.add((i, j)) + # lower right diagonal + for i, j in zip(range(row + 1, board_size), range(col + 1, board_size)): + diagonals.add((i, j)) + return diagonals + + +def get_number_of_attacking_bishops(board_size: int, positions: List[Position]) -> int: + count = 0 + for index, position in enumerate(positions): + diagonals = generate_diagonals(position, board_size) + for position in positions[index:]: + if position in diagonals: + count += 1 + return count + + +if __name__ == "__main__": + positions = [(0, 0), (1, 2), (2, 2), (4, 0)] + print(get_number_of_attacking_bishops(5, positions)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/069.py b/Solutions/069.py new file mode 100644 index 0000000..c89ba38 --- /dev/null +++ b/Solutions/069.py @@ -0,0 +1,51 @@ +""" +Problem: + +Given a list of integers, return the largest product that can be made by multiplying +any three integers. + +For example, if the list is [-10, -10, 5, 2], we should return 500, since that's +-10 * -10 * 5. + +You can assume the list has at least three integers. +""" + +from typing import List + + +def largest_product_of_3(arr: List[int]) -> int: + # tracking the smallest 2 and the largest 3 numbers and generating the largest + # product using them + negative_1, negative_2 = 0, 0 + positive_1, positive_2, positive_3 = 0, 0, 0 + for elem in arr: + if elem < negative_1: + negative_2 = negative_1 + negative_1 = elem + elif elem < negative_2: + negative_2 = elem + elif elem > positive_1: + positive_3 = positive_2 + positive_2 = positive_1 + positive_1 = elem + elif elem > positive_2: + positive_3 = positive_2 + positive_2 = elem + elif elem > positive_3: + positive_3 = elem + return max( + positive_1 * negative_1 * negative_2, positive_1 * positive_2 * positive_3 + ) + + +if __name__ == "__main__": + print(largest_product_of_3([-10, -10, 5, 2])) + print(largest_product_of_3([10, -10, 5, 2])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/070.py b/Solutions/070.py new file mode 100644 index 0000000..35f22d5 --- /dev/null +++ b/Solutions/070.py @@ -0,0 +1,30 @@ +""" +Problem: + +Given a positive integer n, return the n-th perfect number. + +For example, given 1, you should return 19. Given 2, you should return 28. +""" + + +def calc_sum_of_digits(num: int) -> int: + s = 0 + for digit in str(num): + s += int(digit) + return s + + +def get_nth_perfect_num_naive(n: int) -> int: + num = 19 + count = 1 + while n > count: + num += 1 + if calc_sum_of_digits(num) == 10: + count += 1 + return num + + +if __name__ == "__main__": + print(get_nth_perfect_num_naive(1)) + print(get_nth_perfect_num_naive(2)) + print(get_nth_perfect_num_naive(10)) diff --git a/Solutions/071.py b/Solutions/071.py new file mode 100644 index 0000000..853abeb --- /dev/null +++ b/Solutions/071.py @@ -0,0 +1,38 @@ +""" +Problem: + +Using a function rand7() that returns an integer from 1 to 7 (inclusive) with uniform +probability, implement a function rand5() that returns an integer from 1 to 5 +(inclusive). +""" + +from random import randint +import matplotlib.pyplot as plt + + +# rand7 implementation +def rand7() -> int: + return randint(1, 7) + + +def rand5() -> int: + val = rand7() + if val <= 5: + return val + return rand5() + + +if __name__ == "__main__": + values = [] + for i in range(100_000): + values.append(rand5()) + plt.hist(values, bins=5, edgecolor="black") + plt.show() + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/072.py b/Solutions/072.py new file mode 100644 index 0000000..dbf32ea --- /dev/null +++ b/Solutions/072.py @@ -0,0 +1,121 @@ +""" +Problem: + +In a directed graph, each node is assigned an uppercase letter. We define a path's +value as the number of most frequently-occurring letter along that path. For example, +if a path in the graph goes through "ABACA", the value of the path is 3, since there +are 3 occurrences of 'A' on the path. + +Given a graph with n nodes and m directed edges, return the largest value path of the +graph. If the largest value is infinite, then return null. + +The graph is represented with a string and an edge list. The i-th character represents +the uppercase letter of the i-th node. Each tuple in the edge list (i, j) means there +is a directed edge from the i-th node to the j-th node. Self-edges are possible, as +well as multi-edges. + +For example, the following input graph: + +ABACA +[(0, 1), + (0, 2), + (2, 3), + (3, 4)] +Would have maximum value 3 using the path of vertices [0, 2, 3, 4], (A, A, C, A). + +The following input graph: + +A +[(0, 0)] +Should return null, since we have an infinite loop. +""" + +# Solution copied from: +# https://github.com/vineetjohn/daily-coding-problem/blob/master/solutions/problem_072.py + + +from typing import Dict, List, Optional, Set, Tuple + + +class GraphPath: + def __init__( + self, nodes: Set[str] = set(), letter_counts: Dict[str, int] = dict() + ) -> None: + self.nodes = nodes + self.letter_counts = letter_counts + + def __repr__(self) -> str: + return "nodes={}, letters={}".format(self.nodes, self.letter_counts) + + +def get_max_value_string_helper( + graph_path: GraphPath, node: str, adjacency_map: Dict[str, Set[str]] +) -> List[GraphPath]: + if node in graph_path.nodes: + return [graph_path] + + new_nodes = graph_path.nodes.copy() + new_nodes.add(node) + new_letter_counts = graph_path.letter_counts.copy() + if node[0] not in new_letter_counts: + new_letter_counts[node[0]] = 0 + new_letter_counts[node[0]] += 1 + + new_graph_path = GraphPath(new_nodes, new_letter_counts) + + if node not in adjacency_map: + return [new_graph_path] + + paths = list() + for child_node in adjacency_map[node]: + new_paths = get_max_value_string_helper( + new_graph_path, child_node, adjacency_map + ) + paths.extend(new_paths) + return paths + + +def get_max_value_string( + graph_string: str, edge_list: List[Tuple[int, int]] +) -> Optional[int]: + letter_counts = dict() + nodes = list() + for char in graph_string: + if char not in letter_counts: + letter_counts[char] = 0 + else: + letter_counts[char] += 1 + nodes.append("{}{}".format(char, letter_counts[char])) + + adjacency_map = dict() + for start, end in edge_list: + if nodes[start] not in adjacency_map: + adjacency_map[nodes[start]] = set() + if nodes[start] != nodes[end]: + adjacency_map[nodes[start]].add(nodes[end]) + + paths = list() + graph_path = GraphPath() + for node in adjacency_map: + new_paths = get_max_value_string_helper(graph_path, node, adjacency_map) + paths.extend(new_paths) + + max_value = 0 + for path in paths: + max_path_value = max(path.letter_counts.values()) + if max_path_value > max_value: + max_value = max_path_value + return max_value if max_value > 0 else None + + +if __name__ == "__main__": + print(get_max_value_string("ABACA", [(0, 1), (0, 2), (2, 3), (3, 4)])) + print(get_max_value_string("A", [(0, 0)])) + + +""" +SPECS: + +TIME COMPLEXITY: O((len(graph_string) + edges) ^ 2) +SPACE COMPLEXITY: O(len(graph_string) + edges) +""" diff --git a/Solutions/073.py b/Solutions/073.py new file mode 100644 index 0000000..0ff106c --- /dev/null +++ b/Solutions/073.py @@ -0,0 +1,51 @@ +""" +Problem: + +Given the head of a singly linked list, reverse it in-place. +""" + +from DataStructures.LinkedList import LinkedList + + +def reverse_inplace(ll: LinkedList) -> None: + ll.rear = ll.head + ptr_prev, ptr_curr, ptr_next = None, ll.head, ll.head.next + # reversing the flow + while ptr_curr is not None: + ptr_curr.next = ptr_prev + ptr_prev, ptr_curr = ptr_curr, ptr_next + if ptr_next is None: + break + ptr_next = ptr_next.next + ll.head = ptr_prev + + +if __name__ == "__main__": + ll = LinkedList() + for num in range(1, 6): + ll.add(num) + print(ll) + reverse_inplace(ll) + print(ll) + + ll = LinkedList() + for num in range(1, 3): + ll.add(num) + print(ll) + reverse_inplace(ll) + print(ll) + + ll = LinkedList() + for num in range(1, 2): + ll.add(num) + print(ll) + reverse_inplace(ll) + print(ll) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/074.py b/Solutions/074.py new file mode 100644 index 0000000..7c4fbde --- /dev/null +++ b/Solutions/074.py @@ -0,0 +1,49 @@ +""" +Problem 74: + +Suppose you have a multiplication table that is N by N. That is, a 2D array where the +value at the i-th row and j-th column is (i + 1) * (j + 1) (if 0-indexed) or i * j +(if 1-indexed). + +Given integers N and X, write a function that returns the number of times X appears as +a value in an N by N multiplication table. + +For example, given N = 6 and X = 12, you should return 4, since the multiplication +table looks like this: + +1 2 3 4 5 6 +2 4 6 8 10 12 +3 6 9 12 15 18 +4 8 12 16 20 24 +5 10 15 20 25 30 +6 12 18 24 30 36 +And there are 4 12's in the table. +""" + + +def calculate_frequency(n: int, x: int) -> int: + count = 0 + for i in range(1, n + 1): + for j in range(1, i + 1): + if i * j == x: + if i == j: + count += 1 + else: + count += 2 + return count + + +if __name__ == "__main__": + print(calculate_frequency(6, 12)) + print(calculate_frequency(1, 1)) + print(calculate_frequency(2, 4)) + print(calculate_frequency(3, 6)) + print(calculate_frequency(3, 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/075.py b/Solutions/075.py new file mode 100644 index 0000000..41301d0 --- /dev/null +++ b/Solutions/075.py @@ -0,0 +1,38 @@ +""" +Problem: + +Given an array of numbers, find the length of the longest increasing subsequence in +the array. The subsequence does not necessarily have to be contiguous. + +For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15], +the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15. +""" + +from typing import List + + +def longest_increasing_subsequence(arr: List[int]) -> int: + length = len(arr) + arr_dp = [1 for i in range(length)] + for i in range(1, length): + for j in range(i): + if arr[i] > arr[j]: + # increasing subsequence + arr_dp[i] = max(arr_dp[i], arr_dp[j] + 1) + return max(arr_dp) + + +if __name__ == "__main__": + print( + longest_increasing_subsequence( + [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/076.py b/Solutions/076.py new file mode 100644 index 0000000..1b5a6b2 --- /dev/null +++ b/Solutions/076.py @@ -0,0 +1,64 @@ +""" +Problem: + +You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of +columns that can be removed to ensure that each row is ordered from top to bottom +lexicographically. That is, the letter at each column is lexicographically later as you +go down each row. It does not matter whether each row itself is ordered +lexicographically. + +For example, given the following table: + +cba +daf +ghi +This is not ordered because of the a in the center. We can remove the second column to +make it ordered: + +ca +df +gi +So your function should return 1, since we only needed to remove 1 column. + +As another example, given the following table: + +abcdef +Your function should return 0, since the rows are already ordered (there's only one +row). + +As another example, given the following table: + +zyx +wvu +tsr +Your function should return 3, since we would need to remove all the columns to order +it. +""" + +from typing import List + + +def get_minimum_column_removals(matrix: List[List[int]]) -> int: + rows, columns = len(matrix), len(matrix[0]) + count = 0 + for column in range(columns): + # checking if the column is lexicographical + for row in range(rows - 1): + if matrix[row][column] > matrix[row + 1][column]: + count += 1 + break + return count + + +if __name__ == "__main__": + print(get_minimum_column_removals(["cba", "daf", "ghi"])) + print(get_minimum_column_removals(["abcdef"])) + print(get_minimum_column_removals(["zyx", "wvu", "tsr"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/077.py b/Solutions/077.py new file mode 100644 index 0000000..e6bb990 --- /dev/null +++ b/Solutions/077.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given a list of possibly overlapping intervals, return a new list of intervals where +all overlapping intervals have been merged. + +The input list is not necessarily ordered in any way. + +For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return +[(1, 3), (4, 10), (20, 25)]. +""" + +from typing import List, Tuple + + +def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: + intervals.sort(key=lambda x: x[0]) + merged_intervals = [] + start = intervals[0][0] + end = intervals[0][1] + # generating the merged intervals + for interval in intervals[1:]: + curr_start, curr_end = interval + if end < curr_start: + merged_intervals.append((start, end)) + start = curr_start + end = curr_end + elif end < curr_end and end > curr_start: + end = curr_end + # adding the last interval + merged_intervals.append((start, end)) + return merged_intervals + + +if __name__ == "__main__": + print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25)])) + print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25), (6, 12)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/078.py b/Solutions/078.py new file mode 100644 index 0000000..a54b99b --- /dev/null +++ b/Solutions/078.py @@ -0,0 +1,72 @@ +""" +Problem: + +Given k sorted singly linked lists, write a function to merge all the lists into one +sorted singly linked list. +""" + +from sys import maxsize +from typing import List + +from DataStructures.LinkedList import LinkedList, Node + + +def merge_sorted_linked_list(list_of_LL: List[LinkedList]) -> LinkedList: + k = len(list_of_LL) + position_arr = [LL.head for LL in list_of_LL] + sorted_ll = LinkedList() + while any(position_arr): + # finding the node with minimum value + minimum = maxsize + for i in range(k): + if position_arr[i] is not None: + if position_arr[i].val < minimum: + minimum = position_arr[i].val + position = i + # generating new node + if sorted_ll.head is None: + sorted_ll.add(position_arr[position].val) + curr_position = sorted_ll.head + else: + curr_position.next = Node(position_arr[position].val) + curr_position = curr_position.next + sorted_ll.length += 1 + position_arr[position] = position_arr[position].next + # resetting rear + sorted_ll.rear = curr_position + return sorted_ll + + +if __name__ == "__main__": + LL1 = LinkedList() + LL1.add(2) + LL1.add(25) + LL1.add(70) + + LL2 = LinkedList() + LL2.add(5) + LL2.add(8) + LL2.add(14) + LL2.add(15) + LL2.add(21) + LL2.add(48) + + LL3 = LinkedList() + LL3.add(0) + LL3.add(90) + + print(LL1) + print(LL2) + print(LL3) + + List = [LL1, LL2, LL3] + print(merge_sorted_linked_list(List)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n + k) +SPACE COMPLEXITY: O(n + k) +[n = total number of nodes] +""" diff --git a/Solutions/079.py b/Solutions/079.py new file mode 100644 index 0000000..83ac6e5 --- /dev/null +++ b/Solutions/079.py @@ -0,0 +1,40 @@ +""" +Problem: + +Given an array of integers, write a function to determine whether the array could +become non-decreasing by modifying at most 1 element. + +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. + +Given the array [10, 5, 1], you should return false, since we can't modify any one +element to get a non-decreasing array. +""" + +from typing import List + + +def check_1_modify_to_sorted(arr: List[int]) -> bool: + value = arr[0] + non_increasing_count = 0 + for elem in arr[1:]: + if elem - value < 0: + non_increasing_count += 1 + if non_increasing_count > 1: + return False + value = elem + return True + + +if __name__ == "__main__": + print(check_1_modify_to_sorted([10, 5, 7])) + print(check_1_modify_to_sorted([10, 5, 1])) + print(check_1_modify_to_sorted([1, 10, 5, 7])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/080.py b/Solutions/080.py new file mode 100644 index 0000000..35b406c --- /dev/null +++ b/Solutions/080.py @@ -0,0 +1,60 @@ +""" +Problem: + +Given the root of a binary tree, return a deepest node. For example, in the following +tree, return d. + + a + / \ + b c + / +d +""" + +from typing import Optional, Tuple + +from DataStructures.Tree import BinaryTree, Node + + +def deepest_node_helper(node: Node) -> Tuple[int, Optional[Node]]: + if node is None: + return 0, None + if not (node.left and node.right): + return 1, node + # getting the deepest node of the left-subtree + left_height, left_node = 0, None + if node.left: + left_height, left_node = deepest_node_helper(node.left) + # getting the deepest node of the right-subtree + right_height, right_node = 0, None + if node.right: + right_height, right_node = deepest_node_helper(node.right) + # comparing and returning the deepest node + if left_height > right_height: + return left_height + 1, left_node + return right_height + 1, right_node + + +def deepest_node(tree: BinaryTree) -> Node: + _, node = deepest_node_helper(tree.root) + return node + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node("a") + + tree.root.left = Node("b") + tree.root.right = Node("c") + + tree.root.left.left = Node("d") + + print(deepest_node(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) [recursion depth] +""" diff --git a/Solutions/081.py b/Solutions/081.py new file mode 100644 index 0000000..3773994 --- /dev/null +++ b/Solutions/081.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given a mapping of digits to letters (as in a phone number), and a digit string, return +all possible letters the number could represent. You can assume each valid number in +the mapping is a single digit. + +For example if {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], } then "23" should return +['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']. +""" + +from typing import Dict, List + + +def get_mappings( + digit_to_character_map: Dict[str, str], string: str, result: List[str] = [] +) -> List[str]: + if not string: + return result + if not result: + for elem in digit_to_character_map[string[0]]: + result.append(elem) + return get_mappings(digit_to_character_map, string[1:], result) + # generating the mappings + temp = [] + for part in result: + for elem in digit_to_character_map[string[0]]: + temp.append(part + elem) + result[:] = temp + return get_mappings(digit_to_character_map, string[1:], result) + + +if __name__ == "__main__": + print(get_mappings({"2": ["a", "b", "c"], "3": ["d", "e", "f"]}, "23", [])) + print(get_mappings({"2": ["a", "b", "c"], "3": ["d", "e", "f"]}, "32", [])) + print(get_mappings({"2": ["a", "b", "c"], "3": ["d", "e", "f"]}, "222", [])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ m) +SPACE COMPLEXITY: O(n ^ m) +[n = string length, m = no of characters in map] +""" diff --git a/Solutions/082/082.py b/Solutions/082/082.py new file mode 100644 index 0000000..b50d760 --- /dev/null +++ b/Solutions/082/082.py @@ -0,0 +1,41 @@ +""" +Problem: + +Using a read7() method that returns 7 characters from a file, implement readN(n) which +reads n characters. + +For example, given a file with the content "Hello world", three read7() returns +"Hello w", "orld" and then "". +""" + +# COUNT_7 stores the number of characters already read from the file +# STASHED_TEXT stores the unreturned data (used in readN) +COUNT_7 = 0 +STASHED_TEXT = "" + + +def read7(filename: str = "data_082.txt") -> str: + global COUNT_7 + with open(filename, "r") as f: + f.seek(COUNT_7, 0) + data = f.read(7) + COUNT_7 += 7 + return data + + +def readN(n: int, filename: str = "data_082.txt") -> str: + global STASHED_TEXT + for _ in range((n // 7) + 1): + STASHED_TEXT += read7(filename) + text = STASHED_TEXT[:n] + STASHED_TEXT = STASHED_TEXT[n:] + return text + + +if __name__ == "__main__": + print(readN(3)) + print(readN(10)) + print(readN(15)) + print(readN(25)) + print(readN(1000)) + print(readN(1000)) diff --git a/Solutions/082/data_082.txt b/Solutions/082/data_082.txt new file mode 100644 index 0000000..850ea4c --- /dev/null +++ b/Solutions/082/data_082.txt @@ -0,0 +1,2 @@ +Lorem ipsum dolor sit amet consectetur adipisicing elit. Officia, explicabo, quasi modi ea eaque vel perferendis consectetur aliquam laboriosam corporis fuga blanditiis alias! Fugit illum incidunt debitis nobis. Ad, assumenda? Lorem ipsum dolor sit amet +consectetur adipisicing elit. Quod similique, consequuntur alias nostrum excepturi repudiandae rem adipisci veniam accusantium inventore unde dolore dolor? Voluptatum non quibusdam nisi sunt harum quidem! \ No newline at end of file diff --git a/Solutions/083.py b/Solutions/083.py new file mode 100644 index 0000000..02478c1 --- /dev/null +++ b/Solutions/083.py @@ -0,0 +1,65 @@ +""" +Problem: + +Invert a binary tree. + +For example, given the following tree: + + a + / \ + b c + / \ / +d e f +should become: + + a + / \ + c b + \ / \ + f e d +""" + +from DataStructures.Tree import BinaryTree, Node + + +def invert_helper(node: Node) -> None: + node.right, node.left = node.left, node.right + # recursively inverting the children + if node.right is not None: + invert_helper(node.right) + if node.left is not None: + invert_helper(node.left) + + +def invert(tree: BinaryTree) -> None: + # inverts the tree in place + if not tree.root: + return + invert_helper(tree.root) + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node("a") + + tree.root.left = Node("b") + tree.root.right = Node("c") + + tree.root.left.left = Node("d") + tree.root.left.right = Node("e") + + tree.root.right.left = Node("f") + + print(tree) + + invert(tree) + + print(tree) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/085.py b/Solutions/085.py new file mode 100644 index 0000000..58c2725 --- /dev/null +++ b/Solutions/085.py @@ -0,0 +1,23 @@ +""" +Problem: + +Given three 32-bit integers x, y, and b, return x if b is 1 and y if b is 0, using only +mathematical or bit operations. You can assume b can only be 1 or 0. +""" + + +def switch_on_int(x: int, y: int, b: int) -> int: + return (x * b) + (y * abs(b - 1)) + + +if __name__ == "__main__": + print(switch_on_int(6, 8, 1)) + print(switch_on_int(6, 8, 0)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/086.py b/Solutions/086.py new file mode 100644 index 0000000..749118d --- /dev/null +++ b/Solutions/086.py @@ -0,0 +1,52 @@ +""" +Problem: + +Given a string of parentheses, write a function to compute the minimum number of +parentheses to be removed to make the string valid (i.e. each open parenthesis is +eventually closed). + +For example, given the string "()())()", you should return 1. Given the string ")(", +you should return 2, since we must remove all of them. +""" + +from copy import deepcopy + +from DataStructures.Stack import Stack + + +def get_min_parentheses_remove( + expression: str, stack: Stack = Stack(), num_removed: int = 0 +) -> int: + if not expression and stack.is_empty(): + return num_removed + elif not expression: + return len(stack) + num_removed + if (expression[0] == ")") and (not stack.is_empty() and stack.peek() == "("): + stack.pop() + return get_min_parentheses_remove(expression[1:], stack, num_removed) + # calulating the modifications for parenthesis added to stack + stack_copy = deepcopy(stack) + stack_copy.push(expression[0]) + modifications_parenthesis_added_to_stack = get_min_parentheses_remove( + expression[1:], stack_copy, num_removed + ) + # calulating the modifications for parenthesis removed + modifications_parenthesis_ignored = get_min_parentheses_remove( + expression[1:], stack, num_removed + 1 + ) + return min( + modifications_parenthesis_added_to_stack, modifications_parenthesis_ignored + ) + + +if __name__ == "__main__": + print(get_min_parentheses_remove("()())()")) + print(get_min_parentheses_remove(")(")) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/087.py b/Solutions/087.py new file mode 100644 index 0000000..f3fa6fc --- /dev/null +++ b/Solutions/087.py @@ -0,0 +1,93 @@ +""" +Problem: + +A rule looks like this: + +A NE B + +This means this means point A is located northeast of point B. + +A SW C + +means that point A is southwest of C. + +Given a list of rules, check if the sum of the rules validate. For example: + +A N B +B NE C +C N A +does not validate, since A cannot be both north and south of C. + +A NW B +A N B +is considered valid. +""" + +from __future__ import annotations +from typing import Union + +OPPOSITES_CARDINALS = {"N": "S", "S": "N", "E": "W", "W": "E"} + + +class Node: + def __init__(self, val: str) -> None: + self.val = val + self.neighbours = {"N": set(), "E": set(), "S": set(), "W": set()} + + def __repr__(self) -> str: + return f"{self.val}" + + def __eq__(self, other: Union[Node, str]) -> bool: + if type(other) == Node: + return self.val == other.val + elif type(other) == str: + return self.val == other + return False + + def __hash__(self) -> int: + return hash(self.val) + + +class Map: + def __init__(self) -> None: + self.nodes = {} + + def add_rule(self, rule: str) -> None: + node1, direction, node2 = rule.split() + node1 = Node(node1) + node2 = Node(node2) + # cheking for the existance of the nodes + if node1 not in self.nodes: + self.nodes[node1.val] = node1 + else: + node1 = self.nodes[node1.val] + if node2 not in self.nodes: + self.nodes[node2.val] = node2 + else: + node2 = self.nodes[node2.val] + # updating the neighbours + for char in direction: + if (node1 in node2.neighbours[char]) or ( + node2 in node1.neighbours[OPPOSITES_CARDINALS[char]] + ): + raise RuntimeError + for node in node1.neighbours[char]: + self.add_rule(f"{node} {char} {node2}") + # adding the rule to the calling node + for char in direction: + node2.neighbours[char].add(node1) + node1.neighbours[OPPOSITES_CARDINALS[char]].add(node2) + + +if __name__ == "__main__": + m = Map() + + m.add_rule("A N B") + print("Rule Applied!") + m.add_rule("B NE C") + print("Rule Applied!") + + try: + m.add_rule("C N A") + except RuntimeError: + print("Invalid Rule!") diff --git a/Solutions/088.py b/Solutions/088.py new file mode 100644 index 0000000..92124c2 --- /dev/null +++ b/Solutions/088.py @@ -0,0 +1,33 @@ +""" +Problem: + +Implement division of two positive integers without using the division, multiplication, +or modulus operators. Return the quotient as an integer, ignoring the remainder. +""" + + +def divide(dividend: int, divisor: int) -> int: + quotient = 0 + while dividend > 0: + dividend -= divisor + if dividend >= 0: + quotient += 1 + return quotient + + +if __name__ == "__main__": + print(divide(1, 0)) + print(divide(1, 1)) + print(divide(0, 1)) + print(divide(12, 3)) + print(divide(13, 3)) + print(divide(25, 5)) + print(divide(25, 7)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/089.py b/Solutions/089.py new file mode 100644 index 0000000..e0fb482 --- /dev/null +++ b/Solutions/089.py @@ -0,0 +1,69 @@ +""" +Problem: + +Determine whether a tree is a valid binary search tree. + +A binary search tree is a tree with two children, left and right, and satisfies the +constraint that the key in the left child must be less than or equal to the root and +the key in the right child must be greater than or equal to the root. +""" + +from DataStructures.Tree import BinaryTree, BinarySearchTree, Node + + +def is_binary_search_tree_helper(node: Node) -> bool: + if node is None: + return True + if node.left is None and node.right is None: + return True + elif (node.left and node.left.val > node.val) or ( + node.right and node.right.val < node.val + ): + return False + return is_binary_search_tree_helper(node.left) and is_binary_search_tree_helper( + node.right + ) + + +def is_binary_search_tree(tree: BinaryTree) -> bool: + return is_binary_search_tree_helper(tree.root) + + +if __name__ == "__main__": + tree1 = BinarySearchTree() + + tree1.add(5) + tree1.add(9) + tree1.add(1) + tree1.add(4) + tree1.add(10) + tree1.add(3) + tree1.add(2) + tree1.add(10) + tree1.add(7) + + print(is_binary_search_tree(tree1)) + + tree2 = BinaryTree() + tree2.root = Node(5) + + tree2.root.left = Node(4) + tree2.root.right = Node(6) + + print(is_binary_search_tree(tree2)) + + tree3 = BinaryTree() + tree3.root = Node(5) + + tree3.root.left = Node(6) + tree3.root.right = Node(4) + + print(is_binary_search_tree(tree3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) [recursion depth] +""" diff --git a/Solutions/090.py b/Solutions/090.py new file mode 100644 index 0000000..ce5d0c7 --- /dev/null +++ b/Solutions/090.py @@ -0,0 +1,43 @@ +""" +Problem: + +Given an integer n and a list of integers l, write a function that randomly generates a +number from 0 to n-1 that isn't in l (uniform). +""" + +import matplotlib.pyplot as plt +from random import randint +from typing import List + + +def generate_num_not_in_data(n: int, data: List[int]) -> int: + num = randint(0, n - 1) + if num in data: + return generate_num_not_in_data(n, data) + return num + + +if __name__ == "__main__": + data = [1, 3, 5] + results = {} + for i in range(100_000): + val = generate_num_not_in_data(7, data) + if val in results: + results[val] += 1 + else: + results[val] = 1 + + x, y = [], [] + for i in results: + x.append(i) + y.append(results[i]) + plt.bar(x=x, height=y, edgecolor="black") + plt.show() + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/091.py b/Solutions/091.py new file mode 100644 index 0000000..5e7758e --- /dev/null +++ b/Solutions/091.py @@ -0,0 +1,27 @@ +""" +Problem: + +What does the below code snippet print out? How can we fix the anonymous functions to +behave as we'd expect? + +functions = [] +for i in range(10): + functions.append(lambda : i) + +for f in functions: + print(f()) +""" + +# The code is expected to print 9, 9, ..., 9 (10 times) as the value of i is set to 9 +# at the end of the 1st loop and is not changed during iterating through the 2nd loop. +# Considering we plan to print 0 to 9, we can set and update the value of i every +# iteration + +functions = [] +for i in range(10): + functions.append(lambda: i) + +i = 0 # MODIFICATION +for f in functions: + print(f()) + i += 1 # MODIFICATION diff --git a/Solutions/092.py b/Solutions/092.py new file mode 100644 index 0000000..3dc3ccc --- /dev/null +++ b/Solutions/092.py @@ -0,0 +1,91 @@ +""" +Problem: + +We're given a hashmap with a key courseId and value a list of courseIds, which +represents that the prerequsite of courseId is courseIds. Return a sorted ordering of +courses such that we can finish all courses. + +Return null if there is no such ordering. + +For example, given {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}, +should return ['CSC100', 'CSC200', 'CSCS300']. +""" + +from typing import Dict, List, Optional, Set, Tuple + + +def get_order_helper( + course_map: Dict[str, str], + course: str, + order: List[str], + processed: Set[str], + break_limit: Optional[int] = None, + curr: int = 0, +) -> Tuple[Optional[List[int]], Optional[Set[int]]]: + if not break_limit: + break_limit = len(course_map) + if break_limit < curr: + return None, None + if course_map[course] == []: + # if the course doesn't have any pre-req + if course not in processed: + order.append(course) + processed.add(course) + return order, processed + + for prerequisite in course_map[course]: + order, processed = get_order_helper( + course_map, prerequisite, order, processed, break_limit, curr + 1 + ) + if order is None: + return None, None + order.append(course) + processed.add(course) + return order, processed + + +def get_order(course_map: Dict[str, str]) -> Optional[List[str]]: + order = [] + processed = set() + + for course in course_map: + if course not in processed: + for prerequisite in course_map[course]: + if prerequisite not in processed: + order, processed = get_order_helper( + course_map, prerequisite, order, processed + ) + if order is None: + return None + order.append(course) + processed.add(course) + return order + + +if __name__ == "__main__": + prereqs = {"CSC300": ["CSC100", "CSC200"], "CSC200": ["CSC100"], "CSC100": []} + print(get_order(prereqs)) + + prereqs = { + "CSC400": ["CSC300"], + "CSC300": ["CSC100", "CSC200"], + "CSC200": ["CSC100"], + "CSC100": [], + } + print(get_order(prereqs)) + + prereqs = { + "CSC400": ["CSC300"], + "CSC300": ["CSC100", "CSC200"], + "CSC200": ["CSC100"], + "CSC100": ["CSC400"], + } + print(get_order(prereqs)) + + +""" +SPECS: + +TIME COMPLEXITY: O(courses x prerequisites) +SPACE COMPLEXITY: O(courses x prerequisites) +""" diff --git a/Solutions/093.py b/Solutions/093.py new file mode 100644 index 0000000..ee841bc --- /dev/null +++ b/Solutions/093.py @@ -0,0 +1,148 @@ +""" +Problem: + +Given a tree, find the largest tree/subtree that is a BST. + +Given a tree, return the size of the largest tree/subtree that is a BST. +""" + +from sys import maxsize +from typing import Tuple + +from DataStructures.Tree import BinaryTree, Node + + +def get_largest_bst_size_helper(node: Node) -> Tuple[int, Node, bool, int, int]: + if not node: + return 0, node, True, maxsize, -maxsize + if not node.left and not node.right: + return 1, node, True, node.val, node.val + + l_height, l_root, l_is_bst, l_max_val, l_min_val = get_largest_bst_size_helper( + node.left + ) + r_height, r_root, r_is_bst, r_max_val, r_min_val = get_largest_bst_size_helper( + node.right + ) + if l_is_bst and r_is_bst: + if node.left and node.right: + if l_max_val <= node.val <= r_min_val: + return (l_height + r_height + 1), node, True, r_max_val, l_min_val + else: + if node.left and node.val > l_max_val: + return l_height + 1, node, True, node.val, l_min_val + elif node.right and node.val < r_min_val: + return r_height + 1, node, True, r_max_val, node.val + if l_height > r_height: + return l_height, l_root, False, l_max_val, l_min_val + return r_height, r_root, False, r_max_val, r_min_val + + +def get_largest_bst_size(tree: BinaryTree) -> Tuple[int, int]: + size, node, _, _, _ = get_largest_bst_size_helper(tree.root) + return size, node.val + + +if __name__ == "__main__": + a = Node(3) + b = Node(2) + c = Node(6) + d = Node(1) + e = Node(1) + f = Node(4) + + a.left = b + a.right = c + b.left = d + b.right = e + c.left = f + + tree = BinaryTree() + tree.root = a + + print(tree) + print("Size: {}\tNode Val: {}".format(*get_largest_bst_size(tree))) + + a = Node(3) + b = Node(2) + c = Node(6) + d = Node(1) + e = Node(4) + f = Node(4) + + a.left = b + a.right = c + b.left = d + b.right = e + c.left = f + + tree = BinaryTree() + tree.root = a + + print(tree) + print("Size: {}\tNode Val: {}".format(*get_largest_bst_size(tree))) + + a = Node(1) + b = Node(2) + c = Node(6) + d = Node(1) + e = Node(3) + f = Node(4) + + a.left = b + a.right = c + b.left = d + b.right = e + c.left = f + + tree = BinaryTree() + tree.root = a + + print(tree) + print("Size: {}\tNode Val: {}".format(*get_largest_bst_size(tree))) + + a = Node(3) + b = Node(2) + c = Node(6) + d = Node(1) + e = Node(3) + f = Node(4) + + a.left = b + a.right = c + b.left = d + b.right = e + c.left = f + + tree = BinaryTree() + tree.root = a + + print(tree) + print("Size: {}\tNode Val: {}".format(*get_largest_bst_size(tree))) + + a = Node(3) + b = Node(1) + c = Node(6) + d = Node(0) + e = Node(2) + f = Node(4) + + a.left = b + a.right = c + b.left = d + b.right = e + c.left = f + + tree = BinaryTree() + tree.root = a + + print(tree) + print("Size: {}\tNode Val: {}".format(*get_largest_bst_size(tree))) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/094.py b/Solutions/094.py new file mode 100644 index 0000000..51ad55b --- /dev/null +++ b/Solutions/094.py @@ -0,0 +1,77 @@ +""" +Problem: + +Given a binary tree of integers, find the maximum path sum between two nodes. The path +must go through at least one node, and does not need to go through the root. +""" + +from DataStructures.Tree import BinaryTree, Node + + +def get_max_path_sum_helper( + node: Node, current_max_sum: int = 0, overall_max_sum: int = 0 +) -> int: + if not node: + return 0 + + l_max_sum = get_max_path_sum_helper(node.left, current_max_sum, overall_max_sum) + r_max_sum = get_max_path_sum_helper(node.right, current_max_sum, overall_max_sum) + # current max sum = max( + # node's value added to the current sum + # current max sum + # only node's value selected + # right subtree not selected + # left subtree not selected + # entire subtree selected + # ) + current_max_sum = max( + current_max_sum + node.val, + current_max_sum, + node.val, + l_max_sum + node.val, + r_max_sum + node.val, + l_max_sum + node.val + r_max_sum, + ) + # overall max sum is updated as per requirement + overall_max_sum = max(current_max_sum, overall_max_sum) + return overall_max_sum + + +def get_max_path_sum(tree: BinaryTree) -> int: + return get_max_path_sum_helper(tree.root) + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(1) + + print(tree) + print(get_max_path_sum(tree)) + + tree.root.left = Node(2) + print(tree) + print(get_max_path_sum(tree)) + + tree.root.right = Node(3) + print(tree) + print(get_max_path_sum(tree)) + + tree.root.val = -1 + print(tree) + print(get_max_path_sum(tree)) + + tree.root.left.left = Node(4) + print(tree) + print(get_max_path_sum(tree)) + + tree.root.right.right = Node(-1) + print(tree) + print(get_max_path_sum(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/095.py b/Solutions/095.py new file mode 100644 index 0000000..10b7b21 --- /dev/null +++ b/Solutions/095.py @@ -0,0 +1,56 @@ +""" +Problem: + +Given a number represented by a list of digits, find the next greater permutation of a +number, in terms of lexicographic ordering. If there is not greater permutation +possible, return the permutation with the lowest value/ordering. + +For example, the list [1,2,3] should return [1,3,2]. The list [1,3,2] should return +[2,1,3]. The list [3,2,1] should return [1,2,3] + +Can you perform the operation without allocating extra memory (disregarding the input +memory)? +""" + +from typing import List + + +def get_next(arr: List[int]) -> List[int]: + length = len(arr) + if length < 2: + return arr + # finding the last element arranged in ascending order + for index in range(length - 1, -1, -1): + if index > 0 and arr[index - 1] < arr[index]: + break + # if index is 0, arr is sorted in descending order + if index == 0: + arr.reverse() + return arr + # finding the next permutation + for k in range(length - 1, index - 1, -1): + if arr[k] > arr[index - 1]: + arr[k], arr[index - 1] = arr[index - 1], arr[k] + break + # arranging the other elements in proper order + size = (length - 1) + index + for i in range(index, (size + 1) // 2): + arr[i], arr[size - i] = arr[size - i], arr[i] + return arr + + +if __name__ == "__main__": + print(get_next([1, 2, 3])) + print(get_next([1, 3, 2])) + print(get_next([2, 1, 3])) + print(get_next([2, 3, 1])) + print(get_next([3, 1, 2])) + print(get_next([3, 2, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/096.py b/Solutions/096.py new file mode 100644 index 0000000..d9326a1 --- /dev/null +++ b/Solutions/096.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a number in the form of a list of digits, return all possible permutations. + +For example, given [1,2,3], return [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]. +""" + +from copy import deepcopy +from typing import List, Optional + + +def generate_all_permutations( + arr: List[int], l: int = 0, r: Optional[int] = None, res: List[List[int]] = [] +) -> List[List[int]]: + if r is None: + r = len(arr) - 1 + if l == r: + res.append(list(arr)) + return res + # generating all permutation using backtracking + for i in range(l, r + 1): + arr[l], arr[i] = arr[i], arr[l] + generate_all_permutations(arr, l + 1, r, res) + arr[l], arr[i] = arr[i], arr[l] + return res + + +if __name__ == "__main__": + print(generate_all_permutations([1, 2, 3], res=[])) + print(generate_all_permutations([1, 2], res=[])) + print(generate_all_permutations([1], res=[])) + print(generate_all_permutations([], res=[])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n!) +SPACE COMPLEXITY: O(n!) +[there are n! permutions for an array with n elements] +""" diff --git a/Solutions/097.py b/Solutions/097.py new file mode 100644 index 0000000..60b1eff --- /dev/null +++ b/Solutions/097.py @@ -0,0 +1,159 @@ +""" +Problem: + +Write a map implementation with a get function that lets you retrieve the value of a +key at a particular time. + +It should contain the following methods: + set(key, value, time): # sets key to value for t = time. + get(key, time): # gets the key at t = time. +The map should work like this. If we set a key at a particular time, it will maintain +that value forever or until it gets set at a later time. In other words, when we get a +key at a time, it should return the value that was set for that key set at the most +recent time. + +Consider the following examples: + +d.set(1, 1, 0) # set key 1 to value 1 at time 0 +d.set(1, 2, 2) # set key 1 to value 2 at time 2 +d.get(1, 1) # get key 1 at time 1 should be 1 +d.get(1, 3) # get key 1 at time 3 should be 2 + +d.set(1, 1, 5) # set key 1 to value 1 at time 5 +d.get(1, 0) # get key 1 at time 0 should be null +d.get(1, 10) # get key 1 at time 10 should be 1 + +d.set(1, 1, 0) # set key 1 to value 1 at time 0 +d.set(1, 2, 0) # set key 1 to value 2 at time 0 +d.get(1, 0) # get key 1 at time 0 should be 2 +""" + +from typing import Any, Dict, Optional + + +class Node: + def __init__(self, val_list: Dict[int, int], time: int) -> None: + self.val_list = val_list + self.time = time + self.next = None + self.prev = None + + def __repr__(self) -> str: + if self.next: + return f"{self.val_list} ({self.time}) <=> {str(self.next)}" + return f"{self.val_list} ({self.time})" + + def __eq__(self, other: Any) -> bool: + if type(other) == Node: + return self.time == other.time + return False + + +class Double_Linked_List: + def __init__(self) -> None: + self.head = None + self.rear = None + self.length = 0 + + def __repr__(self) -> str: + return str(self.head) + + def __bool__(self) -> bool: + return bool(self.head) + + def add(self, val_list: Dict[int, int], time: int) -> None: + self.length += 1 + if self.head == None: + self.head = Node(val_list, time) + self.rear = self.head + else: + self.rear.next = Node(val_list, time) + self.rear.next.prev = self.rear + self.rear = self.rear.next + + +class Map: + def __init__(self) -> None: + self.linked_list = Double_Linked_List() + + def set(self, key: int, value: int, time: int) -> None: + if not self.linked_list: + self.linked_list.add({key: value}, time) + else: + pos = self.linked_list.head + while pos and pos.time < time: + pos = pos.next + # adding the new node at the head + if pos == self.linked_list.head: + temp_val_list = {key: value} + new_node = Node(temp_val_list, time) + + self.linked_list.head.prev = new_node + new_node.next = self.linked_list.head + self.head = new_node + # adding the new value + if pos: + if time == pos.time: + pos.val_list[key] = value + else: + temp_val_list = dict(pos.prev.val_list) + temp_val_list[key] = value + new_node = Node(temp_val_list, time) + + new_node.next = pos + new_node.prev = pos.prev + pos.prev.next = new_node + pos.prev = new_node + return + temp_val_list = dict(self.linked_list.rear.val_list) + temp_val_list[key] = value + self.linked_list.add(temp_val_list, time) + + def get(self, key: int, time: int) -> Optional[int]: + if not self.linked_list: + return None + + pos = self.linked_list.head + while pos and pos.time < time: + pos = pos.next + # key in the rear + if not pos: + try: + temp = self.linked_list.rear.val_list[key] + return temp + except: + return None + # key in the current node + elif pos and pos.time == time: + try: + temp = pos.val_list[key] + return temp + except: + return None + # key in previous node + else: + try: + temp = pos.prev.val_list[key] + return temp + except: + return None + + +if __name__ == "__main__": + d = Map() + d.set(1, 1, 0) # set key 1 to value 1 at time 0 + d.set(1, 2, 2) # set key 1 to value 2 at time 2 + print(d.get(1, 1)) # get key 1 at time 1 should be 1 + print(d.get(1, 3)) # get key 1 at time 3 should be 2 + print() + + d = Map() + d.set(1, 1, 5) # set key 1 to value 1 at time 5 + print(d.get(1, 0)) # get key 1 at time 0 should be null + print(d.get(1, 10)) # get key 1 at time 10 should be 1 + print() + + d = Map() + d.set(1, 1, 0) # set key 1 to value 1 at time 0 + d.set(1, 2, 0) # set key 1 to value 2 at time 0 + print(d.get(1, 0)) # get key 1 at time 0 should be 2 diff --git a/Solutions/098.py b/Solutions/098.py new file mode 100644 index 0000000..cee88f3 --- /dev/null +++ b/Solutions/098.py @@ -0,0 +1,84 @@ +""" +Problem: + +Given a 2D board of characters and a word, find if the word exists in the grid. + +The word can be constructed from letters of sequentially adjacent cell, where "adjacent" +cells are those horizontally or vertically neighboring. The same letter cell may not be +used more than once. + +For example, given the following board: + +[ + ['A','B','C','E'], + ['S','F','C','S'], + ['A','D','E','E'] +] +exists(board, "ABCCED") returns true, exists(board, "SEE") returns true, +exists(board, "ABCB") returns false. +""" + +from typing import List, Set, Tuple + +Board = List[List[str]] +Position = Tuple[int, int] + + +def get_neighbors(positons: Position, n: int, m: int) -> List[Position]: + i, j = positons + neighbors = [(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1)] + result = [] + for neighbor in neighbors: + i, j = neighbor + if i <= i < n and 0 <= j < m: + result.append(neighbor) + return result + + +def exists_helper( + board: Board, position: Position, string: str, visited: Set[Position] = set() +) -> bool: + if not string: + return True + # using backtracking to generate the result as every position can be used only once + neighbors = get_neighbors(position, len(board), len(board[0])) + for neighbor in neighbors: + i, j = neighbor + if (board[i][j] == string[0]) and (neighbor not in visited): + visited.add((i, j)) + if exists_helper(board, (i, j), string[1:], visited): + return True + visited.remove((i, j)) + return False + + +def exists(board: Board, string: str) -> bool: + if not string: + return True + + for row_index, row in enumerate(board): + for index, elem in enumerate(row): + if string[0] == elem: + if exists_helper(board, (row_index, index), string[1:], set()): + return True + return False + + +if __name__ == "__main__": + board = [ + ["A", "B", "C", "E"], + ["S", "F", "C", "S"], + ["A", "D", "E", "E"] + ] + + print(exists(board, "ABCCED")) + print(exists(board, "SEE")) + print(exists(board, "ABCB")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) +""" \ No newline at end of file diff --git a/Solutions/099.py b/Solutions/099.py new file mode 100644 index 0000000..db49aad --- /dev/null +++ b/Solutions/099.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given an unsorted array of integers, find the length of the longest consecutive +elements sequence. + +For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is +[1, 2, 3, 4]. Return its length: 4. + +Your algorithm should run in O(n) complexity. +""" + +from typing import List + + +def longest_consecutive_elements_sequence(arr: List[int]) -> int: + length = len(arr) + arr_elems_set = set(arr) + longest_sequence = 0 + # generating the longest sequence length + for i in range(length): + if (arr[i] - 1) not in arr_elems_set: + # current element is the starting element of a sequence + j = arr[i] + while j in arr_elems_set: + j += 1 + # update longest sequence length + longest_sequence = max(longest_sequence, j - arr[i]) + return longest_sequence + + +if __name__ == "__main__": + print(longest_consecutive_elements_sequence([100, 4, 200, 1])) + print(longest_consecutive_elements_sequence([100, 4, 200, 1, 3])) + print(longest_consecutive_elements_sequence([100, 4, 200, 2, 3])) + print(longest_consecutive_elements_sequence([100, 4, 200, 1, 3, 2])) + print(longest_consecutive_elements_sequence([100, 4, 200, 1, 3, 2, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/100.py b/Solutions/100.py new file mode 100644 index 0000000..3fe07e1 --- /dev/null +++ b/Solutions/100.py @@ -0,0 +1,54 @@ +""" +Problem: + +You are in an infinite 2D grid where you can move in any of the 8 directions: + + (x,y) to + (x+1, y), + (x - 1, y), + (x, y+1), + (x, y-1), + (x-1, y-1), + (x+1,y+1), + (x-1,y+1), + (x+1,y-1) +You are given a sequence of points and the order in which you need to cover the points. +Give the minimum number of steps in which you can achieve it. You start from the first +point. + +Example: Input: [(0, 0), (1, 1), (1, 2)] Output: 2 It takes 1 step to move from (0, 0) +to (1, 1). It takes one more step to move from (1, 1) to (1, 2). +""" + +from typing import List, Tuple + + +def get_min_steps(sequence: List[Tuple[int, int]]) -> int: + length = len(sequence) + if length in [0, 1]: + return 0 + + curr_position = sequence[0] + total_distance = 0 + for next_position in sequence[1:]: + i, j = curr_position + y, x = next_position + total_distance += max((abs(y - i)), abs(x - j)) + curr_position = next_position + return total_distance + + +if __name__ == "__main__": + print(get_min_steps([])) + print(get_min_steps([(0, 0)])) + print(get_min_steps([(0, 0), (1, 1), (1, 2)])) + print(get_min_steps([(0, 0), (1, 1), (1, 2), (3, 4)])) + print(get_min_steps([(0, 0), (1, 1), (1, 2), (3, 6)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/101.py b/Solutions/101.py new file mode 100644 index 0000000..df0b6c5 --- /dev/null +++ b/Solutions/101.py @@ -0,0 +1,63 @@ +""" +Problem: + +Given an even number (greater than 2), return two prime numbers whose sum will be equal +to the given number. + +A solution will always exist. See Goldbach’s conjecture. + +Example: + +numut: 4 Output: 2 + 2 = 4 If there are more than one solution possible, return the +lexicographically smaller solution. + +If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then + +[a, b] < [c, d] +if a < c or a==c and b < d. +""" + +from typing import Tuple + + +def is_prime(num: int) -> bool: + # time complexity: O(log(n)) + for i in range(2, int(num ** 0.5) + 1): + if num % i == 0: + return False + return True + + +def get_prime_sum(num: int) -> Tuple[int, int]: + if num > 2 and is_prime(num - 2): + return 2, num - 2 + if num > 3 and is_prime(num - 3): + return 3, num - 3 + # all prime numbers are of the form (6n + 1) or (6n - 1) + for i in range(6, num // 2, 6): + if is_prime(i - 1) and is_prime(num - i + 1): + return (i - 1), (num - i + 1) + elif is_prime(i + 1) and is_prime(num - i - 1): + return (i + 1), (num - i - 1) + + +if __name__ == "__main__": + num = 4 + num_1, num_2 = get_prime_sum(num) + print(f"{num} = {num_1} + {num_2}") + + num = 10 + num_1, num_2 = get_prime_sum(num) + print(f"{num} = {num_1} + {num_2}") + + num = 100 + num_1, num_2 = get_prime_sum(num) + print(f"{num} = {num_1} + {num_2}") + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/102.py b/Solutions/102.py new file mode 100644 index 0000000..f2c7a2c --- /dev/null +++ b/Solutions/102.py @@ -0,0 +1,47 @@ +""" +Problem: + +Given a list of integers and a number K, return which contiguous elements of the list +sum to K. + +For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4]. +""" + +from typing import List, Optional + + +def get_arr_contiguous_sum(arr: List[int], k: int) -> Optional[List[int]]: + length = len(arr) + total_sum = 0 + start, end = 0, 0 + # generating the sequence using moving window + for i in range(length): + if total_sum == k: + return arr[start:end] + total_sum += arr[i] + end = i + 1 + if total_sum > k: + total_sum -= arr[start] + start += 1 + if total_sum == k: + return arr[start:end] + return None + + +if __name__ == "__main__": + print(get_arr_contiguous_sum([1, 2, 3, 4, 5], 0)) + print(get_arr_contiguous_sum([1, 2, 3, 4, 5], 1)) + print(get_arr_contiguous_sum([1, 2, 3, 4, 5], 5)) + print(get_arr_contiguous_sum([5, 4, 3, 4, 5], 12)) + print(get_arr_contiguous_sum([5, 4, 3, 4, 5], 11)) + print(get_arr_contiguous_sum([1, 2, 3, 4, 5], 9)) + print(get_arr_contiguous_sum([1, 2, 3, 4, 5], 3)) + print(get_arr_contiguous_sum([1, 2, 3, 4, 5], 300)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/103.py b/Solutions/103.py new file mode 100644 index 0000000..48d7495 --- /dev/null +++ b/Solutions/103.py @@ -0,0 +1,57 @@ +""" +Problem: + +Given a string and a set of characters, return the shortest substring containing all +the characters in the set. + +For example, given the string "figehaeci" and the set of characters {a, e, i}, you +should return "aeci". + +If there is no substring containing all the characters in the set, return null. +""" + +from typing import Set + + +def shortest_substring_with_all_characters(string: str, characters: Set[str]) -> str: + curr_char_queue, index_queue = [], [] + curr_seen = set() + num_char = len(characters) + result = None + # generating the shortest substring + for i in range(len(string)): + if string[i] in characters: + curr_char_queue.append(string[i]) + index_queue.append(i) + curr_seen.add(string[i]) + # shortening the substring + shift = 0 + for k in range(len(curr_char_queue) // 2): + if curr_char_queue[k] == curr_char_queue[-k - 1]: + shift += 1 + # truncating the queues + curr_char_queue = curr_char_queue[shift:] + index_queue = index_queue[shift:] + # all characters found + if len(curr_seen) == num_char: + if (not result) or (len(result) > (index_queue[-1] - index_queue[0] + 1)): + result = string[index_queue[0] : index_queue[-1] + 1] + return result + + +if __name__ == "__main__": + print(shortest_substring_with_all_characters("abcdedbc", {"g", "f"})) + print(shortest_substring_with_all_characters("abccbbbccbcb", {"a", "b", "c"})) + print(shortest_substring_with_all_characters("figehaeci", {"a", "e", "i"})) + print(shortest_substring_with_all_characters("abcdedbc", {"d", "b", "b"})) + print(shortest_substring_with_all_characters("abcdedbc", {"b", "c"})) + print(shortest_substring_with_all_characters("abcdecdb", {"b", "c"})) + print(shortest_substring_with_all_characters("abcdecdb", {"b", "c", "e"})) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/104.py b/Solutions/104.py new file mode 100644 index 0000000..bcb2abb --- /dev/null +++ b/Solutions/104.py @@ -0,0 +1,61 @@ +""" +Problem: + +Determine whether a doubly linked list is a palindrome. What if it’s singly linked? + +For example, 1 -> 4 -> 3 -> 4 -> 1 returns true while 1 -> 4 returns false. +""" + +from DataStructures.LinkedList import LinkedList + + +def is_palindrome(ll: LinkedList) -> bool: + if ll.head is None: + return True + elif ll.rear == ll.head: + return True + + pos1 = ll.head + pos2 = ll.rear + for i in range((ll.length + 1) // 2): + if pos1.val != pos2.val: + return False + # updating the end pointer + pos = pos1 + for _ in range((ll.length - (2 * i)) - 2): + pos = pos.next + pos2 = pos + # updating the start pointer + pos1 = pos1.next + return True + + +if __name__ == "__main__": + LL = LinkedList() + for i in [1, 4, 3, 2, 3, 4, 1]: + LL.add(i) + print("Palindrome: {}\t\tList: {}".format(is_palindrome(LL), LL)) + + LL = LinkedList() + for i in [1, 4, 3]: + LL.add(i) + print("Palindrome: {}\t\tList: {}".format(is_palindrome(LL), LL)) + + LL = LinkedList() + for i in [1]: + LL.add(i) + print("Palindrome: {}\t\tList: {}".format(is_palindrome(LL), LL)) + + LL = LinkedList() + print("Palindrome: {}\t\tList: {}".format(is_palindrome(LL), LL)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +[This problem can be reduced to O(n) time & space by caching the Linked List in an +array] +[If a Double Linked List is used, the problem is reduced to O(n) time & O(1) space] +""" diff --git a/Solutions/105.py b/Solutions/105.py new file mode 100644 index 0000000..419e4ba --- /dev/null +++ b/Solutions/105.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a function f, and N return a debounced f of N milliseconds. + +That is, as long as the debounced f continues to be invoked, f itself will not be +called for N milliseconds. +""" + +from time import sleep +from typing import Any, Callable + + +def debounce(ms: int) -> Callable: + interval_seconds = ms / 1000 + + def decorate(f: Callable) -> Any: + def wrapped(*args, **kwargs): + print("waiting initiated...") + sleep(interval_seconds) + print("waiting over...") + + return f(*args, **kwargs) + + return wrapped + + return decorate + + +@debounce(3000) +def add_nums(x: int, y: int) -> int: + return x + y + + +if __name__ == "__main__": + print(add_nums(1, 1)) + print() + print(add_nums(1, 2)) + print() + print(add_nums(1, 3)) + print() + print(add_nums(1, 4)) diff --git a/Solutions/106.py b/Solutions/106.py new file mode 100644 index 0000000..530a344 --- /dev/null +++ b/Solutions/106.py @@ -0,0 +1,35 @@ +""" +Problem: + +Given an integer list where each number represents the number of hops you can make, +determine whether you can reach to the last index starting at index 0. + +For example, [2, 0, 1, 0] returns true while [1, 1, 0, 1] returns false. +""" + +from typing import List + + +def can_reach_end(arr: List[int]) -> bool: + length = len(arr) + curr_position, last_index = 0, length - 1 + while curr_position < length: + if curr_position == last_index: + return True + elif arr[curr_position] == 0: + return False + curr_position += arr[curr_position] + return False + + +if __name__ == "__main__": + print(can_reach_end([2, 0, 1, 0])) + print(can_reach_end([1, 1, 0, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/107.py b/Solutions/107.py new file mode 100644 index 0000000..c0c1a66 --- /dev/null +++ b/Solutions/107.py @@ -0,0 +1,57 @@ +""" +Problem: + +Print the nodes in a binary tree level-wise. For example, the following should print +1, 2, 3, 4, 5. + + 1 + / \ +2 3 + / \ + 4 5 +""" + +from typing import List + +from DataStructures.Queue import Queue +from DataStructures.Tree import BinaryTree, Node + + +def get_lvl_wise_nodes(tree: BinaryTree) -> List[Node]: + # using bfs to generate the list of nodes by level + if not tree.root: + return [] + + queue = Queue() + queue.enqueue(tree.root) + ans = [] + while not queue.is_empty(): + node = queue.dequeue() + if node.left is not None: + queue.enqueue(node.left) + if node.right is not None: + queue.enqueue(node.right) + ans.append(node.val) + return ans + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(1) + + tree.root.left = Node(2) + tree.root.right = Node(3) + + tree.root.right.left = Node(4) + tree.root.right.right = Node(5) + + print(f"Tree: {tree}") + print(f"Level wise result: {get_lvl_wise_nodes(tree)}") + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/108.py b/Solutions/108.py new file mode 100644 index 0000000..f198f5c --- /dev/null +++ b/Solutions/108.py @@ -0,0 +1,26 @@ +""" +Problem: + +Given two strings A and B, return whether or not A can be shifted some number of times +to get B. + +For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, +return false. +""" + + +def can_shift(A: str, B: str) -> bool: + return (A and B) and (len(A) == len(B)) and (B in A * 2) + + +if __name__ == "__main__": + print(can_shift("abcde", "cdeab")) + print(can_shift("abc", "acb")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/109.py b/Solutions/109.py new file mode 100644 index 0000000..93270e3 --- /dev/null +++ b/Solutions/109.py @@ -0,0 +1,35 @@ +""" +Problem: + +Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should +be swapped, the 3rd and 4th bit should be swapped, and so on. + +For example, 10101010 should be 01010101. 11100010 should be 11010001. + +Bonus: Can you do this in one line? +""" + + +def swap_bits(num: int) -> int: + # (left shift digits at odd position) BITWISE-OR (right shift digits at even + # position) + # NOTE: If the value of filter mask is placed in the expression, it reduces to one + # liner + filter_mask = 85 + return ((num & filter_mask) << 1) | ((num & (filter_mask << 1)) >> 1) + + +if __name__ == "__main__": + print("Swapped:", bin(swap_bits(0))) + print("Swapped:", bin(swap_bits(255))) + print("Swapped:", bin(swap_bits(210))) + print("Swapped:", bin(swap_bits(170))) + print("Swapped:", bin(swap_bits(226))) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/110.py b/Solutions/110.py new file mode 100644 index 0000000..8927440 --- /dev/null +++ b/Solutions/110.py @@ -0,0 +1,64 @@ +""" +Problem: + +Given a binary tree, return all paths from the root to leaves. + +For example, given the tree + + 1 + / \ + 2 3 + / \ + 4 5 +it should return [[1, 2], [1, 3, 4], [1, 3, 5]]. +""" + +from typing import List + +from DataStructures.Tree import BinaryTree, Node + + +def get_paths_helper(node: Node, paths: List[int], curr_path: List[int]) -> None: + if not node.left and not node.right: + # leaf node + curr_path.append(node.val) + paths.append([*curr_path]) + curr_path.pop() + return + # non-leaf node + curr_path.append(node.val) + if node.left: + get_paths_helper(node.left, paths, curr_path) + if node.right: + get_paths_helper(node.right, paths, curr_path) + curr_path.pop() + + +def get_paths(tree: BinaryTree): + if not tree.root: + return [] + paths = [] + get_paths_helper(tree.root, paths, []) + return paths + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(1) + + tree.root.left = Node(2) + tree.root.right = Node(3) + + tree.root.right.left = Node(4) + tree.root.right.right = Node(5) + + print(tree) + print(get_paths(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/111.py b/Solutions/111.py new file mode 100644 index 0000000..c84bc8f --- /dev/null +++ b/Solutions/111.py @@ -0,0 +1,61 @@ +""" +Problem: + +Given a word W and a string S, find all starting indices in S which are anagrams of W. + +For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4. +""" + +from typing import Dict, List + + +def get_char_frequency(string: str) -> Dict[str, int]: + freq = {} + for char in string: + if char not in freq: + freq[char] = 0 + freq[char] += 1 + return freq + + +def get_word_start_loc(word: str, string: str) -> List[int]: + word_len = len(word) + str_len = len(string) + char_needed_master = get_char_frequency(word) + char_needed = dict(char_needed_master) + curr = 0 + starting_indices = [] + # if the word is longer than the string, no anagram is possible + if (word_len > str_len) or (word_len == 0): + return [] + # generating the starting indices + while curr < str_len: + for i in range(curr, str_len): + if string[i] not in char_needed: + curr = i + char_needed = dict(char_needed_master) + break + elif string[i] in char_needed: + char_needed[string[i]] -= 1 + if char_needed[string[i]] == 0: + del char_needed[string[i]] + if char_needed == {}: + starting_indices.append(curr) + curr = i - 1 + char_needed = dict(char_needed_master) + break + curr += 1 + return starting_indices + + +if __name__ == "__main__": + print(get_word_start_loc("ab", "abxaba")) + print(get_word_start_loc("tac", "cataract")) + + +""" +SPECS: + +TIME COMPLEXITY: O(len(word) x len(string)) +SPACE COMPLEXITY: O(len(word)) +""" diff --git a/Solutions/112.py b/Solutions/112.py new file mode 100644 index 0000000..b1490b7 --- /dev/null +++ b/Solutions/112.py @@ -0,0 +1,99 @@ +""" +Problem: + +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the +tree. Assume that each node in the tree also has a pointer to its parent. + +According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined +between two nodes v and w as the lowest node in T that has both v and w as descendants +(where we allow a node to be a descendant of itself)." +""" + +from __future__ import annotations +from typing import Optional + +from DataStructures.Tree import BinaryTree + + +class Node: + def __init__(self, val: int, parent: Optional[Node] = None) -> None: + self.val = val + self.left = None + self.right = None + self.parent = parent + + def __eq__(self, other: Node) -> bool: + return self is other + + def __hash__(self) -> int: + return hash(self.val) + + def __repr__(self) -> str: + return self.str_representation() + + def str_representation(self) -> str: + if self.right is None and self.left is None: + return f"('{self.val}')" + elif self.left is not None and self.right is None: + return f"({self.left.str_representation()}, '{self.val}', None)" + elif self.left is not None and self.right is not None: + return ( + f"({self.left.str_representation()}," + + f" '{self.val}', {self.right.str_representation()})" + ) + elif self.left is None and self.right is not None: + return f"(None, '{self.val}', {self.right.str_representation()})" + + +def get_lca(node1: Node, node2: Node) -> Optional[Node]: + node1_ancestors = set() + node = node1 + while node: + node1_ancestors.add(node) + node = node.parent + node = node2 + while node: + if node in node1_ancestors: + return node + node = node.parent + return None + + +if __name__ == "__main__": + tree = BinaryTree() + + a = Node(1) + b = Node(2, parent=a) + c = Node(3, parent=a) + d = Node(4, parent=b) + e = Node(5, parent=b) + f = Node(6, parent=c) + g = Node(7, parent=c) + + tree.root = a + + tree.root.left = b + tree.root.right = c + + tree.root.left.left = d + tree.root.left.right = e + + tree.root.right.left = f + tree.root.right.right = g + + print(tree) + + print(get_lca(f, g)) + print(get_lca(a, g)) + print(get_lca(d, g)) + print(get_lca(a, c)) + print(get_lca(e, b)) + print(get_lca(a, Node(8))) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/113.py b/Solutions/113.py new file mode 100644 index 0000000..642f076 --- /dev/null +++ b/Solutions/113.py @@ -0,0 +1,27 @@ +""" +Problem: + +Given a string of words delimited by spaces, reverse the words in string. For example, +given "hello world here", return "here world hello" + +Follow-up: given a mutable string representation, can you perform this operation +in-place? +""" + + +def reverse_words_in_string(string: str) -> str: + words = string.split() + words.reverse() + return " ".join(words) + + +if __name__ == "__main__": + print(reverse_words_in_string("hello world here")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/114.py b/Solutions/114.py new file mode 100644 index 0000000..ee64044 --- /dev/null +++ b/Solutions/114.py @@ -0,0 +1,83 @@ +""" +Problem: + +Given a string and a set of delimiters, reverse the words in the string while +maintaining the relative order of the delimiters. For example, given +"hello/world:here", return "here/world:hello" + +Follow-up: Does your solution work for the following cases: "hello/world:here/", +"hello//world:here" +""" + +from typing import Set + + +def rev_words(string: str, delimiters: Set[str]) -> str: + if len(string) == 0: + return string + + words = [] + delims = [] + flag_beg = string[0] in delimiters + flag_delim = False + curr_str = "" + # generating the words and delimiters + for char in string: + if char in delimiters: + if flag_delim: + curr_str += char + else: + if curr_str: + words.append(curr_str) + curr_str = char + flag_delim = True + else: + if flag_delim: + flag_delim = False + delims.append(curr_str) + curr_str = char + else: + curr_str += char + # check if last character is a delimiter + if flag_delim: + delims.append(curr_str) + else: + words.append(curr_str) + + words = words[::-1] + words.append("") + delims.append("") + len_words = len(words) + len_delims = len(delims) + i, j = 0, 0 + reversed_string = "" + # generating the reversed string + if flag_beg: + j = 1 + reversed_string += delims[0] + while i < len_words or j < len_delims: + try: + reversed_string += words[i] + reversed_string += delims[j] + i += 1 + j += 1 + except IndexError: + break + return reversed_string + + +if __name__ == "__main__": + print(rev_words("hello/world:here", {":", "/"})) + print(rev_words("here/world:hello", {":", "/"})) + print(rev_words("hello/world:here/", {":", "/"})) + print(rev_words("hello//world:here", {":", "/"})) + print(rev_words("hello", {":", "/"})) + print(rev_words("//:", {":", "/"})) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/115.py b/Solutions/115.py new file mode 100644 index 0000000..6316c38 --- /dev/null +++ b/Solutions/115.py @@ -0,0 +1,67 @@ +""" +Problem: + +Given two non-empty binary trees s and t, check whether tree t has exactly the same +structure and node values with a subtree of s. A subtree of s is a tree consists of a +node in s and all of this node's descendants. The tree s could also be considered as a +subtree of itself. +""" + +from DataStructures.Tree import BinaryTree, Node + + +def is_equal(node1: Node, node2: Node) -> bool: + if (not node1) and (not node2): + return True + if (not node1) or (not node2): + return False + if node1.val != node2.val: + return False + return is_equal(node1.left, node2.left) and is_equal(node1.right, node2.right) + + +def find_helper(sub_tree1: Node, sub_tree2: Node) -> bool: + if is_equal(sub_tree1, sub_tree2): + return True + # if the subtree is not same, the children are checked + if sub_tree1.left and find_helper(sub_tree1.left, sub_tree2): + return True + if sub_tree1.right and find_helper(sub_tree1.right, sub_tree2): + return True + return False + + +def get_match(s: BinaryTree, t: BinaryTree) -> bool: + if s.root and t.root: + return find_helper(s.root, t.root) + return False + + +if __name__ == "__main__": + tree1 = BinaryTree() + tree1.root = Node(0) + tree1.root.left = Node(1) + tree1.root.right = Node(2) + tree1.root.right.left = Node(3) + tree1.root.right.right = Node(4) + + tree2 = BinaryTree() + tree2.root = Node(2) + tree2.root.left = Node(3) + tree2.root.right = Node(4) + + tree3 = BinaryTree() + tree3.root = Node(2) + tree3.root.left = Node(3) + tree3.root.right = Node(5) + + print(get_match(tree1, tree2)) + print(get_match(tree1, tree3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/116.py b/Solutions/116.py new file mode 100644 index 0000000..d4ee7b3 --- /dev/null +++ b/Solutions/116.py @@ -0,0 +1,57 @@ +""" +Problem: + +Generate a finite, but an arbitrarily large binary tree quickly in O(1). + +That is, generate() should return a tree whose size is unbounded but finite. +""" + +from random import random, randint + +import matplotlib.pyplot as plt + +from DataStructures.Tree import BinaryTree, Node + + +def generate_helper( + node: Node, + probability_add_children: float = 0.5, + probability_add_branch: float = 0.5, +) -> None: + if random() > probability_add_children: + return + # generating the left branch + if random() < probability_add_branch: + node.left = Node(randint(1, 1000)) + generate_helper(node.left, probability_add_children, probability_add_branch) + # generating the right branch + if random() < probability_add_branch: + node.right = Node(randint(1, 1000)) + generate_helper(node.right, probability_add_children, probability_add_branch) + + +def generate() -> BinaryTree: + tree = BinaryTree() + tree.root = Node(randint(1, 1000)) + generate_helper(tree.root, 0.7, 0.7) + # suggestion: don't use higher values for probability, it will lead to recursion + # error + return tree + + +if __name__ == "__main__": + tree_length_list = [] + for i in range(1000): + tree_length_list.append(len(generate())) + plt.hist(tree_length_list) + plt.show() + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n nodes cannot be generated in O(1) time, but since n is finite it may be considered +constant] +""" diff --git a/Solutions/117.py b/Solutions/117.py new file mode 100644 index 0000000..a42ecd8 --- /dev/null +++ b/Solutions/117.py @@ -0,0 +1,81 @@ +""" +Problem: + +Given a binary tree, return the level of the tree with minimum sum. +""" + +from sys import maxsize + +from DataStructures.Queue import Queue +from DataStructures.Tree import BinaryTree, Node + + +def get_level_min_sum(tree: BinaryTree) -> int: + if not tree.root: + return 0 + # the levels are delimited in the queue by None + queue = Queue() + queue.enqueue(tree.root) + queue.enqueue(None) + + min_level_sum = maxsize + curr_level_sum = 0 + while not queue.is_empty(): + node = queue.dequeue() + if node is not None: + if node.left: + queue.enqueue(node.left) + if node.right: + queue.enqueue(node.right) + curr_level_sum += node.val + else: + min_level_sum = min(curr_level_sum, min_level_sum) + if len(queue) > 0: + queue.enqueue(None) + curr_level_sum = 0 + return min_level_sum + + +if __name__ == "__main__": + a = Node(100) + b = Node(200) + c = Node(300) + d = Node(400) + e = Node(500) + f = Node(600) + g = Node(700) + h = Node(800) + + a.left = b + a.right = c + + b.left = d + b.right = e + + c.left = f + c.right = g + + d.right = h + + tree = BinaryTree() + tree.root = a + + print(tree) + print(get_level_min_sum(tree)) + a.val = 1000 + print(tree) + print(get_level_min_sum(tree)) + b.val = 1500 + print(tree) + print(get_level_min_sum(tree)) + h.val = 2000 + print(tree) + print(get_level_min_sum(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/118.py b/Solutions/118.py new file mode 100644 index 0000000..d704648 --- /dev/null +++ b/Solutions/118.py @@ -0,0 +1,61 @@ +""" +Problem: + +Given a sorted list of integers, square the elements and give the output in sorted +order. + +For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81]. +""" + +from typing import List + +Array = List[int] + + +def merge_sorted_lists(arr1: Array, arr2: Array) -> Array: + ptr1, length1 = 0, len(arr1) + ptr2, length2 = 0, len(arr2) + merged_sorted_array = [] + # generating merged sorted list + while ptr1 < length1 and ptr2 < length2: + if arr1[ptr1] < arr2[ptr2]: + merged_sorted_array.append(arr1[ptr1]) + ptr1 += 1 + else: + merged_sorted_array.append(arr2[ptr2]) + ptr2 += 1 + merged_sorted_array.extend(arr1[ptr1:]) + merged_sorted_array.extend(arr2[ptr2:]) + return merged_sorted_array + + +def sort_squared_elements(arr: Array) -> Array: + last_negative_position = 0 + length = len(arr) + for i in range(length): + if arr[i] > 0: + last_negative_position = i + break + else: + last_negative_position = length + + negative_part = [elem * elem for elem in arr[:last_negative_position]][::-1] + positive_part = [elem * elem for elem in arr[last_negative_position:]] + return merge_sorted_lists(positive_part, negative_part) + + +if __name__ == "__main__": + print(sort_squared_elements([])) + print(sort_squared_elements([0])) + print(sort_squared_elements([-1, 1])) + print(sort_squared_elements([0, 2, 3])) + print(sort_squared_elements([-9, -2, 0])) + print(sort_squared_elements([-9, -2, 0, 2, 3])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/119.py b/Solutions/119.py new file mode 100644 index 0000000..b8557a5 --- /dev/null +++ b/Solutions/119.py @@ -0,0 +1,51 @@ +""" +Problem: + +Given a set of closed intervals, find the smallest set of numbers that covers all the +intervals. If there are multiple smallest sets, return any of them. + +For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of numbers +that covers all these intervals is {3, 6}. +""" + +from typing import List, Optional, Tuple + + +def get_spanning_interval(intervals: List[List[int]]) -> Optional[Tuple]: + if not intervals: + return + start = intervals[0][1] + end = start + pos = 1 + # updating start + for interval in intervals[1:]: + interval_start, interval_end = interval + if interval_start < start and interval_end < start: + start = interval_end + pos += 1 + else: + break + # updating end + for interval in intervals[pos:]: + interval_start, _ = interval + if interval_start > end: + end = interval_start + return start, end + + +if __name__ == "__main__": + print(get_spanning_interval([[0, 3]])) + print(get_spanning_interval([[0, 3], [2, 6]])) + print(get_spanning_interval([[0, 3], [2, 6], [3, 4]])) + print(get_spanning_interval([[0, 3], [2, 6], [3, 4], [6, 7]])) + print(get_spanning_interval([[0, 3], [2, 6], [3, 4], [6, 9]])) + print(get_spanning_interval([[0, 3], [2, 6], [3, 4], [6, 100]])) + print(get_spanning_interval([[0, 4], [1, 2], [5, 6]])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/120.py b/Solutions/120.py new file mode 100644 index 0000000..62a7092 --- /dev/null +++ b/Solutions/120.py @@ -0,0 +1,51 @@ +""" +Problem: + +Implement the singleton pattern with a twist. First, instead of storing one instance, +store two instances. And in every even call of getInstance(), return the first instance +and in every odd call of getInstance(), return the second instance. +""" + +from __future__ import annotations + + +class Twisted_Singleton: + _instance1, _instance2 = None, None + _is_odd = True + _is_initialized = False + + def __init__(self, instance_num: int) -> None: + self.instance_num = instance_num + + def __repr__(self) -> str: + return str(self.instance_num) + + @staticmethod + def initialize() -> None: + if not Twisted_Singleton._is_initialized: + Twisted_Singleton._instance1 = Twisted_Singleton(1) + Twisted_Singleton._instance2 = Twisted_Singleton(2) + Twisted_Singleton._is_initialized = True + + @staticmethod + def getInstance() -> Twisted_Singleton: + if not Twisted_Singleton._is_initialized: + Twisted_Singleton.initialize() + + if Twisted_Singleton._is_odd: + instance = Twisted_Singleton._instance1 + else: + instance = Twisted_Singleton._instance2 + Twisted_Singleton._is_odd = not Twisted_Singleton._is_odd + return instance + + +if __name__ == "__main__": + Twisted_Singleton.initialize() + + print(Twisted_Singleton.getInstance()) + print(Twisted_Singleton.getInstance()) + print(Twisted_Singleton.getInstance()) + print(Twisted_Singleton.getInstance()) + print(Twisted_Singleton.getInstance()) + print(Twisted_Singleton.getInstance()) diff --git a/Solutions/121.py b/Solutions/121.py new file mode 100644 index 0000000..832ef80 --- /dev/null +++ b/Solutions/121.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given a string which we can delete at most k, return whether you can make a palindrome. + +For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get +'waterretaw'. +""" + + +def is_palindrome(string: str) -> bool: + return string == string[::-1] + + +def can_make_palindrome(string: str, k: int) -> bool: + if is_palindrome(string): + return True + if not k: + return False + # checking all possible combinations of the string + for i in range(len(string)): + if can_make_palindrome(string[:i] + string[i + 1 :], k - 1): + return True + return False + + +if __name__ == "__main__": + print(can_make_palindrome("a", 0)) + print(can_make_palindrome("aaa", 2)) + print(can_make_palindrome("add", 0)) + print(can_make_palindrome("waterrfetawx", 3)) + print(can_make_palindrome("waterrfetawx", 2)) + print(can_make_palindrome("waterrfetawx", 1)) + print(can_make_palindrome("malayalam", 0)) + print(can_make_palindrome("malayalam", 1)) + print(can_make_palindrome("asdf", 5)) + print(can_make_palindrome("asdf", 2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/122.py b/Solutions/122.py new file mode 100644 index 0000000..f342528 --- /dev/null +++ b/Solutions/122.py @@ -0,0 +1,50 @@ +""" +Problem: + +You are given a 2-d matrix where each cell represents number of coins in that cell. +Assuming we start at matrix[0][0], and can only move right or down, find the maximum +number of coins you can collect by the bottom right corner. + +For example, in this matrix + +0 3 1 1 +2 0 0 4 +1 5 3 1 +The most we can collect is 0 + 2 + 1 + 5 + 3 + 1 = 12 coins. +""" + +from typing import List + + +def get_max_coins(matrix: List[List[int]]) -> int: + n = len(matrix) + m = len(matrix[0]) + # generating the maximum number of coins using dynamic programming + for i in range(1, n): + for j in range(1, m): + matrix[i][j] += max(matrix[i - 1][j], matrix[i][j - 1]) + return matrix[n - 1][m - 1] + + +if __name__ == "__main__": + matrix = [ + [0, 3, 1, 1], + [2, 0, 0, 4], + [1, 5, 3, 1] + ] + print(get_max_coins(matrix)) + + matrix = [ + [0, 3, 1, 1], + [2, 8, 9, 4], + [1, 5, 3, 1] + ] + print(get_max_coins(matrix)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(1) [modifying the matrix in place] +""" diff --git a/Solutions/123.py b/Solutions/123.py new file mode 100644 index 0000000..f3038bb --- /dev/null +++ b/Solutions/123.py @@ -0,0 +1,86 @@ +""" +Problem: + +Given a string, return whether it represents a number. Here are the different kinds of +numbers: + +"10", a positive integer +"-10", a negative integer +"10.1", a positive real number +"-10.1", a negative real number +"1e5", a number in scientific notation +And here are examples of non-numbers: + +"a" +"x 1" +"a -2" +"-" +""" + + +def check_valid_number_representation(string: str) -> bool: + is_valid = True + has_number = False + num_negatives, num_points, num_e = 0, 0, 0 + + for char in string: + if not (char.isdigit()): + if char == "-": + if num_negatives >= 1: + # if the string contains an 'e', 2 '-'s are allowed (for mantissa + # and exponent) + if num_negatives == 1 and num_e == 1: + num_negatives += 1 + continue + is_valid = False + break + num_negatives += 1 + elif char == ".": + if num_points >= 1: + # if the string contains an 'e', 2 '.'s are allowed (for mantissa + # and exponent) + if num_points == 1 and num_e == 1: + num_points += 1 + continue + is_valid = False + break + num_points += 1 + elif char == "e": + # a number can have only 1 'e' + if num_e >= 1: + is_valid = False + break + num_e += 1 + elif char == " ": + # spaces are ignored + pass + else: + # any other character makes the number invalid + is_valid = False + break + else: + # current character is a number + has_number = True + return is_valid and has_number + + +if __name__ == "__main__": + print(check_valid_number_representation("10")) + print(check_valid_number_representation("-10")) + print(check_valid_number_representation("10.1")) + print(check_valid_number_representation("-10.1")) + print(check_valid_number_representation("1e5")) + print(check_valid_number_representation("1e-5")) + print(check_valid_number_representation("-1.6 e -5.2")) + print(check_valid_number_representation("a")) + print(check_valid_number_representation("x 1")) + print(check_valid_number_representation("a -2")) + print(check_valid_number_representation("-")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/124.py b/Solutions/124.py new file mode 100644 index 0000000..dc1b70c --- /dev/null +++ b/Solutions/124.py @@ -0,0 +1,36 @@ +""" +Problem: + +You have 100 fair coins and you flip them all at the same time. Any that come up tails +you set aside. The ones that come up heads you flip again. How many rounds do you +expect to play before only one coin remains? + +Write a function that, given 'n', returns the number of rounds you'd expect to play +until one coin remains. +""" + +from math import log2, ceil + + +def expectation(n: int) -> int: + # since the number of coins is expected (mean) to be halved on each toss, we use + # log2 + # ceil is used to round it off to the next larger integer as number of tosses + # cannot be a fraction + return ceil(log2(n + 1)) + + +if __name__ == "__main__": + print(expectation(0)) + print(expectation(1)) + print(expectation(2)) + print(expectation(100)) + print(expectation(200)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/125.py b/Solutions/125.py new file mode 100644 index 0000000..f9f6de4 --- /dev/null +++ b/Solutions/125.py @@ -0,0 +1,76 @@ +""" +Problem: + +Given the root of a binary search tree, and a target K, return two nodes in the tree +whose sum equals K. + +For example, given the following tree and K of 20 + + 10 + / \ + 5 15 + / \ + 11 15 +Return the nodes 5 and 15. +""" + +from typing import Generator, Optional, Tuple + +from DataStructures.Tree import BinaryTree, Node + + +def inorder_traverse_generator(node: Node) -> Generator[int, None, None]: + if node.left: + for val in inorder_traverse_generator(node.left): + yield val + yield node.val + if node.right: + for val in inorder_traverse_generator(node.right): + yield val + + +def get_inorder_traverse_generator( + tree: BinaryTree, +) -> Optional[Generator[int, None, None]]: + if tree.root: + return inorder_traverse_generator(tree.root) + return None + + +def get_target_sum(tree: BinaryTree, k: int) -> Tuple[Optional[int], Optional[int]]: + generator = get_inorder_traverse_generator(tree) + if not generator: + return None, None + # checking for the target sum + previous = set() + for val in generator: + if (k - val) in previous: + return (k - val), val + previous.add(val) + return None, None + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(10) + + tree.root.left = Node(5) + tree.root.right = Node(15) + + tree.root.right.left = Node(11) + tree.root.right.right = Node(15) + + print(get_target_sum(tree, 15)) + print(get_target_sum(tree, 20)) + print(get_target_sum(tree, 21)) + print(get_target_sum(tree, 25)) + print(get_target_sum(tree, 30)) + print(get_target_sum(tree, 35)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/126.py b/Solutions/126.py new file mode 100644 index 0000000..9d3451c --- /dev/null +++ b/Solutions/126.py @@ -0,0 +1,42 @@ +""" +Problem: + +Write a function that rotates a list by k elements. For example, [1, 2, 3, 4, 5, 6] +rotated by two becomes [3, 4, 5, 6, 1, 2]. Try solving this without creating a copy of +the list. How many swap or move operations do you need? +""" + +from typing import List + + +def rotate_list_once(arr: List[int], length: int) -> None: + # updates the list inplace + first_elem = arr[0] + for i in range(length - 1): + arr[i] = arr[i + 1] + arr[length - 1] = first_elem + + +def rotate_list(arr: List[int], k: int) -> List[int]: + length = len(arr) + k = k % length + for _ in range(k): + rotate_list_once(arr, length) + return arr + + +if __name__ == "__main__": + print(rotate_list([1, 2, 3, 4, 5, 6], 0)) + print(rotate_list([1, 2, 3, 4, 5, 6], 2)) + print(rotate_list([1, 2, 3, 4, 5, 6], 4)) + print(rotate_list([1, 2, 3, 4, 5, 6], 6)) + print(rotate_list([1, 2, 3, 4, 5, 6], 10)) + print(rotate_list([1, 2, 3, 4, 5, 6], 1_000_000_000)) + + +""" +SPECS: + +TIME COMPLEXITY: O(k x n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/127.py b/Solutions/127.py new file mode 100644 index 0000000..e4cbcf9 --- /dev/null +++ b/Solutions/127.py @@ -0,0 +1,88 @@ +""" +Problem: + +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. + +For example, the following linked list: + +1 -> 2 -> 3 -> 4 -> 5 is the number 54321. + +Given two linked lists in this format, return their sum in the same linked list format. + +For example, given + +9 -> 9 5 -> 2 return 124 (99 + 25) as: + +4 -> 2 -> 1 +""" + +from DataStructures.LinkedList import LinkedList, Node + + +def add_linked_lists(ll1: LinkedList, ll2: LinkedList) -> LinkedList: + sum_linked_list = LinkedList() + pos1, pos2 = ll1.head, ll2.head + carry, curr_position_sum = 0, 0 + # generating the sum of the linked lists + while pos1 or pos2: + if pos1 == None: + curr_position_sum = pos2.val + carry + if curr_position_sum >= 10: + carry, curr_position_sum = 1, curr_position_sum - 10 + else: + carry = 0 + elif pos2 == None: + curr_position_sum = pos1.val + carry + if curr_position_sum >= 10: + carry, curr_position_sum = 1, curr_position_sum - 10 + else: + carry = 0 + else: + curr_position_sum = pos2.val + pos1.val + carry + if curr_position_sum >= 10: + carry, curr_position_sum = 1, curr_position_sum - 10 + else: + carry = 0 + sum_linked_list.add(curr_position_sum) + # moving to the next value + if pos1: + pos1 = pos1.next + if pos2: + pos2 = pos2.next + if carry == 1: + sum_linked_list.add(1) + return sum_linked_list + + +def create_linked_list(val: int) -> LinkedList: + LL = LinkedList() + while val > 0: + LL.add(val % 10) + val = val // 10 + return LL + + +if __name__ == "__main__": + LL1 = create_linked_list(99) + LL2 = create_linked_list(25) + + print(LL1) + print(LL2) + print(add_linked_lists(LL1, LL2)) + print() + + LL1 = create_linked_list(9) + LL2 = create_linked_list(250) + + print(LL1) + print(LL2) + print(add_linked_lists(LL1, LL2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/128.py b/Solutions/128.py new file mode 100644 index 0000000..2f71d84 --- /dev/null +++ b/Solutions/128.py @@ -0,0 +1,76 @@ +""" +Problem: + +All the disks start off on the first rod in a stack. They are ordered by size, with the +largest disk on the bottom and the smallest one at the top. + +The goal of this puzzle is to move all the disks from the first rod to the last rod +while following these rules: + +You can only move one disk at a time. +A move consists of taking the uppermost disk from one of the stacks and placing it on +top of another stack. +You cannot place a larger disk on top of a smaller disk. +Write a function that prints out all the steps necessary to complete the Tower of Hanoi. +You should assume that the rods are numbered, with the first rod being 1, the second +(auxiliary) rod being 2, and the last (goal) rod being 3. + +For example, with n = 3, we can do this in 7 moves: + +Move 1 to 3 +Move 1 to 2 +Move 3 to 2 +Move 1 to 3 +Move 2 to 1 +Move 2 to 3 +Move 1 to 3 +""" + +from typing import Optional + + +def towers_of_hanoi( + n: int, + start_rod: Optional[str] = None, + aux_rod: Optional[str] = None, + end_rod: Optional[str] = None, +) -> None: + # initializing the names for the rods [using different convention from the one + # mentioned in the question] + if not start_rod: + start_rod = "start_rod" + print( + f"\nTower of Hanoi for {n} Disks ========================================" + ) + if not aux_rod: + aux_rod = "aux_rod" + if not end_rod: + end_rod = "end_rod" + # if the number of disks left to move is 1, its shifted [base case for recursion] + if n == 1: + print(f"Move disk 1 from {start_rod} to {end_rod}") + return + + # moving the top disk of the start rod to the proper position in the auxilary rod + # using the end rod as buffer + towers_of_hanoi(n - 1, start_rod, end_rod, aux_rod) + # moving the top disk from the start rod to the end rod + print(f"Move disk {n} from {start_rod} to {end_rod}") + # moving the top disk of the auxilary rod to the proper position in the end rod + # using the start rod as buffer + towers_of_hanoi(n - 1, aux_rod, start_rod, end_rod) + + +if __name__ == "__main__": + towers_of_hanoi(3) + towers_of_hanoi(4) + towers_of_hanoi(5) + towers_of_hanoi(6) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/129.py b/Solutions/129.py new file mode 100644 index 0000000..a776037 --- /dev/null +++ b/Solutions/129.py @@ -0,0 +1,40 @@ +""" +Problem: + +Given a real number n, find the square root of n. For example, given n = 9, return 3. +""" + +TOLERENCE = 10 ** (-6) + + +def almost_equal(num1: float, num2: float) -> bool: + return num1 - TOLERENCE < num2 < num1 + TOLERENCE + + +def get_sqrt(num: int) -> float: + # using binary search to get the sqaure-root + high, low = num, 0 + while True: + mid = (high + low) / 2 + mid_square = mid * mid + if almost_equal(mid_square, num): + return round(mid, 6) + elif mid_square < num: + low = mid + 1 + else: + high = mid - 1 + + +if __name__ == "__main__": + print(get_sqrt(100)) + print(get_sqrt(9)) + print(get_sqrt(3)) + print(get_sqrt(2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/130.py b/Solutions/130.py new file mode 100644 index 0000000..c457cb8 --- /dev/null +++ b/Solutions/130.py @@ -0,0 +1,77 @@ +""" +Problem: + +Given an array of numbers representing the stock prices of a company in chronological +order and an integer k, return the maximum profit you can make from k buys and sells. +You must buy the stock before you can sell it, and you must sell the stock before you +can buy it again. + +For example, given k = 2 and the array [5, 2, 4, 0, 1], you should return 3. +""" + +from typing import List + + +def get_max_profit_helper( + arr: List[int], + curr_index: int, + curr_profit: int, + buys_left: int, + sells_left: int, + length: int, +) -> int: + # if the end of the array is reached or no more sells can be performed current + # profit is returned (base case for recursion) + if curr_index == length or sells_left == 0: + return curr_profit + # if the number of 'buys' and 'sells' left are equal, the stock needs to be bought + if buys_left == sells_left: + return max( + # wait for a different deal + get_max_profit_helper( + arr, curr_index + 1, curr_profit, buys_left, sells_left, length + ), + # buy at the current price + get_max_profit_helper( + arr, + curr_index + 1, + curr_profit - arr[curr_index], + buys_left - 1, + sells_left, + length, + ), + ) + # if the number of 'buys' and 'sells' left are inequal, the stock needs to be sold + return max( + # wait and hold for selling at a different price + get_max_profit_helper( + arr, curr_index + 1, curr_profit, buys_left, sells_left, length, + ), + # sell at the current price + get_max_profit_helper( + arr, + curr_index + 1, + curr_profit + arr[curr_index], + buys_left, + sells_left - 1, + length, + ), + ) + + +def get_max_profit(arr: List[int], k: int) -> int: + return get_max_profit_helper(arr, 0, 0, k, k, len(arr)) + + +if __name__ == "__main__": + print(get_max_profit([5, 2, 4, 0, 1], 2)) + print(get_max_profit([5, 2, 4], 2)) + print(get_max_profit([5, 2, 4], 1)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/131.py b/Solutions/131.py new file mode 100644 index 0000000..1e7db39 --- /dev/null +++ b/Solutions/131.py @@ -0,0 +1,101 @@ +""" +Problem: + +Given the head to a singly linked list, where each node also has a 'random' pointer +that points to anywhere in the linked list, deep clone the list. +""" + +from DataStructures.LinkedList import LinkedList, Node + + +def rand_join(ll: LinkedList, pos1: int, pos2: int) -> None: + pos_source = ll.head + pos_dest = ll.head + try: + # moving the pointers to the required position + for _ in range(pos1): + pos_source = pos_source.next + for _ in range(pos2): + pos_dest = pos_dest.next + # setting the random pointer + pos_source.random_ptr = pos_dest + except: + raise IndexError("Given position is out of the Linked List") + + +def clone(ll: LinkedList) -> LinkedList: + clone_head = ll.head + pos1 = ll.head + pos2 = ll.head.next + # duplicating all elements (by value in the linked list) + # [a -> b -> c becomes a -> a -> b -> b -> c -> c] + for _ in range(ll.length): + pos1.next = Node(pos1.val) + pos1 = pos1.next + pos1.next = pos2 + pos1 = pos1.next + if pos2 is None: + break + pos2 = pos2.next + # setting the clone head to the proper position + clone_head = clone_head.next + pos1 = ll.head + # setting the random pointer of the cloned linked list + # (every 2nd element in the new linked list: a -> [a] -> b -> [b] -> c -> [c]) + for _ in range(ll.length - 1): + pos1.next.random_ptr = pos1.random_ptr + pos1 = pos1.next.next + # reverting the linked list to its original form + pos1 = ll.head + pos2 = ll.head.next + for _ in range(ll.length - 1): + pos1.next = pos2.next + pos2.next = pos2.next.next + pos1 = pos1.next + if pos2.next == None: + break + pos2 = pos2.next + # creating the cloned linked list from the generated nodes + cloned_LL = LinkedList() + cloned_LL.head = clone_head + cloned_LL.length = ll.length + cloned_LL.rear = pos2 + return cloned_LL + + +# adding the random pointer to Node class +setattr(Node, "random_ptr", None) + +if __name__ == "__main__": + LL = LinkedList() + + LL.add(1) + LL.add(2) + LL.add(3) + LL.add(4) + + rand_join(LL, 0, 2) + rand_join(LL, 2, 0) + rand_join(LL, 1, 3) + + print("Original List:", LL) + + LL_clone = clone(LL) + + print("Cloned List:", LL_clone) + + # adding different elements to show that the clone is a deep copy + LL.add(100) + LL_clone.add(5) + + print("\nOriginal List:", LL) + + print("Cloned List:", LL_clone) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/132.py b/Solutions/132.py new file mode 100644 index 0000000..80272bb --- /dev/null +++ b/Solutions/132.py @@ -0,0 +1,119 @@ +""" +Problem: + +Design and implement a HitCounter class that keeps track of requests (or hits). It +should support the following operations: + +* record(timestamp): records a hit that happened at timestamp +* total(): returns the total number of hits recorded +* range(lower, upper): returns the number of hits that occurred between timestamps lower + and upper (inclusive) +Follow-up: What if our system has limited memory? +""" + +from DataStructures.LinkedList import Node, LinkedList + + +def add_node_sorted(ll: LinkedList, val: int) -> None: + ll.length += 1 + if not ll.head: + ll.head = Node(val) + ll.rear = ll.head + elif val > ll.rear.val: + ll.rear.next = Node(val) + ll.rear = ll.rear.next + else: + pos = ll.head + while pos.val < val: + pos = pos.next + temp = pos.val + pos.val = val + new_node = Node(temp) + new_node.next = pos.next + pos.next = new_node + if pos == ll.rear: + ll.rear = new_node + + +def get_number_of_nodes_in_range(ll: LinkedList, start: int, stop: int) -> int: + if not ll.head: + return 0 + + pos = ll.head + num = 0 + while pos and pos.val < start: + pos = pos.next + if not pos: + return 0 + while pos and pos.val <= stop: + pos = pos.next + num += 1 + return num + + +class HitCounter: + def __init__(self) -> None: + self.List = LinkedList() + self.start = None + self.end = None + + def record(self, timestamp: int) -> None: + add_node_sorted(self.List, timestamp) + # keeping track of the smallest and largest timestamp + if not self.start: + self.start = timestamp + self.end = timestamp + elif timestamp < self.start: + self.start = timestamp + elif timestamp > self.end: + self.end = timestamp + + def total(self) -> int: + return len(self.List) + + def range(self, lower: int, upper: int) -> int: + if upper < self.start or lower > self.end: + return 0 + return get_number_of_nodes_in_range(self.List, lower, upper) + + def __repr__(self): + return str(self.List) + + +if __name__ == "__main__": + hc = HitCounter() + + time1 = 1 + time2 = 10 + time3 = 20 + + print(hc.total()) + print(hc) + print() + + hc.record(time2) + + print(hc.total()) + print(hc) + print("Number in range:") + print(hc.range(5, 15)) + print(hc.range(10, 15)) + print() + + hc.record(time1) + + print(hc.total()) + print(hc) + print("Number in range:") + print(hc.range(5, 15)) + print(hc.range(12, 15)) + print() + + hc.record(time3) + + print(hc.total()) + print(hc) + print("Number in range:") + print(hc.range(5, 15)) + print(hc.range(0, 25)) + print() diff --git a/Solutions/134.py b/Solutions/134.py new file mode 100644 index 0000000..d794947 --- /dev/null +++ b/Solutions/134.py @@ -0,0 +1,65 @@ +""" +Problem: + +You have a large array with most of the elements as zero. + +Use a more space-efficient data structure, SparseArray, that implements the same +interface: + +init(arr, size): initialize with the original large array and size. +set(i, val): updates index at i with val. +get(i): gets the value at index i. +""" + +from typing import List + + +class SparseArray: + def __init__(self, arr: List[int], size: int) -> None: + self.arr = {} + self.size = size + for index, val in enumerate(arr): + if val != 0: + self.arr[index] = val + + def __repr__(self) -> str: + string = "" + for pos in range(self.size): + if pos in self.arr: + string += f"{self.arr[pos]}, " + else: + string += "0, " + return "[" + string.rstrip(" ,") + "]" + + def set(self, pos: int, val: int) -> int: + if pos > self.size: + raise IndexError + if val == 0: + if pos in self.arr: + del self.arr[pos] + else: + self.arr[pos] = val + + def get(self, pos: int) -> int: + if pos > self.size: + raise IndexError + if pos in self.arr: + return self.arr[pos] + return 0 + + +if __name__ == "__main__": + arr = SparseArray([1, 0, 0, 0, 3, 0, 2, 0], 8) + + print(arr) + + print(arr.get(0)) + print(arr.get(2)) + arr.set(2, 4) + print(arr.get(2)) + arr.set(4, 1) + print(arr.get(4)) + arr.set(0, 0) + print(arr.get(0)) + + print(arr) diff --git a/Solutions/135.py b/Solutions/135.py new file mode 100644 index 0000000..2637a91 --- /dev/null +++ b/Solutions/135.py @@ -0,0 +1,72 @@ +""" +Problem: + +Given a binary tree, find a minimum path sum from root to a leaf. + +For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15. + + 10 + / \ +5 5 + \ \ + 2 1 + / + -1 +""" + +from typing import List, Tuple + +from DataStructures.Tree import BinaryTree, Node + + +def minimum_path_sum_helper(node: Node) -> Tuple[int, List[int]]: + left_sum, left = None, None + right_sum, right = None, None + if node.left: + left_sum, left = minimum_path_sum_helper(node.left) + if node.right: + right_sum, right = minimum_path_sum_helper(node.right) + # generating the minimum path sum + if not left and not right: + return node.val, [node.val] + elif left and not right: + return (left_sum + node.val), left + [node.val] + elif right and not left: + return (right_sum + node.val), right + [node.val] + return min( + ((left_sum + node.val), left + [node.val]), + ((right_sum + node.val), right + [node.val]), + key=lambda x: x[0], + ) + + +def minimum_path_sum(tree: BinaryTree) -> List[int]: + if not tree.root: + raise ValueError("Empty Tree") + _, path = minimum_path_sum_helper(tree.root) + return path[::-1] + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(10) + + tree.root.left = Node(5) + tree.root.right = Node(5) + + tree.root.left.right = Node(2) + + tree.root.right.right = Node(1) + + tree.root.right.right.left = Node(-1) + + print(tree) + print(minimum_path_sum(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/136.py b/Solutions/136.py new file mode 100644 index 0000000..c644738 --- /dev/null +++ b/Solutions/136.py @@ -0,0 +1,127 @@ +""" +Problem: + +Given an N by M matrix consisting only of 1's and 0's, find the largest rectangle +containing only 1's and return its area. + +For example, given the following matrix: + +[[1, 0, 0, 0], + [1, 0, 1, 1], + [1, 0, 1, 1], + [0, 1, 0, 0]] +Return 4. +""" + +from typing import List + +Matrix = List[List[int]] + + +def is_row_extendable(matrix: Matrix, erow: int, scol: int, ecol: int) -> bool: + return all(matrix[erow][scol:ecol]) + + +def is_column_extendable(matrix: Matrix, ecol: int, srow: int, erow: int) -> bool: + for row in range(srow, erow): + if not matrix[row][ecol]: + return False + return True + + +def area_helper( + matrix: Matrix, + num_rows: int, + num_cols: int, + srow: int, + erow: int, + scol: int, + ecol: int, +) -> int: + current_area = (erow - srow) * (ecol - scol) + row_ex_area, col_ex_area = 0, 0 + # checking if the area can be extended + can_extend_row = erow < num_rows and is_row_extendable(matrix, erow, scol, ecol) + if can_extend_row: + row_ex_area = area_helper( + matrix, num_rows, num_cols, srow, erow + 1, scol, ecol + ) + can_extend_col = ecol < num_cols and is_column_extendable(matrix, ecol, srow, erow) + if can_extend_col: + col_ex_area = area_helper( + matrix, num_rows, num_cols, srow, erow, scol, ecol + 1 + ) + return max(current_area, row_ex_area, col_ex_area) + + +def get_max_rect(matrix: Matrix) -> int: + if not matrix: + return 0 + # generating the maximum area + max_area = 0 + num_rows, num_cols = len(matrix), len(matrix[0]) + for i in range(num_rows): + for j in range(num_cols): + upper_bound_area = (num_rows - i) * (num_cols - j) + if matrix[i][j] and upper_bound_area > max_area: + area = area_helper(matrix, num_rows, num_cols, i, i + 1, j, j + 1) + max_area = max(area, max_area) + return max_area + + +if __name__ == "__main__": + matrix = [ + [1, 0, 0, 0], + [1, 0, 1, 1], + [1, 0, 1, 1], + [0, 1, 0, 0] + ] + print(get_max_rect(matrix)) + + matrix = [ + [1, 0, 0, 0], + [1, 0, 1, 1], + [1, 0, 1, 1], + [0, 1, 1, 1] + ] + print(get_max_rect(matrix)) + + matrix = [ + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1] + ] + print(get_max_rect(matrix)) + + matrix = [ + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0] + ] + print(get_max_rect(matrix)) + + matrix = [ + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 0, 0], + [0, 0, 0, 0] + ] + print(get_max_rect(matrix)) + + matrix = [ + [1, 1, 0, 0], + [1, 0, 0, 0], + [1, 0, 0, 0], + [1, 0, 0, 0] + ] + print(get_max_rect(matrix)) + + +""" +SPECS: + +TIME COMPLEXITY: O((n x m) ^ 2) +SPACE COMPLEXITY: O(n + m) +""" diff --git a/Solutions/138.py b/Solutions/138.py new file mode 100644 index 0000000..154c2f1 --- /dev/null +++ b/Solutions/138.py @@ -0,0 +1,40 @@ +""" +Problem: + +Find the minimum number of coins required to make n cents. + +You can use standard American denominations, that is, 1¢, 5¢, 10¢, and 25¢. + +For example, given n = 16, return 3 since we can make it with a 10¢, a 5¢, and a 1¢. +""" + +from typing import List + + +def calc_num_coins(target: int, denominations: List[int] = [1, 5, 10, 25]) -> int: + # pre-requisted: sorted denominations + length = len(denominations) + count = 0 + for i in range(length - 1, -1, -1): + count += target // denominations[i] + target = target % denominations[i] + if target == 0: + break + if target != 0: + raise ValueError("Target cannot be reached by using the supplied denominations") + return count + + +if __name__ == "__main__": + print(calc_num_coins(16)) + print(calc_num_coins(90)) + print(calc_num_coins(93)) + print(calc_num_coins(100)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/139.py b/Solutions/139.py new file mode 100644 index 0000000..c47fce5 --- /dev/null +++ b/Solutions/139.py @@ -0,0 +1,85 @@ +""" +Problem: + +Given an iterator with methods next() and hasNext(), create a wrapper iterator, +PeekableInterface, which also implements peek(). peek shows the next element that would +be returned on next(). + +Here is the interface: + +class PeekableInterface(object): + def __init__(self, iterator): + pass + + def peek(self): + pass + + def next(self): + pass + + def hasNext(self): + pass +""" + +from typing import Any, Iterable + + +class PeekableInterface(object): + def __init__(self, iterator: Iterable[Any]) -> None: + self.iterator = iterator + try: + self.next_val = next(self.iterator) + self.has_next = True + except StopIteration: + self.next_val = None + self.has_next = False + + def peek(self) -> Any: + return self.next_val + + def next(self) -> Any: + if self.has_next: + curr_elem = self.next_val + try: + self.next_val = next(self.iterator) + except StopIteration: + self.next_val = None + self.has_next = False + return curr_elem + return None + + def hasNext(self) -> bool: + return self.has_next + + +if __name__ == "__main__": + sample_list = [1, 2, 3, 4, 5] + iterator = iter(sample_list) + peekable = PeekableInterface(iterator) + + print(peekable.peek()) + print(peekable.hasNext()) + + print(peekable.next()) + print(peekable.next()) + print(peekable.next()) + + print(peekable.peek()) + print(peekable.hasNext()) + + print(peekable.next()) + print(peekable.hasNext()) + print(peekable.peek()) + print(peekable.next()) + + print(peekable.hasNext()) + print(peekable.peek()) + + print() + + sample_list = [] + iterator = iter(sample_list) + peekable = PeekableInterface(iterator) + + print(peekable.peek()) + print(peekable.hasNext()) diff --git a/Solutions/140.py b/Solutions/140.py new file mode 100644 index 0000000..4fb5da3 --- /dev/null +++ b/Solutions/140.py @@ -0,0 +1,44 @@ +""" +Problem: + +Given an array of integers in which two elements appear exactly once and all other +elements appear exactly twice, find the two elements that appear only once. + +For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. The order does +not matter. + +Follow-up: Can you do this in linear time and constant space? +""" + +from typing import List, Tuple + + +def get_uniques(arr: List[int]) -> Tuple[int, int]: + xor_result = 0 + for val in arr: + xor_result = xor_result ^ val + # using the rightmost set bit as mask to segregate the array of numbers into 2 sets + # performing xor for num1 and num2 based on the set to which they belong to (the 2 + # sets are based on whether a number has rightmost_set_bit of the xor result 1 or 0) + rightmost_set_bit = xor_result & ~(xor_result - 1) + num1, num2 = 0, 0 + for val in arr: + if val & rightmost_set_bit: + num1 = num1 ^ val + else: + num2 = num2 ^ val + return num1, num2 + + +if __name__ == "__main__": + print(get_uniques([2, 4, 6, 8, 10, 2, 6, 10])) + print(get_uniques([2, 4, 8, 8, 10, 2, 6, 10])) + print(get_uniques([2, 3, 8, 8, 10, 2, 1, 10])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/141.py b/Solutions/141.py new file mode 100644 index 0000000..7c7117b --- /dev/null +++ b/Solutions/141.py @@ -0,0 +1,87 @@ +""" +Problem: + +Implement 3 stacks using a single list: + +class Stack: + def __init__(self): + self.list = [] + + def pop(self, stack_number): + pass + + def push(self, item, stack_number): + pass +""" + + +class Stack: + def __init__(self) -> None: + self.list = [] + self.stack1_last_index = 0 + self.stack2_last_index = 0 + self.stack3_last_index = 0 + + def __repr__(self) -> str: + return ( + f"Stack1: {self.list[:self.stack1_last_index]}" + + f"\nStack2: {self.list[self.stack1_last_index:self.stack2_last_index]}" + + f"\nStack3: {self.list[self.stack2_last_index:]}" + ) + + def pop(self, stack_number: int) -> int: + if stack_number == 1: + if len(self.list[: self.stack1_last_index]) == 0: + raise ValueError("Stack Underflow") + self.list.pop(self.stack1_last_index - 1) + self.stack1_last_index -= 1 + self.stack2_last_index -= 1 + self.stack3_last_index -= 1 + elif stack_number == 2: + if len(self.list[self.stack1_last_index : self.stack2_last_index]) == 0: + raise ValueError("Stack Underflow") + self.list.pop(self.stack2_last_index - 1) + self.stack2_last_index -= 1 + self.stack3_last_index -= 1 + elif stack_number == 3: + if len(self.list[self.stack2_last_index :]) == 0: + raise ValueError("Stack Underflow") + self.list.pop() + self.stack3_last_index -= 1 + + def push(self, item: int, stack_number: int) -> None: + if stack_number == 1: + self.list.insert(self.stack1_last_index, item) + self.stack1_last_index += 1 + self.stack2_last_index += 1 + self.stack3_last_index += 1 + elif stack_number == 2: + self.list.insert(self.stack2_last_index, item) + self.stack2_last_index += 1 + self.stack3_last_index += 1 + elif stack_number == 3: + self.list.insert(self.stack3_last_index, item) + self.stack3_last_index += 1 + + +if __name__ == "__main__": + stack = Stack() + stack.push(5, 3) + stack.push(10, 2) + stack.push(1, 1) + + print(stack) + print() + + stack.push(3, 3) + stack.push(1, 2) + stack.push(0, 2) + + print(stack) + print() + + stack.pop(2) + stack.pop(1) + stack.pop(3) + + print(stack) diff --git a/Solutions/142.py b/Solutions/142.py new file mode 100644 index 0000000..0954066 --- /dev/null +++ b/Solutions/142.py @@ -0,0 +1,48 @@ +""" +Problem: + +You're given a string consisting solely of (, ), and *. * can represent either a (, ), +or an empty string. Determine whether the parentheses are balanced. + +For example, (()* and (*) are balanced. )*( is not balanced. +""" + +from copy import deepcopy + +from DataStructures.Stack import Stack + + +def can_balance_parentheses(string: str, stack: Stack = Stack()) -> bool: + if not string and stack.is_empty(): + return True + elif not string: + return False + # checking if the parentheses can be balanced + if string[0] == "(": + stack.push("(") + return can_balance_parentheses(string[1:], stack) + elif string[0] == ")": + if not stack.is_empty() and stack.peek() == "(": + stack.pop() + return can_balance_parentheses(string[1:], stack) + return False + elif string[0] == "*": + return ( + can_balance_parentheses("(" + string[1:], deepcopy(stack)) + or can_balance_parentheses(")" + string[1:], deepcopy(stack)) + or can_balance_parentheses(string[1:], deepcopy(stack)) + ) + + +if __name__ == "__main__": + print(can_balance_parentheses("(()*", Stack())) + print(can_balance_parentheses("(*)", Stack())) + print(can_balance_parentheses(")*(", Stack())) + + +""" +SPECS: + +TIME COMPLEXITY: O(3 ^ n) +SPACE COMPLEXITY: O(3 ^ n) +""" diff --git a/Solutions/144.py b/Solutions/144.py new file mode 100644 index 0000000..0326766 --- /dev/null +++ b/Solutions/144.py @@ -0,0 +1,54 @@ +""" +Problem: + +Given an array of numbers and an index i, return the index of the nearest larger number +of the number at index i, where distance is measured in array indices. + +For example, given [4, 1, 3, 5, 6] and index 0, you should return 3. + +If two distances to larger numbers are equal, then return any one of them. If the array +at i doesn't have a nearest larger integer, then return null. + +Follow-up: If you can preprocess the array, can you do this in constant time? +""" + +from typing import Dict, List + + +def preprocess(arr: List[int]) -> Dict[int, int]: + preprocessed_indices = {} + length = len(arr) + sorted_tuples = [(value, index) for index, value in enumerate(arr)] + sorted_tuples.sort(key=lambda tup: tup[0]) + # generating the minimum distance index + for k, (_, i) in enumerate(sorted_tuples[:-1]): + min_dist = length + for m in range(k + 1, length): + dist_temp = abs(i - sorted_tuples[m][1]) + if dist_temp < min_dist: + min_dist = dist_temp + preprocessed_indices[i] = sorted_tuples[m][1] + return preprocessed_indices + + +def nearest_larger_value_index(arr: List[int], index: int) -> int: + preprocessed_indices = preprocess(arr) + if index not in preprocessed_indices: + return None + return preprocessed_indices[index] + + +if __name__ == "__main__": + print(nearest_larger_value_index([4, 1, 3, 5, 6], 0)) + print(nearest_larger_value_index([4, 1, 3, 5, 6], 1)) + print(nearest_larger_value_index([4, 1, 3, 5, 6], 4)) + print(nearest_larger_value_index([4, 1, 3, 5, 6], 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +[O(n ^ 2) is for preprocessing, after which it's complexity is O(1)] +""" diff --git a/Solutions/145.py b/Solutions/145.py new file mode 100644 index 0000000..9c22ffe --- /dev/null +++ b/Solutions/145.py @@ -0,0 +1,41 @@ +""" +Problem: + +Given the head of a singly linked list, swap every two nodes and return its head. + +For example, given 1 -> 2 -> 3 -> 4, return 2 -> 1 -> 4 -> 3. +""" + +from DataStructures.LinkedList import Node, LinkedList + + +def swap_nodes(ll: LinkedList) -> Node: + node1 = ll.head + node2 = ll.head.next + while True: + try: + node1.val, node2.val = node2.val, node1.val + node1, node2 = node1.next.next, node2.next.next + except: + break + return ll.head + + +if __name__ == "__main__": + LL = LinkedList() + + LL.add(1) + LL.add(2) + LL.add(3) + LL.add(4) + + print(LL) + print(swap_nodes(LL)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/146.py b/Solutions/146.py new file mode 100644 index 0000000..69cd467 --- /dev/null +++ b/Solutions/146.py @@ -0,0 +1,75 @@ +""" +Problem: + +Given a binary tree where all nodes are either 0 or 1, prune the tree so that subtrees +containing all 0s are removed. + +For example, given the following tree: + + 0 + / \ + 1 0 + / \ + 1 0 + / \ + 0 0 +should be pruned to: + + 0 + / \ + 1 0 + / + 1 +We do not remove the tree at the root or its left child because it still has a 1 as a +descendant. +""" + +from DataStructures.Tree import Node, BinaryTree + + +def prune_helper(node: Node) -> None: + if node.left: + prune_helper(node.left) + if node.left.val == 0: + if not node.left.left and not node.left.right: + temp = node.left + node.left = None + del temp + if node.right: + prune_helper(node.right) + if node.right.val == 0: + if not node.right.left and not node.right.right: + temp = node.right + node.right = None + del temp + + +def prune(tree: BinaryTree) -> BinaryTree: + if tree.root: + prune_helper(tree.root) + return tree + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(0) + + tree.root.left = Node(1) + tree.root.right = Node(0) + + tree.root.right.left = Node(1) + tree.root.right.right = Node(0) + + tree.root.right.left.left = Node(0) + tree.root.right.left.right = Node(0) + + print(tree) + print(prune(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/147.py b/Solutions/147.py new file mode 100644 index 0000000..b981a75 --- /dev/null +++ b/Solutions/147.py @@ -0,0 +1,36 @@ +""" +Problem: + +Given a list, sort it using this method: reverse(lst, i, j), which sorts lst from i to +j. +""" + +from typing import List + + +def reverse(lst: List[int], i: int, j: int) -> None: + lst[i : j + 1] = lst[i : j + 1][::-1] + + +def bubble_sort(lst: List[int]) -> List[int]: + length = len(lst) + for i in range(length - 1): + for j in range(length - i - 1): + if lst[j] > lst[j + 1]: + reverse(lst, j, j + 1) + return lst + + +if __name__ == "__main__": + print(bubble_sort([0, 6, 4, 2, 5, 3, 1])) + print(bubble_sort([0, 6, 4, 2, 5, 3, 1, 10, 9])) + print(bubble_sort([0, 6, 4, 2, 5, 3, 1, 2, 3])) + print(bubble_sort([0, 6, 4, 2, 5, 3, 1, 11])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) [since reverse() is being used on adjacent indices] +""" diff --git a/Solutions/148.py b/Solutions/148.py new file mode 100644 index 0000000..03751ae --- /dev/null +++ b/Solutions/148.py @@ -0,0 +1,40 @@ +""" +Problem: + +Gray code is a binary code where each successive value differ in only one bit, as well +as when wrapping around. Gray code is common in hardware so that we don't see temporary +spurious values during transitions. + +Given a number of bits n, generate a possible gray code for it. + +For example, for n = 2, one gray code would be [00, 01, 11, 10]. +""" + +from typing import List + + +def get_grey_code(n: int) -> List[str]: + if n == 0: + return [""] + # generating grey code + previous_grey_code = get_grey_code(n - 1) + base0 = ["0" + val for val in previous_grey_code] + base1 = ["1" + val for val in previous_grey_code[::-1]] + return base0 + base1 + + +if __name__ == "__main__": + print(get_grey_code(0)) + print(get_grey_code(1)) + print(get_grey_code(2)) + print(get_grey_code(3)) + print(get_grey_code(4)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(2 ^ n) +[there are (2 ^ n) grey codes of length n] +""" diff --git a/Solutions/149.py b/Solutions/149.py new file mode 100644 index 0000000..f651fa6 --- /dev/null +++ b/Solutions/149.py @@ -0,0 +1,37 @@ +""" +Problem: + +Given a list of numbers L, implement a method sum(i, j) which returns the sum from the +sublist L[i:j] (including i, excluding j). + +For example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return sum([2, 3]), which is 5. + +You can assume that you can do some pre-processing. sum() should be optimized over the +pre-processing step. +""" + +from typing import List + + +class SubarraySumOptimizer: + def __init__(self, arr: List[int]) -> None: + # runs in O(n) time, O(n) space + self.preprocessed_arr = [0 for _ in range(len(arr) + 1)] + for i in range(len(arr)): + self.preprocessed_arr[i + 1] = self.preprocessed_arr[i] + arr[i] + + def sum(self, start: int, end: int) -> int: + # runs in O(1) time, O(1) space + # NOTE: the sum is supposed to return the sum in the range [start, end) + if (start < 0) or (end > len(self.preprocessed_arr) - 1) or (start > end): + return 0 + return self.preprocessed_arr[end] - self.preprocessed_arr[start] + + +if __name__ == "__main__": + sso = SubarraySumOptimizer([1, 2, 3, 4, 5]) + + print(sso.sum(1, 3)) + print(sso.sum(0, 5)) + print(sso.sum(0, 4)) + print(sso.sum(3, 4)) diff --git a/Solutions/150.py b/Solutions/150.py new file mode 100644 index 0000000..b4f0e85 --- /dev/null +++ b/Solutions/150.py @@ -0,0 +1,33 @@ +""" +Problem: + +Given a list of points, a central point, and an integer k, find the nearest k points +from the central point. + +For example, given the list of points [(0, 0), (5, 4), (3, 1)], the central point +(1, 2), and k = 2, return [(0, 0), (3, 1)]. +""" + +from typing import List, Tuple + +Position = Tuple[int, int] + + +def get_distance(point1: Position, point2: Position) -> float: + return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5 + + +def KNN(arr: List[Position], center: Position, k: int) -> List[Position]: + return sorted(arr, key=lambda position: get_distance(position, center))[:k] + + +if __name__ == "__main__": + print(KNN([(0, 0), (5, 4), (3, 1)], (1, 2), 2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(k) +""" diff --git a/Solutions/151.py b/Solutions/151.py new file mode 100644 index 0000000..10b718a --- /dev/null +++ b/Solutions/151.py @@ -0,0 +1,125 @@ +""" +Problem: + +Given a 2-D matrix representing an image, a location of a pixel in the screen and a +color C, replace the color of the given pixel and all adjacent same colored pixels +with C. + +For example, given the following matrix, and location pixel of (2, 2), and 'G' for +green: + +B B W +W W W +W W W +B B B +Becomes + +B B G +G G G +G G G +B B B +""" + +from typing import List, Set, Tuple +from numpy import array + +Matrix = List[List[int]] +Position = Tuple[int, int] + + +def generate_neighbours(position: Position, rows: int, cols: int) -> List[Position]: + i, j = position + valid_neighbours = [] + neighbours = [ + (i - 1, j - 1), + (i - 1, j), + (i - 1, j + 1), + (i, j + 1), + (i + 1, j + 1), + (i + 1, j), + (i + 1, j - 1), + (i, j - 1), + ] + for neighbour in neighbours: + y, x = neighbour + if (0 <= x < cols) and (0 <= y < rows): + valid_neighbours.append(neighbour) + return valid_neighbours + + +def update_color_dfs_helper( + matrix: Matrix, + position: Position, + new_color: str, + prev_color: str, + visited: Set[Position], + rows: int, + cols: int, +) -> None: + i, j = position + matrix[i][j] = new_color + visited.add(position) + + neighbours = generate_neighbours(position, rows, cols) + for neighbour in neighbours: + y, x = neighbour + if neighbour not in visited and matrix[y][x] == prev_color: + update_color_dfs_helper( + matrix, neighbour, new_color, prev_color, visited, rows, cols + ) + + +def update_color(matrix: Matrix, position: Position, new_color: str) -> Matrix: + rows = len(matrix) + cols = len(matrix[0]) + i, j = position + + update_color_dfs_helper( + matrix, position, new_color, matrix[i][j], set(), rows, cols + ) + return matrix + + +if __name__ == "__main__": + print("Initial Matrix:") + matrix = [ + ["B", "B", "W"], + ["W", "W", "W"], + ["W", "W", "W"], + ["B", "B", "B"] + ] + print(array(matrix)) + print("Updated Matrix:") + print(array(update_color(matrix, (2, 2), "G"))) + print() + + print("Initial Matrix:") + matrix = [ + ["B", "B", "W"], + ["W", "W", "W"], + ["W", "W", "W"], + ["B", "B", "B"] + ] + print(array(matrix)) + print("Updated Matrix:") + print(array(update_color(matrix, (3, 2), "G"))) + print() + + print("Initial Matrix:") + matrix = [ + ["B", "B", "W"], + ["W", "W", "W"], + ["W", "W", "W"], + ["B", "B", "B"] + ] + print(array(matrix)) + print("Updated Matrix:") + print(array(update_color(matrix, (0, 0), "G"))) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) +""" diff --git a/Solutions/152.py b/Solutions/152.py new file mode 100644 index 0000000..c9d3d98 --- /dev/null +++ b/Solutions/152.py @@ -0,0 +1,39 @@ +""" +Problem: + +You are given n numbers as well as n probabilities that sum up to 1. Write a function +to generate one of the numbers with its corresponding probability. + +For example, given the numbers [1, 2, 3, 4] and probabilities [0.1, 0.5, 0.2, 0.2], +your function should return 1 10% of the time, 2 50% of the time, and 3 and 4 20% of +the time. + +You can generate random numbers between 0 and 1 uniformly. +""" + +import matplotlib.pyplot as plt +from random import random +from typing import List + + +class RandomGenerator: + def __init__(self, numbers: List[int], probabilities: List[float]) -> None: + self.numbers = numbers + self.probabilities = probabilities + + def generate(self) -> int: + check = random() + cumulative = 0 + for pos in range(len(self.probabilities)): + cumulative += self.probabilities[pos] + if cumulative >= check: + return self.numbers[pos] + + +if __name__ == "__main__": + generator = RandomGenerator([1, 2, 3, 4], [0.1, 0.5, 0.2, 0.2]) + nums = [] + for _ in range(1, 100_000): + nums.append(generator.generate()) + plt.hist(nums) + plt.show() diff --git a/Solutions/153.py b/Solutions/153.py new file mode 100644 index 0000000..3751f41 --- /dev/null +++ b/Solutions/153.py @@ -0,0 +1,52 @@ +""" +Problem: + +Find an efficient algorithm to find the smallest distance (measured in number of words) +between any two given words in a string. + +For example, given words "hello", and "world" and a text content of "dog cat hello cat +dog dog hello cat world", return 1 because there's only one word "cat" in between the +two words. +""" + + +def calculate_distance(text: str, word1: str, word2: str) -> int: + word_list = text.split() + length = len(word_list) + distance, position, last_match = None, None, None + # searching for the smallest distance + for i in range(length): + if word_list[i] in (word1, word2): + if last_match in (word_list[i], None): + last_match = word_list[i] + position = i + continue + current_distance = i - position - 1 + last_match = word_list[i] + position = i + if distance == None: + distance = current_distance + else: + distance = min(distance, current_distance) + return distance + + +if __name__ == "__main__": + print( + calculate_distance( + "dog cat hello cat dog dog hello cat world", "hello", "world" + ) + ) + print( + calculate_distance("dog cat hello cat dog dog hello cat world", "world", "dog") + ) + print(calculate_distance("hello world", "hello", "world")) + print(calculate_distance("hello", "hello", "world")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/155.py b/Solutions/155.py new file mode 100644 index 0000000..7d8d507 --- /dev/null +++ b/Solutions/155.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a list of elements, find the majority element, which appears more than half the +times (> floor(len(lst) / 2.0)). + +You can assume that such an element exists. + +For example, given [1, 2, 1, 1, 3, 4, 0], return 1. +""" + +from typing import List, Optional + + +def majority_element(arr: List[int]) -> Optional[int]: + length = len(arr) + if not length: + return + elif length < 3: + return arr[0] + # getting the majority element by generating the frequencies + frequency = {} + for elem in arr: + if elem not in frequency: + frequency[elem] = 0 + frequency[elem] += 1 + for elem in frequency: + if frequency[elem] > (length // 2): + return elem + + +if __name__ == "__main__": + print(majority_element([1, 2, 1, 1, 1, 4, 0])) + print(majority_element([1, 1, 1, 3, 3, 3, 4, 1, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/156.py b/Solutions/156.py new file mode 100644 index 0000000..412e896 --- /dev/null +++ b/Solutions/156.py @@ -0,0 +1,35 @@ +""" +Problem: + +Given a positive integer n, find the smallest number of squared integers which sum to n. + +For example, given n = 13, return 2 since 13 = 3^2 + 2^2 = 9 + 4. + +Given n = 27, return 3 since 27 = 3^2 + 3^2 + 3^2 = 9 + 9 + 9. +""" + + +def min_square_num(num: int, accumulator: int = 0) -> int: + if num == 0: + return accumulator + elif num == 1: + return accumulator + 1 + + largest_square_divisor = int(num ** 0.5) ** 2 + num = num - largest_square_divisor + accumulator += 1 + return min_square_num(num, accumulator) + + +if __name__ == "__main__": + print(min_square_num(25)) # (5 ^ 2) + print(min_square_num(13)) # (2 ^ 2) + (3 ^ 2) + print(min_square_num(27)) # (5 ^ 2) + (1 ^ 2) + (1 ^ 2) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/158.py b/Solutions/158.py new file mode 100644 index 0000000..e76b766 --- /dev/null +++ b/Solutions/158.py @@ -0,0 +1,97 @@ +""" +Problem: + +You are given an N * M matrix of 0s and 1s. Starting from the top left corner, how many +ways are there to reach the bottom right corner? + +You can only move right and down. 0 reppossible_pathsents an empty space while 1 reppossible_pathsents a wall +you cannot walk through. + +For example, given the following matrix: + +[[0, 0, 1], + [0, 0, 1], + [1, 0, 0]] +Return 2, as there are only two ways to get to the bottom right: + +Right, down, down, right +Down, right, down, right +The top left corner and bottom right corner will always be 0. +""" + +from typing import List + +Matrix = List[List[int]] + + +def get_possible_paths(matrix: Matrix) -> int: + n, m = len(matrix), len(matrix[0]) + # possible_pathsetting the values of 1 to -1 as positive numbers are used to construct the + # paths + for i in range(n): + for j in range(m): + if matrix[i][j] == 1: + matrix[i][j] = -1 + # setting the vertical and horizontal paths + for i in range(n): + if matrix[i][0] == -1: + break + else: + matrix[i][0] = 1 + for i in range(m): + if matrix[0][i] == -1: + break + else: + matrix[0][i] = 1 + # generating the paths + for i in range(1, n): + for j in range(1, m): + if matrix[i][j] != -1: + possible_paths = 0 + if matrix[i - 1][j] != -1: + possible_paths += matrix[i - 1][j] + if matrix[i][j - 1] != -1: + possible_paths += matrix[i][j - 1] + matrix[i][j] = possible_paths + return matrix[-1][-1] + + +if __name__ == "__main__": + matrix = [ + [0, 0, 1], + [0, 0, 1], + [1, 0, 0] + ] + print(get_possible_paths(matrix)) + + matrix = [ + [0, 0, 1], + [1, 0, 1], + [1, 0, 0] + ] + print(get_possible_paths(matrix)) + + matrix = [ + [0, 0, 0], + [1, 0, 0], + [0, 0, 0] + ] + print(get_possible_paths(matrix)) + + # end cannot be reached as only right and down traversal is allowed + matrix = [ + [0, 0, 0], + [1, 1, 0], + [0, 0, 0], + [0, 1, 1], + [0, 0, 0] + ] + print(get_possible_paths(matrix)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(n x m) +""" diff --git a/Solutions/159.py b/Solutions/159.py new file mode 100644 index 0000000..df3ea4f --- /dev/null +++ b/Solutions/159.py @@ -0,0 +1,34 @@ +""" +Problem: + +Given a string, return the first recurring character in it, or null if there is no +recurring chracter. + +For example, given the string "acbbac", return "b". Given the string "abcdef", return +null. +""" + +from typing import Optional + + +def get_first_recurring_character(string: str) -> Optional[str]: + seen_characters = set() + + for char in string: + if char in seen_characters: + return char + seen_characters.add(char) + return None + + +if __name__ == "__main__": + print(get_first_recurring_character("acbbac")) + print(get_first_recurring_character("abcdef")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/160.py b/Solutions/160.py new file mode 100644 index 0000000..131f7d7 --- /dev/null +++ b/Solutions/160.py @@ -0,0 +1,101 @@ +""" +Problem: + +Given a tree where each edge has a weight, compute the length of the longest path in +the tree. + +For example, given the following tree: + + a + /|\ + b c d + / \ + e f + / \ + g h +and the weights: a-b: 3, a-c: 5, a-d: 8, d-e: 2, d-f: 4, e-g: 1, e-h: 1, the longest +path would be c -> a -> d -> f, with a length of 17. + +The path does not have to pass through the root, and each node can have any amount of +children. +""" + +from __future__ import annotations + + +class Node: + def __init__(self, val: str) -> None: + self.val = val + self.max_path = 0 + self.child_dists = {} + + def add_child(self, child: str, wt: int) -> None: + self.child_dists[child] = wt + + def get_max_path(self, tree: Tree) -> int: + if not self.child_dists: + return 0 + # generating the max path length + path_lengths = [] + children_max_path_lengths = [] + for node, dist in self.child_dists.items(): + path_lengths.append(tree.tree[node].max_path + dist) + children_max_path_lengths.append(tree.tree[node].get_max_path(tree)) + return max(sum(sorted(path_lengths)[-2:]), max(children_max_path_lengths)) + + def update_max_paths(self, tree: Tree) -> None: + if not self.child_dists: + self.max_path = 0 + return + # generating the paths from the root + root_paths = [] + for child, dist in self.child_dists.items(): + tree.tree[child].update_max_paths(tree) + root_paths.append(tree.tree[child].max_path + dist) + self.max_path = max(root_paths) + + +class Tree: + def __init__(self) -> None: + self.tree = {} + self.root = None + + def add_node(self, val: str) -> None: + self.tree[val] = Node(val) + if not self.root: + self.root = val + + def add_child(self, parent: str, child: str, wt: int) -> None: + if parent not in self.tree: + raise ValueError("Parent Node not present in the tree") + self.tree[parent].add_child(child, wt) + self.tree[child] = Node(child) + + def get_longest_path(self) -> int: + if not self.root: + return 0 + self.tree[self.root].update_max_paths(self) + return self.tree[self.root].get_max_path(self) + + +if __name__ == "__main__": + tree = Tree() + + tree.add_node("a") + tree.add_child("a", "b", 3) + tree.add_child("a", "c", 5) + tree.add_child("a", "d", 8) + tree.add_child("d", "e", 2) + tree.add_child("d", "f", 4) + tree.add_child("e", "g", 1) + tree.add_child("e", "h", 1) + + print(tree.get_longest_path()) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/161.py b/Solutions/161.py new file mode 100644 index 0000000..0f9b489 --- /dev/null +++ b/Solutions/161.py @@ -0,0 +1,27 @@ +""" +Problem: + +Given a 32-bit integer, return the number with its bits reversed. + +For example, given the binary number 1111 0000 1111 0000 1111 0000 1111 0000, return +0000 1111 0000 1111 0000 1111 0000 1111. +""" + + +def complement_1s(num: str) -> str: + result = "" + for digit in num: + result += str(int(not int(digit))) + return result + + +if __name__ == "__main__": + print(complement_1s("11110000111100001111000011110000")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/162.py b/Solutions/162.py new file mode 100644 index 0000000..7e48921 --- /dev/null +++ b/Solutions/162.py @@ -0,0 +1,66 @@ +""" +Problem: + +Given a list of words, return the shortest unique prefix of each word. For example, given the list: + +dog +cat +apple +apricot +fish + +Return the list: + +d +c +app +apr +f +""" + +from typing import Dict, List, Optional + + +def get_unique_prefix_for_string( + dictionary: Dict[str, int], string: str, string_list: List[str] +) -> Optional[str]: + prefix = "" + for char in string: + prefix += char + if prefix not in dictionary: + return prefix + # if a string with the current prefix exists, the prefix for the string is + # updated + prev_str_with_same_prefix = string_list[dictionary[prefix]] + prev_prefix = prefix + prev_str_index = dictionary[prefix] + + del dictionary[prefix] + try: + prev_prefix = prev_str_with_same_prefix[: len(prev_prefix) + 1] + except: + return + dictionary[prev_prefix] = prev_str_index + + +def get_unique_prefix(string_list: List[str]) -> List[str]: + dictionary = {} + # generating the unique prefix + for index, string in enumerate(string_list): + prefix = get_unique_prefix_for_string(dictionary, string, string_list) + if not prefix: + raise ValueError("Unique Prefix Generation not possible") + dictionary[prefix] = index + return list(dictionary.keys()) + + +if __name__ == "__main__": + print(get_unique_prefix(["dog", "cat", "apple", "apricot", "fish"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/163.py b/Solutions/163.py new file mode 100644 index 0000000..a5a8930 --- /dev/null +++ b/Solutions/163.py @@ -0,0 +1,51 @@ +""" +Problem: + +Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate +it. + +The expression is given as a list of numbers and operands. For example: [5, 3, '+'] +should return 5 + 3 = 8. + +For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return +5, since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5. + +You can assume the given expression is always valid. +""" + +from typing import List, Union + +from DataStructures.Stack import Stack + +FUNCTIONS = { + "+": lambda a, b: a + b, + "-": lambda a, b: a - b, + "*": lambda a, b: a * b, + "/": lambda a, b: a / b, +} + + +def calculate(expression_list: List[Union[int, str]]) -> Union[float, int]: + stack = Stack() + # calculating the expression + for expression in expression_list: + if expression in FUNCTIONS: + a = stack.pop() + b = stack.pop() + stack.push(FUNCTIONS[expression](a, b)) + else: + stack.push(expression) + return stack[0] + + +if __name__ == "__main__": + print(calculate([5, 3, "+"])) + print(calculate([15, 7, 1, 1, "+", "-", "/", 3, "*", 2, 1, 1, "+", "+", "-"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/164.py b/Solutions/164.py new file mode 100644 index 0000000..6854e4a --- /dev/null +++ b/Solutions/164.py @@ -0,0 +1,30 @@ +""" +Problem: + +You are given an array of length n + 1 whose elements belong to the set {1, 2, ..., n}. +By the pigeonhole principle, there must be a duplicate. Find it in linear time and +space. +""" + +from typing import List + + +def find_duplicate(arr: List[int]) -> int: + seen_numbers = set() + for num in arr: + if num in seen_numbers: + return num + seen_numbers.add(num) + + +if __name__ == "__main__": + print(find_duplicate([1, 2, 4, 6, 5, 3, 2])) + print(find_duplicate([3, 1, 4, 2, 3])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/165.py b/Solutions/165.py new file mode 100644 index 0000000..dbb9fb0 --- /dev/null +++ b/Solutions/165.py @@ -0,0 +1,41 @@ +""" +Problem: + +Given an array of integers, return a new array where each element in the new array is +the number of smaller elements to the right of that element in the original input array. + +For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0], since: + +There is 1 smaller element to the right of 3 +There is 1 smaller element to the right of 4 +There are 2 smaller elements to the right of 9 +There is 1 smaller element to the right of 6 +There are no smaller elements to the right of 1 +""" + +from typing import List + + +def get_smaller_elements_arr(arr: List[int]) -> List[int]: + smaller_elements_arr = [] + length = len(arr) + + for i in range(length): + smaller_elements = 0 + for j in range(i + 1, length): + if arr[i] > arr[j]: + smaller_elements += 1 + smaller_elements_arr.append(smaller_elements) + return smaller_elements_arr + + +if __name__ == "__main__": + print(get_smaller_elements_arr([3, 4, 9, 6, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/166.py b/Solutions/166.py new file mode 100644 index 0000000..a30a1e2 --- /dev/null +++ b/Solutions/166.py @@ -0,0 +1,69 @@ +""" +Problem: + +Implement a 2D iterator class. It will be initialized with an array of arrays, and +should implement the following methods: + +next(): returns the next element in the array of arrays. If there are no more +elements, raise an exception. +has_next(): returns whether or not the iterator still has elements left. +For example, given the input [[1, 2], [3], [], [4, 5, 6]], calling next() repeatedly +should output 1, 2, 3, 4, 5, 6. + +Do not use flatten or otherwise clone the arrays. Some of the arrays can be empty. +""" + +from typing import Generator, List, Optional + + +class Iterator2D: + def __init__(self, iteratable2d: List[List[int]]) -> None: + self.iteratable2d = iteratable2d + self.generator = Iterator2D.generator_func(iteratable2d) + self.next_value = next(self.generator) + + def __repr__(self) -> str: + return str(self.iteratable2d) + + @staticmethod + def generator_func(iteratable2d: List[List[int]]) -> Generator[int, None, None]: + for iteratable in iteratable2d: + for element in iteratable: + yield element + + def has_next(self) -> bool: + return self.next_value is not None + + def next(self) -> Optional[int]: + curr_value = self.next_value + try: + self.next_value = next(self.generator) + except StopIteration: + self.next_value = None + return curr_value + + +if __name__ == "__main__": + iter_obj = Iterator2D([[1, 2], [3], [], [4, 5, 6]]) + print(iter_obj) + + print(iter_obj.has_next()) + print(iter_obj.next()) + + print(iter_obj.has_next()) + print(iter_obj.next()) + + print(iter_obj.has_next()) + print(iter_obj.next()) + + print(iter_obj.has_next()) + print(iter_obj.next()) + + print(iter_obj.has_next()) + print(iter_obj.next()) + + print(iter_obj.has_next()) + print(iter_obj.next()) + + print(iter_obj.has_next()) + print(iter_obj.next()) diff --git a/Solutions/167.py b/Solutions/167.py new file mode 100644 index 0000000..2f3e102 --- /dev/null +++ b/Solutions/167.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a list of words, find all pairs of unique indices such that the concatenation of +the two words is a palindrome. + +For example, given the list ["code", "edoc", "da", "d"], return +[(0, 1), (1, 0), (2, 3)]. +""" + +from typing import List, Tuple + + +def is_palindrome(string: str) -> bool: + return string == string[::-1] + + +def get_concatenated_palindrome_indices( + string_list: List[str], +) -> List[Tuple[int, int]]: + concatenated_palindrome_indices = [] + length = len(string_list) + # generating concatenated palindrome indices + for i in range(length): + for j in range(i + 1, length): + if is_palindrome(string_list[i] + string_list[j]): + concatenated_palindrome_indices.append((i, j)) + if is_palindrome(string_list[j] + string_list[i]): + concatenated_palindrome_indices.append((j, i)) + return concatenated_palindrome_indices + + +if __name__ == "__main__": + print(get_concatenated_palindrome_indices(["code", "edoc", "da", "d"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x len(word)) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/168.py b/Solutions/168.py new file mode 100644 index 0000000..8677dfb --- /dev/null +++ b/Solutions/168.py @@ -0,0 +1,72 @@ +""" +Problem: + +Given an N by N matrix, rotate it by 90 degrees clockwise. + +For example, given the following matrix: + +[[1, 2, 3], + [4, 5, 6], + [7, 8, 9]] + +you should return: + +[[7, 4, 1], + [8, 5, 2], + [9, 6, 3]] + +Follow-up: What if you couldn't use any extra space? +""" + +from numpy import array +from typing import List + +Matrix = List[List[int]] + + +def rotate_matrix(matrix: Matrix) -> Matrix: + num_layers = len(matrix) // 2 + max_index = len(matrix) - 1 + # rotating the matrix + for layer in range(num_layers): + for index in range(layer, max_index - layer): + ( + matrix[layer][index], + matrix[max_index - index][layer], + matrix[max_index - layer][max_index - index], + matrix[index][max_index - layer], + ) = ( + matrix[max_index - index][layer], + matrix[max_index - layer][max_index - index], + matrix[index][max_index - layer], + matrix[layer][index], + ) + return matrix + + +if __name__ == "__main__": + matrix = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ] + print(array(matrix)) + print(array(rotate_matrix(matrix))) + print() + + matrix = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16] + ] + print(array(matrix)) + print(array(rotate_matrix(matrix))) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/169.py b/Solutions/169.py new file mode 100644 index 0000000..d8dfe91 --- /dev/null +++ b/Solutions/169.py @@ -0,0 +1,93 @@ +""" +Problem: + +Given a linked list, sort it in O(n log n) time and constant space. + +For example, the linked list 4 -> 1 -> -3 -> 99 should become -3 -> 1 -> 4 -> 99. +""" + +from typing import Optional + +from DataStructures.LinkedList import Node, LinkedList + + +def sorted_merge(node: Node, a: Optional[Node], b: Optional[Node]) -> Optional[Node]: + if a is None: + return b + if b is None: + return a + + result = None + if a.val <= b.val: + result = a + result.next = sorted_merge(node, a.next, b) + else: + result = b + result.next = sorted_merge(node, a, b.next) + return result + + +def merge_sort(ll: LinkedList, h: Optional[Node]) -> Optional[Node]: + if h is None or h.next is None: + return h + + middle = get_middle(ll, h) + next_to_middle = middle.next + middle.next = None + + left = merge_sort(ll, h) + right = merge_sort(ll, next_to_middle) + + sortedlist = sorted_merge(ll, left, right) + return sortedlist + + +def get_middle(ll: LinkedList, head: Optional[Node]) -> Optional[Node]: + # searching for the middle of the linked list using fast pointer slow pointer + if head == None: + return head + + slow, fast = head, head + while fast.next is not None and fast.next.next is not None: + slow = slow.next + fast = fast.next.next + return slow + + +def sort(ll: LinkedList) -> LinkedList: + ll.head = merge_sort(ll, ll.head) + # reseting rear + curr = ll.head + while curr.next: + curr = curr.next + ll.rear = curr + return ll + + +if __name__ == "__main__": + LL = LinkedList() + + for val in [6, 3, 7, 5, 30, 2, 50]: + LL.add(val) + + print(LL) + sort(LL) + print(LL) + print() + + LL = LinkedList() + + for val in [4, 1, -3, 99]: + LL.add(val) + + print(LL) + sort(LL) + print(LL) + + +""" +SPECS: + +TIME COMPLEXITY: O(n log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/170.py b/Solutions/170.py new file mode 100644 index 0000000..62d6a49 --- /dev/null +++ b/Solutions/170.py @@ -0,0 +1,95 @@ +""" +Problem: + +Given a start word, an end word, and a dictionary of valid words, find the shortest +transformation sequence from start to end such that only one letter is changed at each +step of the sequence, and each transformed word exists in the dictionary. If there is +no possible transformation, return null. Each word in the dictionary have the same +length as start and end and is lowercase. + +For example, given start = "dog", end = "cat", and +dictionary = {"dot", "dop", "dat", "cat"}, return ["dog", "dot", "dat", "cat"]. + +Given start = "dog", end = "cat", and dictionary = {"dot", "tod", "dat", "dar"}, return +null as there is no possible transformation from dog to cat. +""" + +from sys import maxsize +from typing import List, Optional + +from DataStructures.Graph import GraphUndirectedUnweighted +from DataStructures.Queue import Queue + + +def is_str_different_by_1_character(s1: str, s2: str) -> bool: + len1 = len(s1) + len2 = len(s2) + no_mismatch = True + if len1 != len2: + if abs(len1 - len2) > 1: + return False + no_mismatch = False + + for c1, c2 in zip(s1, s2): + if c1 != c2: + if no_mismatch: + no_mismatch = False + else: + return False + return True + + +def create_graph(vert_list: List[str]) -> GraphUndirectedUnweighted: + graph = GraphUndirectedUnweighted() + length = len(vert_list) + for i in range(length): + for j in range(i, length): + if is_str_different_by_1_character(vert_list[i], vert_list[j]): + graph.add_edge(vert_list[i], vert_list[j]) + return graph + + +def bfs_path(graph: GraphUndirectedUnweighted, start: str, stop: str) -> List[str]: + parent_map = {node: None for node in graph.connections} + # bfs + queue = Queue() + seen = set() + queue.enqueue(start) + seen.add(start) + while not queue.is_empty(): + node = queue.dequeue() + for neighbour in graph.connections[node]: + if neighbour not in seen: + parent_map[neighbour] = node + queue.enqueue(neighbour) + seen.add(neighbour) + # generating the path + path = [stop] + while parent_map[path[-1]] is not None: + path.append(parent_map[path[-1]]) + if path[-1] == start: + break + return reversed(path) + + +def min_transform(start: str, stop: str, dictionary: List[str]) -> Optional[List[str]]: + if start not in dictionary: + dictionary.append(start) + if stop not in dictionary: + return None + + graph = create_graph(dictionary) + return bfs_path(graph, start, stop) + + +if __name__ == "__main__": + print(min_transform("dog", "cat", ["dot", "dop", "dat", "cat"])) + print(min_transform("dog", "cat", ["dot", "tod", "dat", "dar"])) + + +""" +SPECS: + +TIME COMPLEXITY: O((n ^ 2) x len(word)) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/172.py b/Solutions/172.py new file mode 100644 index 0000000..ee43346 --- /dev/null +++ b/Solutions/172.py @@ -0,0 +1,53 @@ +""" +Problem: + +Given a string s and a list of words words, where each word is the same length, find +all starting indices of substrings in s that is a concatenation of every word in words +exactly once. + +For example, given s = "dogcatcatcodecatdog" and words = ["cat", "dog"], return [0, 13], +since "dogcat" starts at index 0 and "catdog" starts at index 13. + +Given s = "barfoobazbitbyte" and words = ["dog", "cat"], return [] since there are no +substrings composed of "dog" and "cat" in s. + +The order of the indices does not matter. +""" + +from itertools import permutations as generate_permutations +from re import finditer +from typing import Iterable, List + + +def concat_iteratable(iterateable: Iterable[str]) -> str: + concated_value = "" + for elem in iterateable: + concated_value += elem + return concated_value + + +def get_permutation_match_indices(s: str, words: List[str]) -> List[int]: + permutations = [ + concat_iteratable(permutation) + for permutation in list(generate_permutations(words)) + ] + indices = [] + for permutation in permutations: + indices.extend([match.start() for match in finditer(permutation, s)]) + return indices + + +if __name__ == "__main__": + print(get_permutation_match_indices("barfoobazbitbyte", ["dog", "cat"])) + print(get_permutation_match_indices("dogcatcatcodecatdog", ["cat", "dog"])) + print(get_permutation_match_indices("dogcatcatcodecatdogcat", ["cat", "dog"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ m + 2 ^ n) +SPACE COMPLEXITY: O(n) +[n = number of characters in input string + m = number of match words] +""" diff --git a/Solutions/173.py b/Solutions/173.py new file mode 100644 index 0000000..26afb1a --- /dev/null +++ b/Solutions/173.py @@ -0,0 +1,62 @@ +""" +Problem: + +Write a function to flatten a nested dictionary. Namespace the keys with a period. + +For example, given the following dictionary: + +{ + "key": 3, + "foo": { + "a": 5, + "bar": { + "baz": 8 + } + } +} + +it should become: + +{ + "key": 3, + "foo.a": 5, + "foo.bar.baz": 8 +} + +You can assume keys do not contain dots in them, i.e. no clobbering will occur. +""" + +from typing import Any, Dict + + +def flatten_dictionary(dictionary: Dict[str, Any]) -> Dict[str, Any]: + for key in list(dictionary.keys()): + value = dictionary[key] + if type(value) == dict: + value = flatten_dictionary(value) + del dictionary[key] + for nested_dictionary_key in value: + dictionary[f"{key}.{nested_dictionary_key}"] = value[ + nested_dictionary_key + ] + return dictionary + + +if __name__ == "__main__": + print(flatten_dictionary({ + "key": 3, + "foo": { + "a": 5, + "bar": { + "baz": 8 + } + } + })) + + +""" +SPECS: + +TIME COMPLEXITY: O(number of key-value pairs) +SPACE COMPLEXITY: O(levels of nesting) +""" diff --git a/Solutions/174.md b/Solutions/174.md new file mode 100644 index 0000000..dc0089c --- /dev/null +++ b/Solutions/174.md @@ -0,0 +1,27 @@ +``` +Problem: + +Describe and give an example of each of the following types of polymorphism: + +- Ad-hoc polymorphism +- Parametric polymorphism +- Subtype polymorphism +``` + +## Ad-hoc polymorphism + +- Allow multiple functions that perform an operation on different +- add(int, int) and add(str, str) would be separately implemented + +## Parametric polymorphism + +- This allows a function to deal with generics, and therefore on any concrete + definition of the generic. +- e.g. A List type in Java, regardless of which objects are in the list + +## Subtype polymorphism + +- This allows subclass instances to be treated by a function they same way as it + would superclass instances +- e.g. Instances of Cat will be operated on a function the same way as instances of + it's superclass Animal. diff --git a/Solutions/175.py b/Solutions/175.py new file mode 100644 index 0000000..6631cac --- /dev/null +++ b/Solutions/175.py @@ -0,0 +1,78 @@ +""" +Problem: + +You are given a starting state start, a list of transition probabilities for a Markov +chain, and a number of steps num_steps. Run the Markov chain starting from start for +num_steps and compute the number of times we visited each state. + +For example, given the starting state a, number of steps 5000, and the following +transition probabilities: + +[ + ('a', 'a', 0.9), + ('a', 'b', 0.075), + ('a', 'c', 0.025), + ('b', 'a', 0.15), + ('b', 'b', 0.8), + ('b', 'c', 0.05), + ('c', 'a', 0.25), + ('c', 'b', 0.25), + ('c', 'c', 0.5) +] + +One instance of running this Markov chain might produce +{'a': 3012, 'b': 1656, 'c': 332 }. +""" + +from random import random +from typing import Dict, List, Tuple + +from DataStructures.Graph import GraphDirectedWeighted + + +def get_transition_form_node(graph: GraphDirectedWeighted, node: str) -> str: + transition = random() + curr = 0 + for neighbour in graph.connections[node]: + curr += graph.connections[node][neighbour] + if curr >= transition: + return neighbour + + +def get_transitions( + start: str, transitions: List[Tuple[str, str, float]], steps: int +) -> Dict[str, int]: + # generating graph + graph = GraphDirectedWeighted() + for (node1, node2, probability) in transitions: + graph.add_edge(node1, node2, probability) + # generating visited map + visited = {node: 0 for node in graph.connections} + node = start + for _ in range(steps): + node = get_transition_form_node(graph, node) + visited[node] += 1 + return visited + + +if __name__ == "__main__": + transitions = [ + ("a", "a", 0.9), + ("a", "b", 0.075), + ("a", "c", 0.025), + ("b", "a", 0.15), + ("b", "b", 0.8), + ("b", "c", 0.05), + ("c", "a", 0.25), + ("c", "b", 0.25), + ("c", "c", 0.5), + ] + print(get_transitions("a", transitions, 5000)) + + +""" +SPECS: + +TIME COMPLEXITY: O(steps + transition states) +SPACE COMPLEXITY: O(transition states) +""" diff --git a/Solutions/176.py b/Solutions/176.py new file mode 100644 index 0000000..cb8e175 --- /dev/null +++ b/Solutions/176.py @@ -0,0 +1,42 @@ +""" +Problem: + +Determine whether there exists a one-to-one character mapping from one string s1 to +another s2. + +For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c +and c to d. + +Given s1 = foo and s2 = bar, return false since the o cannot map to two characters. +""" + + +def check(s1: str, s2: str) -> bool: + l1, l2 = len(s1), len(s2) + # checking if each character in s1 maps to 1 character in s2 + d = {} + for i in range(l1): + if s1[i] in d and d[s1[i]] != s2[i]: + return False + d[s1[i]] = s2[i] + # checking if each character in s2 maps to 1 character in s1 + d = {} + for i in range(l2): + if s2[i] in d and d[s2[i]] != s1[i]: + return False + d[s2[i]] = s1[i] + return True + + +if __name__ == "__main__": + print(check("abc", "bcd")) + print(check("abc", "foo")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = number of characters in the strings] +""" diff --git a/Solutions/177.py b/Solutions/177.py new file mode 100644 index 0000000..3aea44e --- /dev/null +++ b/Solutions/177.py @@ -0,0 +1,51 @@ +""" +Problem: + +Given a linked list and a positive integer k, rotate the list to the right by k places. + +For example, given the linked list 7 -> 7 -> 3 -> 5 and k = 2, it should become +3 -> 5 -> 7 -> 7. + +Given the linked list 1 -> 2 -> 3 -> 4 -> 5 and k = 3, it should become +3 -> 4 -> 5 -> 1 -> 2. +""" + +from DataStructures.LinkedList import Node, LinkedList + + +def rotate_linked_list(ll: LinkedList, k: int = 0) -> None: + k = k % ll.length + + for _ in range(k): + temp = ll.head + ll.head = ll.head.next + temp.next = None + ll.rear.next = temp + ll.rear = ll.rear.next + + +if __name__ == "__main__": + LL = LinkedList() + for num in [7, 7, 3, 5]: + LL.add(num) + + print(LL) + rotate_linked_list(LL, 2) + print(LL) + print() + + LL = LinkedList() + for num in [1, 2, 3, 4, 5]: + LL.add(num) + + print(LL) + rotate_linked_list(LL, 3) + print(LL) + + +""" +SPECS: + +TIME COMPLEXITY: O(k) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/178.py b/Solutions/178.py new file mode 100644 index 0000000..5d5ac22 --- /dev/null +++ b/Solutions/178.py @@ -0,0 +1,66 @@ +""" +Problem: + +Alice wants to join her school's Probability Student Club. Membership dues are computed +via one of two simple probabilistic games. + +The first game: roll a die repeatedly. Stop rolling once you get a five followed by a +six. Your number of rolls is the amount you pay, in dollars. + +The second game: same, except that the stopping condition is a five followed by a five. + +Which of the two games should Alice elect to play? Does it even matter? Write a program +to simulate the two games and calculate their expected value. +""" + +from random import randint +from time import sleep +from typing import Tuple + + +def roll_dice() -> int: + return randint(1, 6) + + +def simulate_game(stopping_condition: Tuple[int, int], display: bool = False) -> int: + last_throw, second_last_throw = 0, 0 + required_second_last_throw, required_last_throw = stopping_condition + number_of_throws = 0 + # simulation the game + while ( + last_throw != required_last_throw + or second_last_throw != required_second_last_throw + ): + current_roll = roll_dice() + second_last_throw, last_throw = last_throw, current_roll + number_of_throws += 1 + if display: + sleep(0.1) + print(f"On {number_of_throws}th throw, value: {current_roll}") + if display: + sleep(0.1) + print(f"Total Throws: {number_of_throws}\n") + return number_of_throws + + +if __name__ == "__main__": + print("Game 1 (5, 6):") + simulate_game((5, 6), True) + print("Game 2 (5, 5):") + simulate_game((5, 5), True) + + g1 = 0 + g2 = 0 + for i in range(10_000): + g1 += simulate_game((5, 6)) + g2 += simulate_game((5, 5)) + print("Expectation of Game 1: {:.1f}".format(g1 / 10_000)) + print("Expectation of Game 2: {:.1f}".format(g2 / 10_000)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/179.py b/Solutions/179.py new file mode 100644 index 0000000..7d3fbf9 --- /dev/null +++ b/Solutions/179.py @@ -0,0 +1,40 @@ +""" +Problem: + +Given the sequence of keys visited by a postorder traversal of a binary search tree, +reconstruct the tree. + +For example, given the sequence 2, 4, 3, 8, 7, 5, you should construct the following +tree: + + 5 + / \ + 3 7 + / \ \ +2 4 8 +""" + +from typing import List + +from DataStructures.Tree import BinarySearchTree, Node + + +def bst_from_postorder(postorder: List[int]) -> BinarySearchTree: + tree = BinarySearchTree() + if postorder: + tree.add(postorder[-1]) + for val in postorder[-2::-1]: + tree.add(val) + return tree + + +if __name__ == "__main__": + print(bst_from_postorder([2, 4, 3, 8, 7, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/180.py b/Solutions/180.py new file mode 100644 index 0000000..0d38019 --- /dev/null +++ b/Solutions/180.py @@ -0,0 +1,59 @@ +""" +Problem: + +Given a stack of N elements, interleave the first half of the stack with the second +half reversed using only one other queue. This should be done in-place. + +Recall that you can only push or pop from a stack, and enqueue or dequeue from a queue. + +For example, if the stack is [1, 2, 3, 4, 5], it should become [1, 5, 2, 4, 3]. If the +stack is [1, 2, 3, 4], it should become [1, 4, 2, 3]. + +Hint: Try working backwards from the end state. +""" + +from DataStructures.Stack import Stack +from DataStructures.Queue import Queue + + +def interleave(stack: Stack) -> Stack: + queue = Queue() + # interleaving the elements + for i in range(1, len(stack)): + for _ in range(i, len(stack)): + queue.enqueue(stack.pop()) + for _ in range(len(queue)): + stack.push(queue.dequeue()) + return stack + + +if __name__ == "__main__": + stack = Stack() + + stack.push(1) + stack.push(2) + stack.push(3) + stack.push(4) + + print(stack) + print(interleave(stack)) + print() + + stack = Stack() + + stack.push(1) + stack.push(2) + stack.push(3) + stack.push(4) + stack.push(5) + + print(stack) + print(interleave(stack)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/181.py b/Solutions/181.py new file mode 100644 index 0000000..15a6cb3 --- /dev/null +++ b/Solutions/181.py @@ -0,0 +1,57 @@ +""" +Problem: + +Given a string, split it into as few strings as possible such that each string is a +palindrome. + +For example, given the input string "racecarannakayak", return +["racecar", "anna", "kayak"]. + +Given the input string "abc", return ["a", "b", "c"]. +""" + +from typing import List + + +def is_palindrome(string: str) -> bool: + return string and string == string[::-1] + + +def split_into_string_list_helper( + string: str, current: str, palindrome_list: List[str] +) -> List[str]: + if not string and not current: + return palindrome_list + elif not string: + return palindrome_list + list(current) + # generating the palindrome list + curr = current + string[0] + if is_palindrome(curr): + # adding curr to the list of palindromes + palindrome_list_1 = split_into_string_list_helper( + string[1:], "", palindrome_list + [curr] + ) + # checking if a larger palindrome can be obtained + palindrome_list_2 = split_into_string_list_helper( + string[1:], curr, palindrome_list + ) + return min(palindrome_list_1, palindrome_list_2, key=lambda List: len(List)) + return split_into_string_list_helper(string[1:], curr, palindrome_list) + + +def split_into_string_list(string: str) -> List[str]: + return split_into_string_list_helper(string, "", []) + + +if __name__ == "__main__": + print(split_into_string_list("racecarannakayak")) + print(split_into_string_list("abc")) + print(split_into_string_list("abbbc")) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/182.py b/Solutions/182.py new file mode 100644 index 0000000..231c5eb --- /dev/null +++ b/Solutions/182.py @@ -0,0 +1,62 @@ +""" +Problem: + +A graph is minimally-connected if it is connected and there is no edge that can be +removed while still leaving the graph connected. For example, any binary tree is +minimally-connected. + +Given an undirected graph, check if the graph is minimally-connected. You can choose to +represent the graph as either an adjacency matrix or adjacency list. +""" + +from copy import deepcopy + +from DataStructures.Graph import GraphUndirectedUnweighted +from DataStructures.Queue import Queue + + +def is_minimally_connected(graph: GraphUndirectedUnweighted) -> bool: + graph_copy = GraphUndirectedUnweighted() + graph_copy.connections, graph_copy.nodes = deepcopy(graph.connections), graph.nodes + # getting a random node for starting the traversal + for node in graph.connections: + start = node + break + # running bfs and checking if a node is visited more than once + # (redundant edges present => not a minimally connected graph) + visited = set([start]) + queue = Queue() + queue.enqueue(start) + while not queue.is_empty(): + node = queue.dequeue() + for neighbour in graph_copy.connections[node]: + graph_copy.connections[neighbour].remove(node) + queue.enqueue(neighbour) + if neighbour in visited: + return False + visited.add(neighbour) + return True + + +if __name__ == "__main__": + graph = GraphUndirectedUnweighted() + + graph.add_edge(1, 2) + graph.add_edge(1, 3) + graph.add_edge(3, 4) + + print(graph) + print(is_minimally_connected(graph)) + + graph.add_edge(1, 4) + + print(graph) + print(is_minimally_connected(graph)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x e) +SPACE COMPLEXITY: O(n + e) +""" diff --git a/Solutions/183.md b/Solutions/183.md new file mode 100644 index 0000000..21696cd --- /dev/null +++ b/Solutions/183.md @@ -0,0 +1,17 @@ +``` +Problem: + +Describe what happens when you type a URL into your browser and press Enter. +``` + +## Process of a URL being fetched + +1. The browser's host resolution cache is checked if the website's IP is stored. +2. If the IP is not found, a request is sent to the Domain Name Service (DNS) for the + IP of the host/load balancing host. +3. A HTTP GET request is sent to the host (server). +4. The host responds with a payload (usually in HTML). +5. Browser renders the received HTML. +6. The browser sends requests for additional objects embedded in HTML (images, CSS, + JavaScript) and repeats steps 3-4 to perform step 5. +7. Once the page is loaded, the browser sends further asynchronous requests as needed. diff --git a/Solutions/185.py b/Solutions/185.py new file mode 100644 index 0000000..a7f127a --- /dev/null +++ b/Solutions/185.py @@ -0,0 +1,70 @@ +""" +Problem: + +Given two rectangles on a 2D graph, return the area of their intersection. If the +rectangles don't intersect, return 0. + +For example, given the following rectangles: + +{ + "top_left": (1, 4), + "dimensions": (3, 3) # width, height +} + +and + +{ + "top_left": (0, 5), + "dimensions" (4, 3) # width, height +} + +return 6. +""" + +from typing import Dict, Tuple + + +def intersection( + rectangle1: Dict[str, Tuple[int, int]], rectangle2: Dict[str, Tuple[int, int]] +) -> int: + # segregating the rectangles by x-axis + if rectangle1["top_left"][0] < rectangle2["top_left"][0]: + left = rectangle1 + right = rectangle2 + else: + left = rectangle2 + right = rectangle1 + # segregating the rectangles by y-axis + if rectangle1["top_left"][1] > rectangle2["top_left"][1]: + top = rectangle1 + bottom = rectangle2 + else: + top = rectangle2 + bottom = rectangle1 + # getting the length of overlap on x-axis + if (left["top_left"][0] + left["dimensions"][0]) < right["top_left"][0]: + span_x = 0 + else: + span_x = (left["top_left"][0] + left["dimensions"][0]) - right["top_left"][0] + # getting the length of overlap on y-axis + if (top["top_left"][1] - top["dimensions"][1]) > bottom["top_left"][1]: + span_y = 0 + else: + span_y = bottom["top_left"][1] - (top["top_left"][1] - top["dimensions"][1]) + # returning the overlapped area + return span_x * span_y + + +if __name__ == "__main__": + rectangle1 = {"top_left": (1, 4), "dimensions": (3, 3)} + rectangle2 = {"top_left": (0, 5), "dimensions": (4, 3)} + + print(intersection(rectangle1, rectangle2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/186.py b/Solutions/186.py new file mode 100644 index 0000000..8947923 --- /dev/null +++ b/Solutions/186.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given an array of positive integers, divide the array into two subsets such that the +difference between the sum of the subsets is as small as possible. + +For example, given [5, 10, 15, 20, 25], return the sets {10, 25} and {5, 15, 20}, which +has a difference of 5, which is the smallest possible difference. +""" + +from typing import List, Tuple + + +def smallest_difference_sets( + arr: List[int], set1: List[int] = [], set2: List[int] = [] +) -> Tuple[List[int], List[int]]: + if not arr: + return set1, set2 + # generating the possible lists + temp = arr.pop() + temp1_1, temp2_1 = smallest_difference_sets(list(arr), set1 + [temp], list(set2)) + temp1_2, temp2_2 = smallest_difference_sets(list(arr), list(set1), set2 + [temp]) + # returning the lists with smaller difference + diff1 = abs(sum(temp1_1) - sum(temp2_1)) + diff2 = abs(sum(temp1_2) - sum(temp2_2)) + if diff1 < diff2: + return temp1_1, temp2_1 + return temp1_2, temp2_2 + + +if __name__ == "__main__": + print(smallest_difference_sets([5, 10, 15, 20, 25], [], [])) + print(smallest_difference_sets([5, 10, 15, 20], [], [])) + print(smallest_difference_sets([500, 10, 15, 20, 25], [], [])) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/187.py b/Solutions/187.py new file mode 100644 index 0000000..6842faa --- /dev/null +++ b/Solutions/187.py @@ -0,0 +1,94 @@ +""" +Problem: + +You are given given a list of rectangles represented by min and max x- and +y-coordinates. Compute whether or not a pair of rectangles overlap each other. If one +rectangle completely covers another, it is considered overlapping. + +For example, given the following rectangles: + +{ + "top_left": (1, 4), + "dimensions": (3, 3) # width, height +}, +{ + "top_left": (-1, 3), + "dimensions": (2, 1) +}, +{ + "top_left": (0, 5), + "dimensions": (4, 3) +} + +return true as the first and third rectangle overlap each other. +""" + +from typing import Dict, List, Tuple + +Rectangle = Dict[str, Tuple[int, int]] + + +def get_intersection_area(rect1: List[Rectangle], rect2: List[Rectangle]) -> int: + if rect1["top_left"][0] < rect2["top_left"][0]: + left = rect1 + right = rect2 + else: + left = rect2 + right = rect1 + if rect1["top_left"][1] > rect2["top_left"][1]: + top = rect1 + bottom = rect2 + else: + top = rect2 + bottom = rect1 + if (left["top_left"][0] + left["dimensions"][0]) < right["top_left"][0]: + return 0 + else: + span_x = (left["top_left"][0] + left["dimensions"][0]) - right["top_left"][0] + if (top["top_left"][1] - top["dimensions"][1]) > bottom["top_left"][1]: + return 0 + else: + span_y = bottom["top_left"][1] - (top["top_left"][1] - top["dimensions"][1]) + return span_x * span_y + + +def get_covered_area(rect: Rectangle) -> int: + width, height = rect["dimensions"] + return width * height + + +def check_rectangles_intersection(rectangles: List[Rectangle]) -> bool: + length = len(rectangles) + # checking for intersection for each pair of rectangles + for i in range(length - 1): + for j in range(i + 1, length): + intersection_area = get_intersection_area(rectangles[i], rectangles[j]) + rect1_area = get_covered_area(rectangles[i]) + rect2_area = get_covered_area(rectangles[j]) + if intersection_area in (rect1_area, rect2_area): + return True + return False + + +if __name__ == "__main__": + # NOTE: THE QUESTION STATEMENT IS WRONG THE RECTANGLES 1 & 3 DOES NOT OVERLAP BUT + # ONLY INTERSECT (SMALL MODIFICATION DONE TO MAKE THEM OVERLAP) + rectangles = [ + {"top_left": (1, 4), "dimensions": (3, 3)}, + {"top_left": (-1, 3), "dimensions": (2, 1)}, + {"top_left": (0, 5), "dimensions": (4, 4)}, # MODIFICATION + ] + + print(check_rectangles_intersection(rectangles)) + + rectangles.pop() + + print(check_rectangles_intersection(rectangles)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/188.py b/Solutions/188.py new file mode 100644 index 0000000..27e77ed --- /dev/null +++ b/Solutions/188.py @@ -0,0 +1,40 @@ +""" +Problem: + +What will this code print out? + +def make_functions(): + flist = [] + + for i in [1, 2, 3]: + def print_i(): + print(i) + flist.append(print_i) + + return flist + +functions = make_functions() +for f in functions: + f() + +How can we make it print out what we apparently want? +""" + +# The code will print 3 thrice (in 3 lines) as i is passed by reference + + +def make_functions(): + flist = [] + + for i in [1, 2, 3]: + + def print_i(i): + print(i) + + flist.append((print_i, i)) + return flist + + +functions = make_functions() +for f, i in functions: + f(i) diff --git a/Solutions/189.py b/Solutions/189.py new file mode 100644 index 0000000..41ba719 --- /dev/null +++ b/Solutions/189.py @@ -0,0 +1,49 @@ +""" +Problem: + +Given an array of elements, return the length of the longest subarray where all its +elements are distinct. + +For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest subarray +of distinct elements is [5, 2, 3, 4, 1]. +""" + +from typing import List + + +def max_unique_subarr(arr: List[int]) -> int: + if not arr: + return 0 + + length = len(arr) + cache = set() + max_length, window_length, window_start = 0, 0, 0 + + for i in range(length): + if arr[i] not in cache: + cache.add(arr[i]) + window_length += 1 + continue + + max_length = max(max_length, window_length) + for j in range(window_start, i): + cache.remove(arr[j]) + window_length -= 1 + if arr[j] == arr[i]: + window_start = j + cache.add(arr[j]) + window_length += 1 + break + return max(max_length, window_length) + + +if __name__ == "__main__": + print(max_unique_subarr([5, 1, 3, 5, 2, 3, 4, 1, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/190.py b/Solutions/190.py new file mode 100644 index 0000000..e174ffe --- /dev/null +++ b/Solutions/190.py @@ -0,0 +1,48 @@ +""" +Problem: + +Given a circular array, compute its maximum subarray sum in O(n) time. + +For example, given [8, -1, 3, 4], return 15 as we choose the numbers 3, 4, and 8 where +the 8 is obtained from wrapping around. + +Given [-4, 5, 1, 0], return 6 as we choose the numbers 5 and 1. +""" + +from typing import List + + +def kadane(arr: List[int]) -> int: + max_sum, curr_sum = 0, 0 + for elem in arr: + curr_sum += elem + curr_sum = max(curr_sum, 0) + max_sum = max(max_sum, curr_sum) + return max_sum + + +def max_circular_subarr(arr: List[int]) -> int: + length = len(arr) + max_kadane = kadane(arr) + # generating the maximum sum using the corner elements + max_wrap = 0 + for i in range(length): + max_wrap += arr[i] + arr[i] = -arr[i] + max_wrap += kadane(arr) + return max(max_wrap, max_kadane) + + +if __name__ == "__main__": + print(max_circular_subarr([-4, 5, 1, 0])) + print(max_circular_subarr([8, -1, 3, 4])) + print(max_circular_subarr([-8, -1, -3, -4])) + print(max_circular_subarr([8, -1, 300, -1, 4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/191.py b/Solutions/191.py new file mode 100644 index 0000000..1095ce4 --- /dev/null +++ b/Solutions/191.py @@ -0,0 +1,47 @@ +""" +Problem: + +Given a collection of intervals, find the minimum number of intervals you need to +remove to make the rest of the intervals non-overlapping. + +Intervals can "touch", such as [0, 1] and [1, 2], but they won't be considered +overlapping. + +For example, given the intervals (7, 9), (2, 4), (5, 8), return 1 as the last interval +can be removed and the first two won't overlap. + +The intervals are not necessarily sorted in any order. +""" + +from typing import List + + +def num_overlap(arr: List[int]) -> int: + time_slot_usage = [False for _ in range(max(arr, key=lambda x: x[1])[1] + 1)] + overlap_count = 0 + + for interval in arr: + start, end = interval + overlap_flag = True + for i in range(start, end): + if not time_slot_usage[i]: + time_slot_usage[i] = True + elif overlap_flag: + overlap_count += 1 + overlap_flag = False + return overlap_count + + +if __name__ == "__main__": + print(num_overlap([[0, 1], [1, 2]])) + print(num_overlap([(7, 9), (2, 4), (5, 8)])) + print(num_overlap([(7, 9), (2, 4), (5, 8), (1, 3)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = maximum ending time] +""" diff --git a/Solutions/192.py b/Solutions/192.py new file mode 100644 index 0000000..2653587 --- /dev/null +++ b/Solutions/192.py @@ -0,0 +1,40 @@ +""" +Problem: + +You are given an array of nonnegative integers. Let's say you start at the beginning of +the array and are trying to advance to the end. You can advance at most, the number of +steps that you're currently on. Determine whether you can get to the end of the array. + +For example, given the array [1, 3, 1, 2, 0, 1], we can go from indices +0 -> 1 -> 3 -> 5, so return true. + +Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false. +""" + +from typing import List + + +def can_reach_end(arr: List[int]) -> bool: + length = len(arr) + dp = [False for _ in range(length)] + dp[length - 1] = True + # generating the dp lookup + for i in range(length - 2, -1, -1): + for j in range(i + 1, min(length, i + arr[i] + 1)): + if dp[j]: + dp[i] = True + break + return dp[0] + + +if __name__ == "__main__": + print(can_reach_end([1, 3, 1, 2, 0, 1])) + print(can_reach_end([1, 2, 1, 0, 0])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/193.py b/Solutions/193.py new file mode 100644 index 0000000..801d9c3 --- /dev/null +++ b/Solutions/193.py @@ -0,0 +1,55 @@ +""" +Problem: + +Given a array of numbers representing the stock prices of a company in chronological +order, write a function that calculates the maximum profit you could have made from +buying and selling that stock. You're also given a number fee that represents a +transaction fee for each buy and sell transaction. + +You must buy before you can sell the stock, but you can make as many transactions as +you like. + +For example, given [1, 3, 2, 8, 4, 10] and fee = 2, you should return 9, since you +could buy the stock at $1, and sell at $8, and then buy it at $4 and sell it at $10. +Since we did two transactions, there is a $4 fee, so we have 7 + 6 = 13 profit minus $4 +of fees. +""" + +from typing import List + + +def get_max_profit( + prices: List[int], fee: int, profit: int = 0, current: int = 0, can_buy: bool = True +) -> int: + if not prices: + return profit + if can_buy: + return max( + get_max_profit( + prices[1:], fee, profit, (-prices[0] - fee), False + ), # buying + get_max_profit( + prices[1:], fee, profit, 0, True + ), # holding + ) + return max( + get_max_profit( + prices[1:], fee, (profit + current + prices[0]), 0, True + ), # selling + get_max_profit( + prices[1:], fee, profit, current, False + ), # holding + ) + + +if __name__ == "__main__": + print(get_max_profit([1, 3, 2, 8, 4, 10], 2)) + print(get_max_profit([1, 3, 2, 1, 4, 10], 2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/194.py b/Solutions/194.py new file mode 100644 index 0000000..cda2c32 --- /dev/null +++ b/Solutions/194.py @@ -0,0 +1,39 @@ +""" +Problem: + +Suppose you are given two lists of n points, one list p1, p2, ..., pn on the line y = 0 +and the other list q1, q2, ..., qn on the line y = 1. Imagine a set of n line segments +connecting each point pi to qi. Write an algorithm to determine how many pairs of the +line segments intersect. +""" + +from typing import List + + +def num_intersect(arr1: List[int], arr2: List[int]) -> int: + segments = list(zip(arr1, arr2)) + count = 0 + + for i in range(len(segments)): + p1_start, p1_end = segments[i] + # checking if any other points intersect it + for p2_start, p2_end in segments[:i]: + if (p1_start < p2_start and p1_end > p2_end) or ( + p1_start > p2_start and p1_end < p2_end + ): + count += 1 + return count + + +if __name__ == "__main__": + print(num_intersect([1, 2, 3, 4], [3, 2, 3, 2])) + print(num_intersect([1, 4, 5], [4, 2, 3])) + print(num_intersect([1, 4, 5], [2, 3, 4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/195.py b/Solutions/195.py new file mode 100644 index 0000000..4e9ccdb --- /dev/null +++ b/Solutions/195.py @@ -0,0 +1,52 @@ +""" +Problem: + +Let M be an N by N matrix in which every row and every column is sorted. No two +elements of M are equal. + +Given i1, j1, i2, and j2, compute the number of elements of M smaller than M[i1, j1] +and larger than M[i2, j2]. +""" + +from typing import List + + +def get_num_in_range(mat: List[List[int]], i1: int, j1: int, i2: int, j2: int) -> int: + num1, num2 = mat[i1][j1], mat[i2][j2] + count = sum([len([x for x in row if (x < num1 and x > num2)]) for row in mat]) + return count + + +if __name__ == "__main__": + mat = [ + [1, 3, 7, 10, 15, 20], + [2, 6, 9, 14, 22, 25], + [3, 8, 10, 15, 25, 30], + [10, 11, 12, 23, 30, 35], + [20, 25, 30, 35, 40, 45], + ] + print(get_num_in_range(mat, 3, 3, 1, 1)) + + matrix = [ + [1, 2, 3, 4], + [5, 8, 9, 13], + [6, 10, 12, 14], + [7, 11, 15, 16] + ] + print(get_num_in_range(matrix, 1, 3, 3, 1)) + + matrix = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [10, 11, 12, 13], + [20, 21, 22, 23] + ] + print(get_num_in_range(matrix, 3, 3, 1, 0)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/196.py b/Solutions/196.py new file mode 100644 index 0000000..650ae99 --- /dev/null +++ b/Solutions/196.py @@ -0,0 +1,78 @@ +""" +Problem: + +Given the root of a binary tree, find the most frequent subtree sum. The subtree sum of +a node is the sum of all values under a node, including the node itself. + +For example, given the following tree: + + 5 + / \ +2 -5 + +Return 2 as it occurs twice: once as the left leaf, and once as the sum of 2 + 5 - 5. +""" + +from typing import Dict + +from DataStructures.Tree import Node, BinaryTree + + +def add_to_freq_count(val: int, dictionary: Dict[int, int]) -> Dict[int, int]: + if val not in dictionary: + dictionary[val] = 0 + dictionary[val] += 1 + return dictionary + + +def get_frequent_subtree_sum_helper( + node: Node, sum_freq: Dict[int, int] = {} +) -> Dict[int, int]: + if node.left is None and node.right is None: + return add_to_freq_count(node.val, sum_freq), node.val + + elif node.left is not None and node.right is None: + sum_freq, current = get_frequent_subtree_sum_helper(node.left, sum_freq) + current += node.val + return add_to_freq_count(current, sum_freq), current + + elif node.left is None and node.right is not None: + sum_freq, current = get_frequent_subtree_sum_helper(node.right, sum_freq) + current += node.val + return add_to_freq_count(current, sum_freq), current + + sum_freq, current_left = get_frequent_subtree_sum_helper(node.left, sum_freq) + sum_freq, current_right = get_frequent_subtree_sum_helper(node.right, sum_freq) + current = current_left + node.val + current_right + return add_to_freq_count(current, sum_freq), current + + +def get_frequent_subtree_sum(tree: BinaryTree) -> int: + freq, _ = get_frequent_subtree_sum_helper(tree.root, {}) + # finding the most frequent value + modal_value, frequency = None, 0 + for key, val in freq.items(): + if val > frequency: + frequency = val + modal_value = key + return modal_value + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = Node(5) + tree.root.left = Node(2) + tree.root.right = Node(-5) + + print(tree) + + print(get_frequent_subtree_sum(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/198.py b/Solutions/198.py new file mode 100644 index 0000000..d223184 --- /dev/null +++ b/Solutions/198.py @@ -0,0 +1,55 @@ +""" +Problem: + +Given a set of distinct positive integers, find the largest subset such that every pair +of elements in the subset (i, j) satisfies either i % j = 0 or j % i = 0. + +For example, given the set [3, 5, 10, 20, 21], you should return [5, 10, 20]. Given +[1, 3, 6, 24], return [1, 3, 6, 24]. +""" + +from typing import List + + +def get_largest_subset_helper( + arr: List[int], + length: int, + prev_num: int = 1, + curr_ind: int = 0, + prev_subset: List[int] = [], +) -> List[int]: + if curr_ind == length: + return prev_subset + + curr_elem = arr[curr_ind] + res = get_largest_subset_helper(arr, prev_num, curr_ind + 1, prev_subset) + if curr_elem % prev_num == 0: + # generating the alternate result (with the element added) + alternate_res = get_largest_subset_helper( + arr, curr_elem, curr_ind + 1, prev_subset + [curr_elem] + ) + return max(alternate_res, res, key=lambda result: len(result)) + return res + + +def get_largest_subset(arr: List[int]) -> List[int]: + arr.sort() + return get_largest_subset_helper(arr, len(arr), prev_subset=[]) + + +if __name__ == "__main__": + print(get_largest_subset([])) + print(get_largest_subset([2])) + print(get_largest_subset([2, 3])) + print(get_largest_subset([3, 5, 10, 20, 21])) + print(get_largest_subset([1, 3, 6, 24])) + print(get_largest_subset([3, 9, 15, 30])) + print(get_largest_subset([2, 3, 9, 15, 30])) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/199.py b/Solutions/199.py new file mode 100644 index 0000000..0e5cfa9 --- /dev/null +++ b/Solutions/199.py @@ -0,0 +1,66 @@ +""" +Problem: + +Given a string of parentheses, find the balanced string that can be produced from it +using the minimum number of insertions and deletions. If there are multiple solutions, +return any of them. + +For example, given "(()", you could return "(())". Given "))()(", you could return +"()()()()". +""" + +from copy import deepcopy +from typing import Tuple + +from DataStructures.Stack import Stack + + +def get_min_changes_helper( + string: str, modifications: int, stack: Stack, current: str +) -> Tuple[int, str]: + if not string and stack.is_empty(): + return modifications, current + elif not string: + additions = len(stack) + return modifications + additions, current + (")" * additions) + + if string[0] == "(": + stack_added = deepcopy(stack) + stack_added.push("(") + modifications1, string1 = get_min_changes_helper( + string[1:], modifications, stack_added, current + "(" + ) # adding to stack + modifications2, string2 = get_min_changes_helper( + string[1:], modifications + 1, stack, current + ) # removing from string + return min( + [(modifications1, string1), (modifications2, string2)], + key=lambda tup: tup[0], + ) + + if not stack.is_empty(): + stack.pop() + return get_min_changes_helper(string[1:], modifications, stack, current + ")") + return get_min_changes_helper(string[1:], modifications + 1, stack, current) + + +def get_min_changes(string: str) -> str: + _, res = get_min_changes_helper(string, 0, Stack(), "") + return res + + +if __name__ == "__main__": + print(get_min_changes("(()")) + print(get_min_changes("))()(")) + print(get_min_changes("()(()")) + print(get_min_changes("()(()))")) + print(get_min_changes(")(())")) + print(get_min_changes("())(")) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(2 ^ n) +""" diff --git a/Solutions/200.py b/Solutions/200.py new file mode 100644 index 0000000..927c0f5 --- /dev/null +++ b/Solutions/200.py @@ -0,0 +1,31 @@ +""" +Problem: + +Let X be a set of n intervals on the real line. We say that a set of points P "stabs" X +if every interval in X contains at least one point in P. Compute the smallest set of +points that stabs X. + +For example, given the intervals [(1, 4), (4, 5), (7, 9), (9, 12)], you should return +[4, 9]. +""" + +from typing import List, Tuple + + +def get_stab(list_of_intervals: List[Tuple[int]]) -> Tuple[int, int]: + start, end = zip(*list_of_intervals) + return min(end), max(start) + + +if __name__ == "__main__": + print(get_stab([(1, 4), (4, 5), (7, 9), (9, 12)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[even though zip is a generator and takes O(1) space, destructuring the array takes +O(n) space] +""" diff --git a/Solutions/201.py b/Solutions/201.py new file mode 100644 index 0000000..62e9691 --- /dev/null +++ b/Solutions/201.py @@ -0,0 +1,57 @@ +""" +Problem: + +You are given an array of arrays of integers, where each array corresponds to a row in +a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle: + + 1 + 2 3 +1 5 1 +We define a path in the triangle to start at the top and go down one row at a time to +an adjacent value, eventually ending with an entry on the bottom row. For example, +1 -> 3 -> 5. The weight of the path is the sum of the entries. + +Write a program that returns the weight of the maximum weight path. +""" + +from typing import List + + +def get_maximum_weight_path(triangle: List[List[int]]) -> List[int]: + rows = len(triangle) + + if rows == 0: + return [] + elif rows == 1: + return triangle[0] + + # using dynamic programming to get the maximum weight + # elements stored as (weight, path) + dp = [list(row) for row in triangle] + for i in range(len(dp[-2])): + dp[-2][i] = ( + (max(dp[-1][i], dp[-1][i + 1]) + dp[-2][i]), + [max(dp[-1][i], dp[-1][i + 1]), dp[-2][i]], + ) + for i in range(rows - 3, -1, -1): + for j in range(i + 1): + dp[i][j] = ( + (max(dp[i + 1][j][0], dp[i + 1][j + 1][0]) + dp[i][j]), + max((dp[i + 1][j], dp[i + 1][j + 1]), key=lambda elem: elem[0])[1] + + [dp[i][j]], + ) + return dp[0][0][1][::-1] + + +if __name__ == "__main__": + print(get_maximum_weight_path([[1], [2, 3], [1, 5, 1]])) + print(get_maximum_weight_path([[1], [2, 3], [7, 5, 1]])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = number of items in the triangle] +""" diff --git a/Solutions/202.py b/Solutions/202.py new file mode 100644 index 0000000..da7409a --- /dev/null +++ b/Solutions/202.py @@ -0,0 +1,39 @@ +""" +Problem: + +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. Do not convert the integer into a +string. +""" + + +def is_palindrome(num: int) -> bool: + digits = 0 + num_copy = num + while num_copy >= 10: + digits += 1 + num_copy = num_copy // 10 + # checking for palindrome condition + for i in range((digits) // 2 + 1): + digit1 = (num // (10 ** i)) % 10 + digit2 = (num % (10 ** (digits - i + 1))) // (10 ** (digits - i)) + if digit1 != digit2: + return False + return True + + +if __name__ == "__main__": + print(is_palindrome(121)) + print(is_palindrome(888)) + print(is_palindrome(1661)) + print(is_palindrome(235)) + print(is_palindrome(678)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +[n = number of digits] +""" diff --git a/Solutions/203.py b/Solutions/203.py new file mode 100644 index 0000000..bf080ca --- /dev/null +++ b/Solutions/203.py @@ -0,0 +1,44 @@ +""" +Problem: + +Suppose an array sorted in ascending order is rotated at some pivot unknown to you +beforehand. Find the minimum element in O(log N) time. You may assume the array does +not contain duplicates. + +For example, given [5, 7, 10, 3, 4], return 3. +""" + +from typing import List + + +def find_pivot_helper(arr: List[int], low: int, high: int) -> int: + if low == high: + return high + + mid = (high + low) // 2 + if mid < high and arr[mid] > arr[mid + 1]: + return mid + elif mid > low and arr[mid] < arr[mid - 1]: + return mid - 1 + elif arr[mid] > arr[high]: + return find_pivot_helper(arr, mid + 1, high) + return find_pivot_helper(arr, low, mid - 1) + + +def find_pivot(arr: List[int]) -> int: + length = len(arr) + # the pivot returns the last index of the rotated array + pivot = find_pivot_helper(arr, 0, length) + return (pivot + 1) % length + + +if __name__ == "__main__": + print(find_pivot([5, 7, 10, 3, 4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) [python doesn't support tail recursion optimization] +""" diff --git a/Solutions/205.py b/Solutions/205.py new file mode 100644 index 0000000..265aaba --- /dev/null +++ b/Solutions/205.py @@ -0,0 +1,49 @@ +""" +Problem: + +Given an integer, find the next permutation of it in absolute order. For example, given +48975, the next permutation would be 49578. +""" + +from typing import List + + +def get_next_helper(arr: List[int]) -> List[int]: + length = len(arr) + if length < 2: + return arr + # finding the last element arranged in ascending order + for index in range(length - 1, -1, -1): + if index > 0 and arr[index - 1] < arr[index]: + break + # if index is 0, arr is sorted in descending order + if index == 0: + arr.reverse() + return arr + # finding the next permutation + for k in range(length - 1, index - 1, -1): + if arr[k] > arr[index - 1]: + arr[k], arr[index - 1] = arr[index - 1], arr[k] + break + # arranging the other elements in proper order + size = (length - 1) + index + for i in range(index, (size + 1) // 2): + arr[i], arr[size - i] = arr[size - i], arr[i] + return arr + + +def get_next(num: int) -> int: + return int("".join(get_next_helper(list(str(num))))) + + +if __name__ == "__main__": + print(get_next(48975)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = number of digits] +""" diff --git a/Solutions/206.py b/Solutions/206.py new file mode 100644 index 0000000..77b0958 --- /dev/null +++ b/Solutions/206.py @@ -0,0 +1,31 @@ +""" +Problem: + +A permutation can be specified by an array P, where P[i] represents the location of the +element at i in the permutation. For example, [2, 1, 0] represents the permutation +where elements at the index 0 and 2 are swapped. + +Given an array and a permutation, apply the permutation to the array. For example, +given the array ["a", "b", "c"] and the permutation [2, 1, 0], return ["c", "b", "a"]. +""" + +from typing import List + + +def permute(arr: List[str], p: List[int]) -> List[str]: + for i in range(len(p)): + p[i] = arr[p[i]] + return p + + +if __name__ == "__main__": + print(permute(["a", "b", "c"], [2, 1, 0])) + print(permute(["a", "b", "c", "d"], [3, 0, 1, 2])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/207.py b/Solutions/207.py new file mode 100644 index 0000000..c9195fb --- /dev/null +++ b/Solutions/207.py @@ -0,0 +1,60 @@ +""" +Problem: + +Given an undirected graph G, check whether it is bipartite. Recall that a graph is +bipartite if its vertices can be divided into two independent sets, U and V, such that +no edge connects vertices of the same set. +""" + +from DataStructures.Graph import GraphUndirectedUnweighted + + +def is_bipartite(graph: GraphUndirectedUnweighted) -> bool: + set_1, set_2 = set(), set() + sorted_nodes = sorted( + graph.connections.items(), key=lambda x: len(x[1]), reverse=True + ) + + for node, _ in sorted_nodes: + if node in set_2: + continue + set_1.add(node) + for other_node in graph.connections[node]: + set_2.add(other_node) + for node in set_2: + for other_node in graph.connections[node]: + if other_node in set_2: + return False + return True + + +if __name__ == "__main__": + graph1 = GraphUndirectedUnweighted() + + graph1.add_edge(1, 2) + graph1.add_edge(2, 3) + graph1.add_edge(1, 4) + + print(is_bipartite(graph1)) + + graph1.add_edge(1, 3) + + print(is_bipartite(graph1)) + + graph2 = GraphUndirectedUnweighted() + + graph2.add_edge(1, 2) + graph2.add_edge(2, 3) + graph2.add_edge(3, 4) + graph2.add_edge(4, 1) + + print(is_bipartite(graph2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(v + e) +SPACE COMPLEXITY: O(v) +[e = edges, v = vertices] +""" diff --git a/Solutions/208.py b/Solutions/208.py new file mode 100644 index 0000000..4c61d5e --- /dev/null +++ b/Solutions/208.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given a linked list of numbers and a pivot k, partition the linked list so that all +nodes less than k come before nodes greater than or equal to k. + +For example, given the linked list 5 -> 1 -> 8 -> 0 -> 3 and k = 3, the solution could +be 1 -> 0 -> 5 -> 8 -> 3. +""" + +from DataStructures.LinkedList import Node, LinkedList + + +def pivot_linked_list(ll: LinkedList, k: int) -> None: + ptr1, ptr2 = ll.head, ll.head + length = len(ll) + k = k % length + for _ in range(length): + if ptr2.val < k: + ptr1.val, ptr2.val = ptr2.val, ptr1.val + ptr1 = ptr1.next + ptr2 = ptr2.next + + +if __name__ == "__main__": + LL = LinkedList() + LL.add(5) + LL.add(1) + LL.add(8) + LL.add(0) + LL.add(3) + + print(LL) + + pivot_linked_list(LL, 3) + + print(LL) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/209.py b/Solutions/209.py new file mode 100644 index 0000000..b7cc8e4 --- /dev/null +++ b/Solutions/209.py @@ -0,0 +1,46 @@ +""" +Problem: + +Write a program that computes the length of the longest common subsequence of three +given strings. For example, given "epidemiologist", "refrigeration", and +"supercalifragilisticexpialodocious", it should return 5, since the longest common +subsequence is "eieio". +""" + + +def lcs_of_3(str1: str, str2: str, str3: str) -> int: + str1_length = len(str1) + str2_length = len(str2) + str3_length = len(str3) + dp_matrix = [ + [[0 for i in range(str3_length + 1)] for j in range(str2_length + 1)] + for k in range(str1_length + 1) + ] + # generating the matrix in bottom up + for i in range(1, str1_length + 1): + for j in range(1, str2_length + 1): + for k in range(1, str3_length + 1): + if str1[i - 1] == str2[j - 1] and str1[i - 1] == str3[k - 1]: + dp_matrix[i][j][k] = dp_matrix[i - 1][j - 1][k - 1] + 1 + else: + dp_matrix[i][j][k] = max( + max(dp_matrix[i - 1][j][k], dp_matrix[i][j - 1][k]), + dp_matrix[i][j][k - 1], + ) + return dp_matrix[str1_length][str2_length][str3_length] + + +if __name__ == "__main__": + print( + lcs_of_3( + "epidemiologist", "refrigeration", "supercalifragilisticexpialodocious" + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 3) +SPACE COMPLEXITY: O(n ^ 3) +""" diff --git a/Solutions/210.py b/Solutions/210.py new file mode 100644 index 0000000..c256220 --- /dev/null +++ b/Solutions/210.py @@ -0,0 +1,46 @@ +""" +Problem: + +A Collatz sequence in mathematics can be defined as follows. Starting with any positive +integer: + +If n is even, the next number in the sequence is n / 2 +If n is odd, the next number in the sequence is 3n + 1 It is conjectured that every +such sequence eventually reaches the number 1. Test this conjecture. + +Bonus: What input n <= 1000000 gives the longest sequence? +""" + +from typing import List + + +def get_collatz_sequence_length(num: int, acc: int = 0) -> int: + if num == 1: + return acc + if num % 2 == 0: + return get_collatz_sequence_length(num // 2, acc + 1) + return get_collatz_sequence_length(3 * num + 1, acc + 1) + + +def get_longest_collatz_sequence_under_1000000() -> int: + longest_sequence_value = 0 + longest_sequence = 0 + for i in range(1, 1_000_000): + curr_sequence = get_collatz_sequence_length(i, 0) + if curr_sequence > longest_sequence: + longest_sequence = curr_sequence + longest_sequence_value = i + return longest_sequence_value + + +if __name__ == "__main__": + # NOTE: brute force implementation, it will take quite a bit of time to execute + print(get_longest_collatz_sequence_under_1000000()) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/211.py b/Solutions/211.py new file mode 100644 index 0000000..c21a8da --- /dev/null +++ b/Solutions/211.py @@ -0,0 +1,67 @@ +""" +Problem: + +Given a string and a pattern, find the starting indices of all occurrences of the +pattern in the string. For example, given the string "abracadabra" and the pattern +"abr", you should return [0, 7]. +""" + +from typing import List + + +def kmp_search(string: str, pattern: str) -> List[int]: + pattern_length = len(pattern) + string_length = len(string) + lps = [0] * pattern_length + result = [] + compute_lps(pattern, pattern_length, lps) + + j = 0 + i = 0 + while i < string_length: + if pattern[j] == string[i]: + i += 1 + j += 1 + # entire pattern match + if j == pattern_length: + result.append(i - j) + j = lps[j - 1] + # mismatch after j positions + elif i < string_length and pattern[j] != string[i]: + if j != 0: + j = lps[j - 1] + else: + i += 1 + return result + + +def compute_lps(pattern: str, pattern_length: int, lps: List[int]) -> None: + length = 0 + lps[0] + i = 1 + while i < pattern_length: + # match occours + if pattern[i] == pattern[length]: + length += 1 + lps[i] = length + i += 1 + continue + if length != 0: + length = lps[length - 1] + else: + lps[i] = 0 + i += 1 + + +if __name__ == "__main__": + print(kmp_search("abracadabra", "abr")) + print(kmp_search("abracadabra", "xyz")) + print(kmp_search("aaaa", "aa")) + + +""" +SPECS: + +TIME COMPLEXITY: O(string_length + pattern_length) +SPACE COMPLEXITY: O(pattern_length) +""" diff --git a/Solutions/212.py b/Solutions/212.py new file mode 100644 index 0000000..7b51386 --- /dev/null +++ b/Solutions/212.py @@ -0,0 +1,32 @@ +""" +Problem: + +Spreadsheets often use this alphabetical encoding for its columns: "A", "B", "C", ..., +"AA", "AB", ..., "ZZ", "AAA", "AAB", .... + +Given a column number, return its alphabetical column id. For example, given 1, return +"A". Given 27, return "AA". +""" + + +def get_column_name(num: int) -> str: + result = "" + while num > 0: + result = chr(64 + (num % 26)) + result + num = num // 26 + return result + + +if __name__ == "__main__": + print(get_column_name(1)) + print(get_column_name(27)) + print(get_column_name(30)) + print(get_column_name(53)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/213.py b/Solutions/213.py new file mode 100644 index 0000000..7252360 --- /dev/null +++ b/Solutions/213.py @@ -0,0 +1,54 @@ +""" +Problem: + +Given a string of digits, generate all possible valid IP address combinations. + +IP addresses must follow the format A.B.C.D, where A, B, C, and D are numbers between +0 and 255. Zero-prefixed numbers, such as 01 and 065, are not allowed, except for 0 +itself. + +For example, given "2542540123", you should return ['254.25.40.123', '254.254.0.123']. +""" + +from typing import List + +ACCEPTABLE_NUMBERS = set([str(i) for i in range(256)]) + + +def get_ip_combinations_helper( + string: str, curr: List[str], accumulator: List[List[str]] +) -> None: + if not string and len(curr) == 4: + accumulator.append(list(curr)) + return + elif len(curr) > 4: + return + + curr_part = "" + for char in string: + curr_part += char + length = len(curr_part) + if length > 3: + return + if curr_part in ACCEPTABLE_NUMBERS: + get_ip_combinations_helper( + string[length:], list(curr) + [curr_part], accumulator + ) + + +def get_ip_combinations(string: str) -> List[str]: + accumulator = [] + get_ip_combinations_helper(string, [], accumulator) + return [".".join(combination) for combination in accumulator] + + +if __name__ == "__main__": + print(get_ip_combinations("2542540123")) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(2 ^ n) +""" diff --git a/Solutions/214.py b/Solutions/214.py new file mode 100644 index 0000000..0104dd7 --- /dev/null +++ b/Solutions/214.py @@ -0,0 +1,36 @@ +""" +Problem: + +Given an integer n, return the length of the longest consecutive run of 1s in its +binary representation. + +For example, given 156, you should return 3. +""" + + +def get_longest_chain_of_1s(num: int) -> int: + num = bin(num)[2:] + chain_max = 0 + chain_curr = 0 + + for char in num: + if char == "1": + chain_curr += 1 + else: + chain_max = max(chain_max, chain_curr) + chain_curr = 0 + return max(chain_max, chain_curr) + + +if __name__ == "__main__": + print(get_longest_chain_of_1s(15)) + print(get_longest_chain_of_1s(156)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +[there are log2(n) digits in the binary representation of any number n] +""" diff --git a/Solutions/215.py b/Solutions/215.py new file mode 100644 index 0000000..9315745 --- /dev/null +++ b/Solutions/215.py @@ -0,0 +1,83 @@ +""" +Problem: + +The horizontal distance of a binary tree node describes how far left or right the node +will be when the tree is printed out. + +More rigorously, we can define it as follows: + +The horizontal distance of the root is 0. +The horizontal distance of a left child is hd(parent) - 1. +The horizontal distance of a right child is hd(parent) + 1. +For example, for the following tree, hd(1) = -2, and hd(6) = 0. + + 5 + / \ + 3 7 + / \ / \ + 1 4 6 9 + / / + 0 8 +The bottom view of a tree, then, consists of the lowest node at each horizontal +distance. If there are two nodes at the same depth and horizontal distance, either is +acceptable. + +For this tree, for example, the bottom view could be [0, 1, 3, 6, 8, 9]. + +Given the root to a binary tree, return its bottom view. +""" + +from typing import Dict, List, Tuple + +from DataStructures.Tree import Node, BinaryTree + + +def get_bottom_view_helper( + node: Node, depth: int, hd: int, accumulator: Dict[int, Tuple[int, int]] +) -> Dict[int, Tuple[int, int]]: + if hd not in accumulator: + accumulator[hd] = (depth, node.val) + elif accumulator[hd][0] <= depth: + accumulator[hd] = (depth, node.val) + + if node.left: + get_bottom_view_helper(node.left, depth + 1, hd - 1, accumulator) + if node.right: + get_bottom_view_helper(node.right, depth + 1, hd + 1, accumulator) + return accumulator + + +def get_bottom_view(tree: BinaryTree) -> List[int]: + data = get_bottom_view_helper(tree.root, 0, 0, {}) + res_arr = [(hd, data[hd][1]) for hd in data] + res_arr.sort(key=lambda elem: elem[0]) + return [elem for _, elem in res_arr] + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(5) + + tree.root.left = Node(3) + tree.root.right = Node(7) + + tree.root.left.left = Node(1) + tree.root.left.right = Node(4) + + tree.root.right.left = Node(6) + tree.root.right.right = Node(9) + + tree.root.left.left.left = Node(0) + + tree.root.right.right.left = Node(8) + + print(tree) + print(get_bottom_view(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/216.py b/Solutions/216.py new file mode 100644 index 0000000..b51bc5d --- /dev/null +++ b/Solutions/216.py @@ -0,0 +1,52 @@ +""" +Problem: + +Given a number in Roman numeral format, convert it to decimal. + +The values of Roman numerals are as follows: + +{ + 'M': 1000, + 'D': 500, + 'C': 100, + 'L': 50, + 'X': 10, + 'V': 5, + 'I': 1 +} +In addition, note that the Roman numeral system uses subtractive notation for numbers +such as IV and XL. + +For the input XIV, for instance, you should return 14. +""" + +VALUE_MAP = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1} + + +def convert_roman_to_decimal(num_str: str) -> int: + length = len(num_str) + num = 0 + + for i in range(length - 1): + # check if the value has to be added or subtracted + if VALUE_MAP[num_str[i]] < VALUE_MAP[num_str[i + 1]]: + num -= VALUE_MAP[num_str[i]] + else: + num += VALUE_MAP[num_str[i]] + num += VALUE_MAP[num_str[length - 1]] + return num + + +if __name__ == "__main__": + print(convert_roman_to_decimal("I")) + print(convert_roman_to_decimal("IV")) + print(convert_roman_to_decimal("XIV")) + print(convert_roman_to_decimal("XL")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/217.py b/Solutions/217.py new file mode 100644 index 0000000..546b100 --- /dev/null +++ b/Solutions/217.py @@ -0,0 +1,45 @@ +""" +Problem: + +We say a number is sparse if there are no adjacent ones in its binary representation. +For example, 21 (10101) is sparse, but 22 (10110) is not. For a given input N, find the +smallest sparse number greater than or equal to N. + +Do this in faster than O(N log N) time. +""" + + +def get_next_sparse(num: int) -> int: + binary = bin(num)[2:] + new_str_bin = "" + prev_digit = None + flag = False + # generating the binary representation of the next sparse number + for i, digit in enumerate(binary): + if digit == "1" and prev_digit == "1": + flag = True + if flag: + new_str_bin += "0" * (len(binary) - i) + break + new_str_bin += digit + prev_digit = digit + if flag: + if new_str_bin[0] == "1": + new_str_bin = "10" + new_str_bin[1:] + else: + new_str_bin = "1" + new_str_bin + return int(new_str_bin, base=2) + + +if __name__ == "__main__": + print(get_next_sparse(21)) + print(get_next_sparse(25)) + print(get_next_sparse(255)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/218.py b/Solutions/218.py new file mode 100644 index 0000000..fa01bc8 --- /dev/null +++ b/Solutions/218.py @@ -0,0 +1,45 @@ +""" +Problem: + +Write an algorithm that computes the reversal of a directed graph. For example, if a +graph consists of A -> B -> C, it should become A <- B <- C. +""" + +from DataStructures.Graph import GraphDirectedUnweighted + + +def reverse_direction(graph: GraphDirectedUnweighted) -> None: + visited = set() + for node in graph.connections: + # storing the nodes that require updation in to change as for loop doesn't + # support simultaneous updation + visited.add(node) + to_change = [] + for neighbour in graph.connections[node]: + if neighbour not in visited: + if node not in graph.connections[neighbour]: + to_change.append(neighbour) + for neighbour in to_change: + graph.connections[neighbour].add(node) + graph.connections[node].remove(neighbour) + + +if __name__ == "__main__": + graph = GraphDirectedUnweighted() + + graph.add_edge("A", "B") + graph.add_edge("B", "C") + + print(graph) + + reverse_direction(graph) + + print(graph) + + +""" +SPECS: + +TIME COMPLEXITY: O(v + e) +SPACE COMPLEXITY: O(v) +""" diff --git a/Solutions/219.py b/Solutions/219.py new file mode 100644 index 0000000..680de51 --- /dev/null +++ b/Solutions/219.py @@ -0,0 +1,121 @@ +""" +Problem: + +Connect 4 is a game where opponents take turns dropping red or black discs into a 7 x 6 +vertically suspended grid. The game ends either when one player creates a line of four +consecutive discs of their color (horizontally, vertically, or diagonally), or when +there are no more spots left in the grid. + +Design and implement Connect 4. +""" + +from typing import Optional + + +class Connect4: + def __init__(self) -> None: + self.board = [["-" for _ in range(7)] for _ in range(6)] + self.to_play = "R" + + def get_empty(self, position: int) -> int: + if self.board[0][position] != "-": + return -1 + if self.board[5][position] == "-": + return 5 + + for i in range(5): + if self.board[i][position] == "-" and self.board[i + 1][position] != "-": + return i + + def play_turn(self) -> None: + position = int(input("Enter the location to put the disk: ")) + position -= 1 + row = self.get_empty(position) + + while row == -1: + position = int(input("Enter the location to put the disk: ")) + position -= 1 + row = self.get_empty(position) + + if self.to_play == "R": + self.board[row][position] = "R" + self.to_play = "B" + else: + self.board[row][position] = "B" + self.to_play = "R" + + def victory_check(self) -> Optional[str]: + # horizontal check + for i in range(6): + for j in range(4): + if self.board[i][j] in ("R", "B"): + disk = self.board[i][j] + for k in range(j, j + 4): + if self.board[i][k] != disk: + break + else: + return disk + # vertical check + for i in range(3): + for j in range(7): + if self.board[i][j] in ("R", "B"): + disk = self.board[i][j] + for k in range(i, i + 4): + if self.board[k][j] != disk: + break + else: + return disk + # top left to bottom right diagonal check + for i in range(2): + for j in range(3): + if self.board[i][j] in ("R", "B"): + disk = self.board[i][j] + for k in range(4): + if self.board[i + k][j + k] != disk: + break + else: + return disk + # top right to bottom left diagonal check + for i in range(3, 6): + for j in range(4, 7): + if self.board[i][j] in ("R", "B"): + disk = self.board[i][j] + for k in range(4): + if self.board[i - k][j - k] != disk: + break + else: + return disk + return None + + def full_check(self) -> bool: + for i in range(6): + for j in range(7): + if self.board[i][j] == "-": + return False + return True + + def print_board(self) -> None: + for i in range(6): + for j in range(7): + print(self.board[i][j], end=" ") + print() + + def play(self) -> None: + while not self.full_check() and not self.victory_check(): + try: + print(self.to_play, "to play") + self.play_turn() + print("Board: ") + self.print_board() + print() + except IndexError: + print("Illegal move!") + + if self.full_check(): + print("Its a draw") + else: + print("{} has won".format(self.victory_check())) + + +if __name__ == "__main__": + Connect4().play() diff --git a/Solutions/220.py b/Solutions/220.py new file mode 100644 index 0000000..b987213 --- /dev/null +++ b/Solutions/220.py @@ -0,0 +1,41 @@ +""" +Problem: + +In front of you is a row of N coins, with values v_1, v_2, ..., v_n. + +You are asked to play the following game. You and an opponent take turns choosing +either the first or last coin from the row, removing it from the row, and receiving the +value of the coin. + +Write a program that returns the maximum amount of money you can win with certainty, if +you move first, assuming your opponent plays optimally. +""" + +from typing import List + + +def optimal_strategy_of_game( + coins_arr: List[int], amount: int = 0, to_play: bool = True +) -> int: + if not coins_arr: + return amount + if to_play: + return max( + optimal_strategy_of_game(coins_arr[1:], amount + coins_arr[0], False), + optimal_strategy_of_game(coins_arr[:-1], amount + coins_arr[-1], False), + ) + if coins_arr[0] > coins_arr[-1]: + return optimal_strategy_of_game(coins_arr[1:], amount, True) + return optimal_strategy_of_game(coins_arr[:-1], amount, True) + + +if __name__ == "__main__": + print(optimal_strategy_of_game([1, 2, 3, 4, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/221.py b/Solutions/221.py new file mode 100644 index 0000000..3e218a1 --- /dev/null +++ b/Solutions/221.py @@ -0,0 +1,41 @@ +""" +Problem: + +Let's define a "sevenish" number to be one which is either a power of 7, or the sum of +unique powers of 7. The first few sevenish numbers are 1, 7, 8, 49, and so on. Create +an algorithm to find the nth sevenish number. +""" + + +def get_nth_sevenish_num(number: int) -> int: + curr = 1 + curr_iteration = 1 + while curr < number: + curr_iteration += 1 + curr += curr_iteration + + curr -= curr_iteration + result = 7 ** (curr_iteration - 1) + curr_to_add = 1 + + for _ in range(number - curr - 1): + result += curr_to_add + curr_to_add *= 7 + return result + + +if __name__ == "__main__": + print(get_nth_sevenish_num(1)) # 1 = 7 ^ 0 + print(get_nth_sevenish_num(2)) # 7 = 7 ^ 1 + print(get_nth_sevenish_num(3)) # 8 = 7 ^ 0 + 7 ^ 1 + print(get_nth_sevenish_num(4)) # 49 = 7 ^ 2 + print(get_nth_sevenish_num(5)) # 50 = 7 ^ 0 + 7 ^ 2 + print(get_nth_sevenish_num(6)) # 57 = 7 ^ 0 + 7 ^ 1 + 7 ^ 2 + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/222.py b/Solutions/222.py new file mode 100644 index 0000000..6abe256 --- /dev/null +++ b/Solutions/222.py @@ -0,0 +1,36 @@ +""" +Problem: + +Given an absolute pathname that may have . or .. as part of it, return the shortest +standardized path. + +For example, given /usr/bin/../bin/./scripts/../, return /usr/bin/. +""" + +from DataStructures.Stack import Stack + + +def get_shortest_standardized_path(path: str) -> str: + path_list = path.split("/") + stack = Stack() + + for curr_directory in path_list: + if curr_directory == ".": + continue + elif curr_directory == "..": + stack.pop() + else: + stack.push(curr_directory) + return "/".join(stack) + + +if __name__ == "__main__": + print(get_shortest_standardized_path("/usr/bin/../bin/./scripts/../")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/223.py b/Solutions/223.py new file mode 100644 index 0000000..68e31cb --- /dev/null +++ b/Solutions/223.py @@ -0,0 +1,61 @@ +""" +Problem: + +Typically, an implementation of in-order traversal of a binary tree has O(h) space +complexity, where h is the height of the tree. Write a program to compute the in-order +traversal of a binary tree using O(1) space. +""" + +from typing import Generator + +from DataStructures.Tree import BinaryTree, Node + + +def morris_traversal(tree: BinaryTree) -> Generator[int, None, None]: + current = tree.root + + while current is not None: + if current.left is None: + yield current.val + current = current.right + continue + # Find the inorder predecessor of current + pre = current.left + while pre.right is not None and pre.right is not current: + pre = pre.right + if pre.right is None: + # Make current as right child of its inorder predecessor + pre.right = current + current = current.left + else: + # Revert the changes made in the 'if' part to restore the + # original tree. (Fix the right child of predecessor) + pre.right = None + yield current.val + current = current.right + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = Node(1) + + tree.root.left = Node(2) + tree.root.right = Node(3) + + tree.root.left.left = Node(4) + tree.root.left.right = Node(5) + + tree.root.right.right = Node(6) + + print(tree) + for node in morris_traversal(tree): + print(node, end=" ") + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/225.py b/Solutions/225.py new file mode 100644 index 0000000..05fc000 --- /dev/null +++ b/Solutions/225.py @@ -0,0 +1,43 @@ +""" +Problem: + +There are N prisoners standing in a circle, waiting to be executed. The executions are +carried out starting with the kth person, and removing every successive kth person +going clockwise until there is no one left. + +Given N and k, write an algorithm to determine where a prisoner should stand in order +to be the last survivor. + +For example, if N = 5 and k = 2, the order of executions would be [2, 4, 1, 5, 3], so +you should return 3. + +Bonus: Find an O(log N) solution if k = 2. +""" + +from typing import Optional + + +def find_last_executed(n: int, k: int) -> Optional[int]: + prisoners = [i for i in range(1, n + 1)] + last_executed = None + curr_pos = 0 + + while prisoners: + curr_pos = (curr_pos + k - 1) % len(prisoners) + last_executed = prisoners[curr_pos] + prisoners = prisoners[:curr_pos] + prisoners[curr_pos + 1 :] + return last_executed + + +if __name__ == "__main__": + print(find_last_executed(5, 2)) + print(find_last_executed(3, 2)) + print(find_last_executed(5, 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/226.py b/Solutions/226.py new file mode 100644 index 0000000..aabde46 --- /dev/null +++ b/Solutions/226.py @@ -0,0 +1,78 @@ +""" +Problem: + +You come across a dictionary of sorted words in a language you've never seen before. +Write a program that returns the correct order of letters in this language. + +For example, given ['xww', 'wxyz', 'wxyw', 'ywx', 'ywz'], you should return +['x', 'z', 'w', 'y']. +""" + +from typing import Dict, List, Optional, Set + + +def update_letter_order(sorted_words: List[str], letters: Dict[str, Set[str]]) -> None: + order = [] + new_words = {} + prev_char = None + + for word in sorted_words: + if word: + char = word[0] + if char != prev_char: + order.append(char) + if char not in new_words: + new_words[char] = list() + new_words[char].append(word[1:]) + prev_char = char + + for index, char in enumerate(order): + letters[char] = letters[char] | set(order[index + 1 :]) + for char in new_words: + update_letter_order(new_words[char], letters) + + +def find_path( + letters: Dict[str, Set[str]], start: str, path: List[str], length: int +) -> Optional[List[str]]: + if len(path) == length: + return path + if not letters[start]: + return None + + for next_start in letters[start]: + new_path = find_path(letters, next_start, path + [next_start], length) + if new_path: + return new_path + + +def get_letter_order(sorted_words: List[str]): + letters = {} + for word in sorted_words: + for letter in word: + if letter not in letters: + letters[letter] = set() + + update_letter_order(sorted_words, letters) + + max_children = max([len(x) for x in letters.values()]) + potential_heads = [x for x in letters if len(letters[x]) == max_children] + + path = None + for head in potential_heads: + path = find_path(letters, head, path=[head], length=len(letters)) + if path: + break + return path + + +if __name__ == "__main__": + print(get_letter_order(["xww", "wxyz", "wxyw", "ywx", "ywz"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(words x letters + words ^ 2 + letters ^ 2) +SPACE COMPLEXITY: O(words x letters) +""" diff --git a/Solutions/227.py b/Solutions/227.py new file mode 100644 index 0000000..5164a86 --- /dev/null +++ b/Solutions/227.py @@ -0,0 +1,87 @@ +""" +Problem: + +Boggle is a game played on a 4 x 4 grid of letters. The goal is to find as many words +as possible that can be formed by a sequence of adjacent letters in the grid, using +each cell at most once. Given a game board and a dictionary of valid words, implement a +Boggle solver. +""" + +from typing import List, Set, Tuple + +from DataStructures.Trie import Trie + +Matrix = List[List[str]] +Position = Tuple[int, int] + + +def get_neighbours(position: Position) -> List[Position]: + i, j = position + neighbours = [] + all_neighbours = [ + (i - 1, j - 1), + (i - 1, j), + (i - 1, j + 1), + (i, j + 1), + (i + 1, j + 1), + (i + 1, j), + (i + 1, j - 1), + (i, j - 1), + ] + for y, x in all_neighbours: + if 0 <= x < 4 and 0 <= y < 4: + neighbours.append((y, x)) + return neighbours + + +def get_words( + matrix: Matrix, position: Position, trie: Trie, curr: str, result: Set[str] +) -> None: + possibilities = trie.get_suggestions(curr) + + if not possibilities: + return + if len(possibilities) == 1 and list(possibilities)[0] == curr: + result.add(curr) + return + + for neighbour in get_neighbours(position): + i, j = neighbour + get_words(matrix, neighbour, trie, curr + matrix[i][j], result) + return + + +def solve_Boggle(matrix: Matrix, dictionary: Set[str]) -> Set[str]: + prefix_tree = Trie() + prefix_tree.add_words(dictionary) + result = set() + # generating the resultant words + for i in range(4): + for j in range(4): + if matrix[i][j] in prefix_tree.root.children: + get_words(matrix, (i, j), prefix_tree, matrix[i][j], result) + return result + + +if __name__ == "__main__": + board = [ + ["A", "L", "B", "P"], + ["C", "O", "E", "Y"], + ["F", "C", "H", "O"], + ["B", "A", "D", "A"], + ] + words_in_board = {"PECH", "COLA", "YO", "BAD"} + words_not_in_board = {"FOR", "BULL"} + dictionary = words_in_board | words_not_in_board + + print(dictionary) + print(solve_Boggle(board, dictionary)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +[size of board is 4 x 4 (constant)] +""" diff --git a/Solutions/228.py b/Solutions/228.py new file mode 100644 index 0000000..09402bc --- /dev/null +++ b/Solutions/228.py @@ -0,0 +1,41 @@ +""" +Problem: + +Given a list of numbers, create an algorithm that arranges them in order to form the +largest possible integer. For example, given [10, 7, 76, 415], you should return +77641510. +""" + +from __future__ import annotations +from typing import List + + +class CustomInt: + def __init__(self, value: int) -> None: + self.value = str(value) + + def __lt__(self, other: CustomInt) -> bool: + for c1, c2 in zip(self.value + other.value, other.value + self.value): + if c1 > c2: + return False + elif c1 < c2: + return True + return False + + +def get_largest(arr: List[int]) -> int: + arr = list(map(CustomInt, arr)) + arr.sort(reverse=True) + return int("".join(map(lambda x: x.value, arr))) + + +if __name__ == "__main__": + print(get_largest([10, 7, 76, 415])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/229.py b/Solutions/229.py new file mode 100644 index 0000000..a060d1f --- /dev/null +++ b/Solutions/229.py @@ -0,0 +1,86 @@ +""" +Problem: + +Snakes and Ladders is a game played on a 10 x 10 board, the goal of which is get from square 1 to square 100. +On each turn players will roll a six-sided die and move forward a number of spaces equal to the result. +If they land on a square that represents a snake or ladder, they will be transported ahead or behind, respectively, to a new square. +Find the smallest number of turns it takes to play snakes and ladders. + +For convenience, here are the squares representing snakes and ladders, and their outcomes: +snakes = {16: 6, 48: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73, 95: 75, 98: 78} +ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100} +""" + +from typing import Dict + + +def get_next_ladder_position(ladders: Dict[int, int], position: int): + # helper function to get the position of the next ladder + curr = 101 + for key in ladders: + if key > position and key < curr: + curr = key + return curr + + +def get_next_position_with_no_snake(snakes: Dict[int, int], position: int) -> int: + # helper function to get the position of the next move without landing on a snake + curr = position + 6 + for _ in range(6): + if curr not in snakes: + break + curr -= 1 + return curr + + +def play_snake_and_ladders( + snakes: Dict[int, int], ladders: Dict[int, int], show_trace: bool = False +) -> int: + # function to return the minimum turns required to play the current board + position = 0 + turns = 0 + while position < 100: + turns += 1 + position = min( + get_next_ladder_position(ladders, position), + get_next_position_with_no_snake(snakes, position), + 100, + ) + if show_trace: + print(position, end=" ") + if position in ladders: + position = ladders[position] + if show_trace: + print(f"=> {position}", end=" ") + if position < 100 and show_trace: + print("->", end=" ") + if show_trace: + print() + return turns + + +if __name__ == "__main__": + snakes = { + 16: 6, + 48: 26, + 49: 11, + 56: 53, + 62: 19, + 64: 60, + 87: 24, + 93: 73, + 95: 75, + 98: 78, + } + ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100} + + print(play_snake_and_ladders(snakes, ladders, show_trace=True)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +[the maximum number of squares is 100] +""" diff --git a/Solutions/230.py b/Solutions/230.py new file mode 100644 index 0000000..d63b214 --- /dev/null +++ b/Solutions/230.py @@ -0,0 +1,47 @@ +""" +Problem: + +You are given N identical eggs and access to a building with k floors. +Your task is to find the lowest floor that will cause an egg to break, if dropped from that floor. +Once an egg breaks, it cannot be dropped again. +If an egg breaks when dropped from the xth floor, you can assume it will also break when dropped from any floor greater than x. +Write an algorithm that finds the minimum number of trial drops it will take, in the worst case, to identify this floor. + +Example: + +N = 1 +k = 5 +Output = 5 (we will need to try dropping the egg at every floor, beginning with the first, until we reach the fifth floor) +""" + +from sys import maxsize + + +def calculate(eggs: int, floors: int) -> int: + dp_mat = [[maxsize for _ in range(floors + 1)] for _ in range(eggs + 1)] + # base cases + for i in range(floors + 1): + dp_mat[1][i] = i + dp_mat[0][i] = 0 + for i in range(eggs + 1): + dp_mat[i][0] = 0 + # populating the dp matrix + for egg in range(2, eggs + 1): + for floor in range(1, floors + 1): + for i in range(1, floor + 1): + temp = 1 + max(dp_mat[egg - 1][i - 1], dp_mat[egg][floor - i]) + dp_mat[egg][floor] = min(dp_mat[egg][floor], temp) + return dp_mat[eggs][floors] + + +if __name__ == "__main__": + print(calculate(2, 20)) + print(calculate(3, 15)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x (floor ^ 2)) +SPACE COMPLEXITY: O(n x floor) +""" diff --git a/Solutions/231.py b/Solutions/231.py new file mode 100644 index 0000000..5e4277f --- /dev/null +++ b/Solutions/231.py @@ -0,0 +1,80 @@ +""" +Problem: + +Given a string with repeated characters, rearrange the string so that no two adjacent +characters are the same. If this is not possible, return None. + +For example, given "aaabbc", you could return "ababac". Given "aaab", return None. +""" + +from typing import Optional + +from DataStructures.Queue import Queue + + +def get_unique_adjacent(string: str) -> Optional[str]: + length = len(string) + freq = {} + if length == 0: + return string + + for i in range(length): + if string[i] not in freq: + freq[string[i]] = 0 + freq[string[i]] += 1 + + sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) + queue = Queue() + [queue.enqueue(item) for item in sorted_freq] + result = "" + + if length % 2 == 0 and sorted_freq[0][1] > length // 2: + return None + elif length % 2 == 1 and sorted_freq[0][1] > (length // 2) + 1: + return None + + while not queue.is_empty(): + if len(queue) == 1: + elem, freq = queue.peek() + if freq == 2: + result = elem + result + elem + break + elif freq == 1: + if result[-1] != elem: + result += elem + else: + result = elem + result + break + return None + + elem1, freq1 = queue.peek() + elem2, freq2 = None, None + if len(queue) > 1: + elem2, freq2 = queue[1] + + result += elem1 + elem2 + + queue[0] = elem1, freq1 - 1 + if len(queue) > 1: + queue[1] = elem2, freq2 - 1 + if len(queue) > 1 and queue[1][1] == 0: + queue.dequeue() + if len(queue) > 0 and queue[0][1] == 0: + queue.dequeue() + return result + + +if __name__ == "__main__": + print(get_unique_adjacent("aaabbc")) + print(get_unique_adjacent("aaabbcc")) + print(get_unique_adjacent("aaabbac")) + print(get_unique_adjacent("aaab")) + print(get_unique_adjacent("aaabbaa")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/232.py b/Solutions/232.py new file mode 100644 index 0000000..6c28382 --- /dev/null +++ b/Solutions/232.py @@ -0,0 +1,46 @@ +""" +Problem: + +Implement a PrefixMapSum class with the following methods: + +insert(key: str, value: int): Set a given key's value in the map. If the key already +exists, overwrite the value. +sum(prefix: str): Return the sum of all values of keys that begin with a given prefix. + +For example, you should be able to run the following code: + +>>> mapsum.insert("columnar", 3) +>>> assert mapsum.sum("col") == 3 +>>> mapsum.insert("column", 2) +>>> assert mapsum.sum("col") == 5 +""" + +from DataStructures.Trie import Trie + + +class PrefixMapSum: + def __init__(self) -> None: + self.trie = Trie() + self.hash_map = {} + + def insert(self, key: str, value: int) -> None: + if key not in self.hash_map: + self.trie.add(key) + self.hash_map[key] = value + + def sum(self, prefix: str) -> int: + words = self.trie.get_suggestions(prefix) + result = 0 + for word in words: + result += self.hash_map[word] + return result + + +if __name__ == "__main__": + mapsum = PrefixMapSum() + + mapsum.insert("columnar", 3) + assert mapsum.sum("col") == 3 + + mapsum.insert("column", 2) + assert mapsum.sum("col") == 5 diff --git a/Solutions/233.py b/Solutions/233.py new file mode 100644 index 0000000..f280adb --- /dev/null +++ b/Solutions/233.py @@ -0,0 +1,26 @@ +""" +Problem: + +Implement the function fib(n), which returns the nth number in the Fibonacci sequence, +using only O(1) space. +""" + + +def fib(n: int) -> int: + curr, last = 1, 0 + for _ in range(n - 1): + curr, last = last + curr, curr + return curr + + +if __name__ == "__main__": + for i in range(1, 11): + print(f"Fib {i}:\t{fib(i)}") + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/234.py b/Solutions/234.py new file mode 100644 index 0000000..d5672c0 --- /dev/null +++ b/Solutions/234.py @@ -0,0 +1,73 @@ +""" +Problem: + +Recall that the minimum spanning tree is the subset of edges of a tree that connect all +its vertices with the smallest possible total edge weight. Given an undirected graph +with weighted edges, compute the maximum weight spanning tree. +""" + +from typing import Set + +from DataStructures.Graph import GraphUndirectedWeighted + + +def get_maximum_spanning_tree_helper( + graph: GraphUndirectedWeighted, + curr_node: int, + remaining_nodes: Set[int], + weight: int, +) -> int: + if not remaining_nodes: + return weight + + scores = [] + for destination in graph.connections[curr_node]: + if destination in remaining_nodes: + rem_cp = set(remaining_nodes) + rem_cp.remove(destination) + new_score = get_maximum_spanning_tree_helper( + graph, + destination, + rem_cp, + weight + graph.connections[curr_node][destination], + ) + scores.append(new_score) + return max(scores) + + +def get_maximum_spanning_tree(graph: GraphUndirectedWeighted) -> int: + node_set = set(graph.connections.keys()) + start_node = node_set.pop() + + weight = get_maximum_spanning_tree_helper(graph, start_node, node_set, 0) + return weight + + +if __name__ == "__main__": + graph = GraphUndirectedWeighted() + + graph.add_edge(1, 2, 5) + graph.add_edge(1, 3, 2) + graph.add_edge(3, 2, 1) + graph.add_edge(3, 4, 3) + graph.add_edge(2, 4, 4) + + print(graph) + print(get_maximum_spanning_tree(graph)) + + graph = GraphUndirectedWeighted() + + graph.add_edge(1, 2, 1) + graph.add_edge(1, 3, 2) + graph.add_edge(3, 2, 3) + + print(graph) + print(get_maximum_spanning_tree(graph)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x e) +SPACE COMPLEXITY: O(n x e) +""" diff --git a/Solutions/235.py b/Solutions/235.py new file mode 100644 index 0000000..d696963 --- /dev/null +++ b/Solutions/235.py @@ -0,0 +1,47 @@ +""" +Problem: + +Given an array of numbers of length N, find both the minimum and maximum using less +than 2 * (N - 2) comparisons. +""" + +from typing import List, Tuple + + +def get_min_max(arr: List[int]) -> Tuple[int, int]: + if not arr: + return None, None + + length = len(arr) + if length % 2 == 0: + max_elem = max(arr[0], arr[1]) + min_elem = min(arr[0], arr[1]) + start = 2 + else: + max_elem = min_elem = arr[0] + start = 1 + + # reducing the number of comparisons by comparing the array elements with themselves + # effective comparisons is 3 for every 2 elements + for i in range(start, length, 2): + if arr[i] < arr[i + 1]: + max_elem = max(max_elem, arr[i + 1]) + min_elem = min(min_elem, arr[i]) + continue + max_elem = max(max_elem, arr[i]) + min_elem = min(min_elem, arr[i + 1]) + + return min_elem, max_elem + + +if __name__ == "__main__": + print(get_min_max([1000, 11, 445, 1, 330, 3000])) + print(get_min_max([1000, 11, 445, 1, -330])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/236.py b/Solutions/236.py new file mode 100644 index 0000000..8d17091 --- /dev/null +++ b/Solutions/236.py @@ -0,0 +1,73 @@ +""" +Problem: + +You are given a list of N points (x1, y1), (x2, y2), ..., (xN, yN) representing a +polygon. You can assume these points are given in order; that is, you can construct the +polygon by connecting point 1 to point 2, point 2 to point 3, and so on, finally +looping around to connect point N to point 1. + +Determine if a new point p lies inside this polygon. (If p is on the boundary of the +polygon, you should return False). +""" + +from typing import List, Tuple + +Point = Tuple[int, int] + + +def is_inside(points: List[Point], p: Point) -> bool: + # Using the following concept: + # if a stright line in drawn from the point p to its right (till infinity), the + # drawn line will intersect the lines connecting the points odd number of times + # (if p is enclosed by the points) else the the number of intersections will be + # even (implying its outside the figure created by the points) + + # Details: + # https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon + + if len(points) in (0, 1, 2): + return False + + x, y = p + last = points[0] + intersections = 0 + same_height = set() + + for point in points[1:]: + x1, y1 = last + x2, y2 = point + if min(y1, y2) <= y <= max(y1, y2) and x <= min(x1, x2): + if y2 == y and point not in same_height: + intersections += 1 + same_height.add(point) + elif y1 == y and last not in same_height: + intersections += 1 + same_height.add(last) + last = point + + point = points[0] + x1, y1 = last + x2, y2 = point + if max(y1, y2) >= y >= min(y1, y2) and x <= min(x1, x2): + if y2 == y and point not in same_height: + intersections += 1 + same_height.add(point) + elif y1 == y and last not in same_height: + intersections += 1 + same_height.add(last) + if intersections % 2 == 1: + return True + return False + + +if __name__ == "__main__": + print(is_inside([(4, 3), (5, 4), (6, 3), (5, 2)], (3, 3))) + print(is_inside([(4, 3), (5, 4), (6, 3), (5, 2)], (5, 3))) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/238.py b/Solutions/238.py new file mode 100644 index 0000000..635622d --- /dev/null +++ b/Solutions/238.py @@ -0,0 +1,71 @@ +""" +Problem: + +Blackjack is a two player card game whose rules are as follows: + +- The player and then the dealer are each given two cards. +- The player can then "hit", or ask for arbitrarily many additional cards, so long as + their total does not exceed 21. +- The dealer must then hit if their total is 16 or lower, otherwise pass. +- Finally, the two compare totals, and the one with the greatest sum not exceeding 21 + is the winner. + +For this problem, cards values are counted as follows: each card between 2 and 10 +counts as their face value, face cards count as 10, and aces count as 1. + +Given perfect knowledge of the sequence of cards in the deck, implement a blackjack +solver that maximizes the player's score (that is, wins minus losses). +""" + +from random import shuffle +from typing import List, Tuple + + +def generate_random_card_sequence() -> List[int]: + cards = [i for _ in range(4) for i in range(1, 11)] + shuffle(cards) + return cards + + +def get_best_player_score( + sequence: List[int], player_score: int = 0, dealer_score: int = 0 +) -> Tuple[int, int]: + if not sequence: + return player_score, dealer_score + elif player_score > 21 and dealer_score > 21: + return -1, -1 + elif player_score > 21: + return -1, dealer_score + elif dealer_score > 21: + return player_score, -1 + return max( + get_best_player_score(sequence[1:], player_score + sequence[0], dealer_score), + get_best_player_score(sequence[1:], player_score, dealer_score + sequence[0]), + (player_score, dealer_score), + # the player's score has more weightage than the dealer's score + key=lambda x: 1.01 * x[0] + x[1], + ) + + +def simulate(n: int = 1_000) -> float: + # simulating the game n times and returning the percent of victories for the player + wins = 0 + for _ in range(n): + sequence = generate_random_card_sequence() + player_score, dealer_score = get_best_player_score(sequence) + if player_score > dealer_score and player_score <= 21: + wins += 1 + return (wins / n) * 100 + + +if __name__ == "__main__": + print(f"The Player won {simulate():.2f}% of the times") + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +[the number of cards is constant (52)] +""" diff --git a/Solutions/239.py b/Solutions/239.py new file mode 100644 index 0000000..226aa03 --- /dev/null +++ b/Solutions/239.py @@ -0,0 +1,99 @@ +""" +Problem: + +One way to unlock an Android phone is through a pattern of swipes across a 1-9 keypad. +For a pattern to be valid, it must satisfy the following: +* All of its keys must be distinct. +* It must not connect two keys by jumping over a third key, unless that key has already been used. +For example, 4 - 2 - 1 - 7 is a valid pattern, whereas 2 - 1 - 7 is not. +Find the total number of valid unlock patterns of length N, where 1 <= N <= 9. +""" + +from copy import deepcopy +from typing import Set + + +class Dialpad: + def __init__(self) -> None: + self.nodes = set(range(1, 10)) + self.edges = {} + self.edges[1] = {2, 4, 5, 6, 8} + self.edges[2] = {1, 3, 4, 5, 6, 7, 9} + self.edges[3] = {2, 4, 5, 6, 8} + self.edges[4] = {1, 2, 3, 5, 7, 8, 9} + self.edges[5] = {1, 2, 3, 4, 6, 7, 8, 9} + self.edges[6] = {1, 2, 3, 5, 7, 8, 9} + self.edges[7] = {2, 4, 5, 6, 8} + self.edges[8] = {1, 4, 3, 5, 6, 7, 9} + self.edges[9] = {2, 4, 5, 6, 8} + + def update_connections(self, curr: int) -> None: + if 2 == curr: + self.edges[1].add(3) + self.edges[3].add(1) + elif 4 == curr: + self.edges[1].add(7) + self.edges[7].add(1) + elif 6 == curr: + self.edges[9].add(3) + self.edges[3].add(9) + elif 8 == curr: + self.edges[7].add(9) + self.edges[9].add(7) + elif 5 == curr: + self.edges[1].add(9) + self.edges[9].add(1) + self.edges[7].add(3) + self.edges[3].add(7) + self.edges[2].add(8) + self.edges[8].add(2) + self.edges[4].add(6) + self.edges[6].add(4) + + +def count_code_helper(dp: Dialpad, code_length: int, curr: int, seen: Set[int]) -> int: + # helper function to trace the patterns and get the number of combinations + if code_length == 0: + return 1 + seen_cp = deepcopy(seen) + seen_cp.add(curr) + + copied_dp = deepcopy(dp) + copied_dp.update_connections(curr) + nodes = dp.edges[curr] + sub_count = 0 + + for node in nodes: + if node not in seen_cp: + sub_count += count_code_helper(copied_dp, code_length - 1, node, seen_cp) + return sub_count + + +def count_codes_of_n_length(dp: Dialpad, code_length: int) -> int: + if code_length == 1: + return len(dp.nodes) + count = 0 + for node in dp.nodes: + count += count_code_helper(dp, code_length, node, set()) + return count + + +def get_number_of_valid_unlock_patterns() -> int: + dp = Dialpad() + result = 0 + for n in range(1, 10): + result += count_codes_of_n_length(dp, n) + return result + + +if __name__ == "__main__": + # NOTE: computationally intensive operation as the number of patterns is really high + print(get_number_of_valid_unlock_patterns()) + + +""" +SPECS: + +TIME COMPLEXITY: O((nodes ^ 2) x (code length ^ 2)) +SPACE COMPLEXITY: O((nodes ^ 2) x code length) +""" diff --git a/Solutions/240.py b/Solutions/240.py new file mode 100644 index 0000000..8f1ae35 --- /dev/null +++ b/Solutions/240.py @@ -0,0 +1,50 @@ +""" +Problem: + +There are N couples sitting in a row of length 2 * N. They are currently ordered +randomly, but would like to rearrange themselves so that each couple's partners can sit +side by side. What is the minimum number of swaps necessary for this to happen? +""" + +# The range of the swaps is [0, ceil(N / 2)] + + +from typing import List + + +def get_desired_index(curr_index: int) -> int: + if curr_index % 2 == 0: + return curr_index + 1 + return curr_index - 1 + + +def couple_pairing(array: List[int]) -> int: + if array == None or (len(array) % 2) != 0: + return 0 + hash_table = {} + n_swaps = 0 + + for index, element in enumerate(array): + if element in hash_table: + desired_index = hash_table[element] + value_at_desired_index = array[desired_index] + if value_at_desired_index != element: + array[index], array[desired_index] = array[desired_index], array[index] + n_swaps += 1 + hash_table[value_at_desired_index] = get_desired_index(index) + continue + hash_table[element] = get_desired_index(index) + return n_swaps + + +if __name__ == "__main__": + print(couple_pairing([2, 1, 2, 3, 1, 3])) + print(couple_pairing([3, 2, 1, 1, 2, 3])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/241.py b/Solutions/241.py new file mode 100644 index 0000000..63c6967 --- /dev/null +++ b/Solutions/241.py @@ -0,0 +1,41 @@ +""" +Problem: + +In academia, the h-index is a metric used to calculate the impact of a researcher's +papers. It is calculated as follows: + +A researcher has index h if at least h of her N papers have h citations each. If there +are multiple h satisfying this formula, the maximum is chosen. + +For example, suppose N = 5, and the respective citations of each paper are +[4, 3, 0, 1, 5]. Then the h-index would be 3, since the researcher has 3 papers with at +least 3 citations. + +Given a list of paper citations of a researcher, calculate their h-index. +""" + + +from typing import List + + +def get_h_index(citations: List[int]) -> int: + citations.sort(reverse=True) + for index, citation in enumerate(citations): + if index >= citation: + # implies that there are 'index' papers with atleast 'citation' citations + return index + return 0 + + +if __name__ == "__main__": + print(get_h_index([4, 3, 0, 1, 5])) + print(get_h_index([4, 1, 0, 1, 1])) + print(get_h_index([4, 4, 4, 5, 4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/242.py b/Solutions/242.py new file mode 100644 index 0000000..45e64e4 --- /dev/null +++ b/Solutions/242.py @@ -0,0 +1,38 @@ +""" +Problem: + +You are given an array of length 24, where each element represents the number of new +subscribers during the corresponding hour. Implement a data structure that efficiently +supports the following: + +- update(hour: int, value: int): Increment the element at index hour by value. +- query(start: int, end: int): Retrieve the number of subscribers that have signed up + between start and end (inclusive). + +You can assume that all values get cleared at the end of the day, and that you will not +be asked for start and end values that wrap around midnight. +""" + + +class Hourly_Subscribers: + def __init__(self) -> None: + self.sub_count = [0 for _ in range(24)] + + def update(self, hour: int, value: int) -> None: + self.sub_count[hour - 1] += value + + def query(self, start: int, end: int) -> int: + return sum(self.sub_count[start : end + 1]) + + +if __name__ == "__main__": + hs = Hourly_Subscribers() + + hs.update(2, 50) + hs.update(5, 100) + + print(hs.query(1, 7)) + + hs.update(2, 10) + + print(hs.query(1, 7)) diff --git a/Solutions/243.py b/Solutions/243.py new file mode 100644 index 0000000..8394434 --- /dev/null +++ b/Solutions/243.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given an array of numbers N and an integer k, your task is to split N into k partitions +such that the maximum sum of any partition is minimized. Return this sum. + +For example, given N = [5, 1, 2, 7, 3, 4] and k = 3, you should return 8, since the +optimal partition is [5, 1, 2], [7], [3, 4]. +""" + +from sys import maxsize +from typing import List, Tuple + + +def minimize_partition_sum_helper(arr: List[int], k: int) -> Tuple[List[int], int]: + if k == 1: + return [arr], sum(arr) + + min_value = maxsize + min_candidate = None + for i in range(len(arr)): + arr_1, sum_1 = [arr[:i]], sum(arr[:i]) + arr_2, sum_2 = minimize_partition_sum_helper(arr[i:], k - 1) + candidate = arr_1 + arr_2, max(sum_1, sum_2) + if candidate[1] < min_value: + min_value = candidate[1] + min_candidate = candidate + return min_candidate + + +def minimize_partition_sum(arr: List[int], k: int) -> int: + _, max_sum = minimize_partition_sum_helper(arr, k) + return max_sum + + +if __name__ == "__main__": + print(minimize_partition_sum([5, 1, 2, 7, 3, 4], 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/244.py b/Solutions/244.py new file mode 100644 index 0000000..5192e79 --- /dev/null +++ b/Solutions/244.py @@ -0,0 +1,60 @@ +""" +Problem: + +The Sieve of Eratosthenes is an algorithm used to generate all prime numbers smaller +than N. The method is to take increasingly larger prime numbers, and mark their +multiples as composite. + +For example, to find all primes less than 100, we would first mark [4, 6, 8, ...] +(multiples of two), then [6, 9, 12, ...] (multiples of three), and so on. Once we have +done this for all primes less than N, the unmarked numbers that remain will be prime. + +Implement this algorithm. + +Bonus: Create a generator that produces primes indefinitely (that is, without taking N +as an input). +""" + + +from typing import Generator, List + + +def sieve_of_eratosthenes(sieve: List[int] = []) -> List[int]: + if sieve: + length = len(sieve) + sieve.extend([True for _ in range(length)]) + else: + length = 10 + sieve = [True for _ in range(length * 2)] + sieve[0], sieve[1] = False, False + # sieve generation + for i in range(2, 2 * length): + if sieve[i]: + for j in range(2 * i, 2 * length, i): + sieve[j] = False + return sieve + + +def primes_generator() -> Generator[int, None, None]: + primes = sieve_of_eratosthenes() + prev = 0 + while True: + for i in range(prev, len(primes)): + if primes[i]: + yield i + prev = len(primes) + primes = sieve_of_eratosthenes(primes) + + +if __name__ == "__main__": + generator = primes_generator() + for _ in range(35): + print(next(generator)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/245.py b/Solutions/245.py new file mode 100644 index 0000000..38d65ff --- /dev/null +++ b/Solutions/245.py @@ -0,0 +1,37 @@ +""" +Problem: + +You are given an array of integers, where each element represents the maximum number of +steps that can be jumped going forward from that element. Write a function to return +the minimum number of jumps you must take in order to get from the start to the end of +the array. + +For example, given [6, 2, 4, 0, 5, 1, 1, 4, 2, 9], you should return 2, as the optimal +solution involves jumping from 6 to 5, and then from 5 to 9. +""" + +from sys import maxsize +from typing import List + + +def get_min_jumps(arr: List[int]) -> int: + length = len(arr) + dp = [0 for _ in range(length)] + for i in range(length - 2, -1, -1): + if arr[i]: + dp[i] = min(dp[i + 1 : i + arr[i] + 1]) + 1 + else: + dp[i] = maxsize + return dp[0] + + +if __name__ == "__main__": + print(get_min_jumps([6, 2, 4, 0, 5, 1, 1, 4, 2, 9])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/246.py b/Solutions/246.py new file mode 100644 index 0000000..dd6cc49 --- /dev/null +++ b/Solutions/246.py @@ -0,0 +1,82 @@ +""" +Problem: + +Given a list of words, determine whether the words can be chained to form a circle. A +word X can be placed in front of another word Y in a circle if the last character of X +is same as the first character of Y. + +For example, the words ['chair', 'height', 'racket', 'touch', 'tunic'] can form the +following circle: chair -> racket -> touch -> height -> tunic -> chair. +""" + + +from typing import Dict, List, Set + + +def check_circle_formation_helper( + word_list: List[str], + start: Dict[str, Set[str]], + end: Dict[str, Set[str]], + curr: str, + start_word: str, + seen: Set[str], +) -> bool: + if len(seen) == len(word_list): + if start_word[0] == curr[-1]: + return True + return False + try: + for word in start[curr[-1]]: + if word not in seen: + seen_copy = seen.copy() + seen_copy.add(word) + if check_circle_formation_helper( + word_list, start, end, word, start_word, seen_copy + ): + return True + except KeyError: + # the current word's last character isn't present in start dictionary + pass + return False + + +def check_circle_formation(word_list: List[str]) -> bool: + start = {} + end = {} + for word in word_list: + if word[0] not in start: + start[word[0]] = set() + start[word[0]].add(word) + if word[-1] not in end: + end[word[-1]] = set() + end[word[-1]].add(word) + # starting with all words and checking if a circle can be formed + for word in word_list: + if check_circle_formation_helper( + word_list, start, end, word, word, set([word]) + ): + return True + return False + + +if __name__ == "__main__": + print( + check_circle_formation(["chair", "height", "racket", "touch", "tunic"]) + ) # chair, racket, touch, height, tunic, chair + print( + check_circle_formation(["height", "racket", "touch", "tunic", "car"]) + ) # racket, touch, height, tunic, car, racket + print( + check_circle_formation(["height", "racket", "touch", "tunic"]) + ) # racket, touch, height, tunic (no looping even though there is a chain) + print( + check_circle_formation(["height", "racket", "touch", "tunic", "cat"]) + ) # no looping + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/247.py b/Solutions/247.py new file mode 100644 index 0000000..d62c06a --- /dev/null +++ b/Solutions/247.py @@ -0,0 +1,60 @@ +""" +Problem: + +Given a binary tree, determine whether or not it is height-balanced. A height-balanced +binary tree can be defined as one in which the heights of the two subtrees of any node +never differ by more than one. +""" + +from typing import Tuple + +from DataStructures.Tree import Node, BinaryTree + + +def height_helper(node: Node) -> Tuple[int, bool]: + if node.left is None: + left_height, balance_left = 0, True + else: + left_height, balance_left = height_helper(node.left) + if node.right is None: + right_height, balance_right = 0, True + else: + right_height, balance_right = height_helper(node.right) + + balance = balance_left and balance_right + current_balance = -1 <= (right_height - left_height) <= 1 + height = max(left_height, right_height) + 1 + return height, balance and current_balance + + +def check_balance(tree: BinaryTree) -> bool: + if tree.root is None: + return True + _, balance = height_helper(tree.root) + return balance + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = Node(0) + + tree.root.left = Node(1) + tree.root.right = Node(2) + + tree.root.left.left = Node(3) + tree.root.left.right = Node(4) + + print(check_balance(tree)) + + tree.root.left.right.left = Node(5) + + print(check_balance(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/248.py b/Solutions/248.py new file mode 100644 index 0000000..febd366 --- /dev/null +++ b/Solutions/248.py @@ -0,0 +1,27 @@ +""" +Problem: + +Find the maximum of two numbers without using any if-else statements, branching, or +direct comparisons. +""" + + +def get_max(num1: int, num2: int) -> int: + return num1 ^ ((num1 ^ num2) & -(num1 < num2)) + + +if __name__ == "__main__": + print(get_max(1, 5)) + print(get_max(4, 3)) + print(get_max(-3, 6)) + print(get_max(5, -4)) + print(get_max(-4, -2)) + print(get_max(-3, -6)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/249.py b/Solutions/249.py new file mode 100644 index 0000000..89ca256 --- /dev/null +++ b/Solutions/249.py @@ -0,0 +1,28 @@ +""" +Problem: + +Given an array of integers, find the maximum XOR of any two elements. +""" + +from sys import maxsize +from typing import List + + +def get_max_xor(arr: List[int]) -> int: + max_xor = -maxsize + for index, elem1 in enumerate(arr): + for elem2 in arr[index + 1 :]: + max_xor = max(max_xor, elem1 ^ elem2) + return max_xor + + +if __name__ == "__main__": + print(get_max_xor([1, 2, 3, 4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/250.py b/Solutions/250.py new file mode 100644 index 0000000..c59467a --- /dev/null +++ b/Solutions/250.py @@ -0,0 +1,101 @@ +""" +Problem: + +A cryptarithmetic puzzle is a mathematical game where the digits of some numbers are +represented by letters. Each letter represents a unique digit. + +For example, a puzzle of the form: + + SEND ++ MORE +-------- + MONEY +may have the solution: + +{'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2} + +Given a three-word puzzle like the one above, create an algorithm that finds a solution +""" + + +from typing import Dict, List, Set + + +def get_num_from_string(char_map: Dict[str, int], string: str) -> int: + mantissa = 10 + total = 0 + for char in string[::-1]: + total += char_map[char] * mantissa + mantissa *= 10 + return total + + +def is_valid_map(exp1: str, exp2: str, res: str, char_map: Dict[str, int]) -> bool: + num1 = get_num_from_string(char_map, exp1) + num2 = get_num_from_string(char_map, exp2) + num3 = get_num_from_string(char_map, res) + return num1 + num2 == num3 + + +def get_valid_char_map( + exp1: str, exp2: str, res: str, char_maps: List[Dict[str, int]] +) -> Dict[str, int]: + for char_map in char_maps: + if is_valid_map(exp1, exp2, res, char_map): + return char_map + + +def assign_letters( + chars_left: Set[str], + nums_left: Set[int], + restrictions: Dict[str, Set[int]], + char_map: Dict[str, int] = {}, +) -> List[Dict[str, int]]: + # function to assign digits to the characters + # brute force approach: all valid (doesn't contradict restictions) combinations + # are generated + if not chars_left: + return [char_map] + curr_char = list(chars_left)[0] + char_maps = [] + for num in nums_left: + if num in restrictions[curr_char]: + continue + char_map_cp = char_map.copy() + char_map_cp[curr_char] = num + child_char_maps = assign_letters( + chars_left - set([curr_char]), + nums_left - set([num]), + restrictions, + char_map_cp, + ) + char_maps.extend(child_char_maps) + return char_maps + + +def decode(exp1: str, exp2: str, res: str) -> Dict[str, int]: + characters = set(exp1) | set(exp2) | set(res) + if len(characters) > 10: + raise ValueError("Number of digits cannot be more than 10") + + nums = set(range(0, 10)) + restrictions = {} + for char in characters: + restrictions[char] = set() + for word in [exp1, exp2, res]: + restrictions[word[0]].add(0) + char_maps = assign_letters(characters, nums, restrictions) + return get_valid_char_map(exp1, exp2, res, char_maps) + + +if __name__ == "__main__": + print(decode("SEND", "MORE", "MONEY")) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n) +[n = number of unique characters] +""" diff --git a/Solutions/252.py b/Solutions/252.py new file mode 100644 index 0000000..5eb1cd8 --- /dev/null +++ b/Solutions/252.py @@ -0,0 +1,38 @@ +""" +Problem: + +The ancient Egyptians used to express fractions as a sum of several terms where each +numerator is one. For example, 4 / 13 can be represented as +1 / (4 + 1 / (18 + (1 / 468))). + +Create an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian +fraction. +""" + +from fractions import Fraction +from math import ceil +from typing import List + + +def get_egyptian_frac( + fraction: Fraction, previous_fraction: List[Fraction] = list() +) -> List[Fraction]: + if fraction.numerator == 1: + previous_fraction.append(fraction) + return previous_fraction + + egyptian_fraction = Fraction(1, ceil(fraction.denominator / fraction.numerator)) + previous_fraction.append(egyptian_fraction) + return get_egyptian_frac(fraction - egyptian_fraction, previous_fraction) + + +if __name__ == "__main__": + print(get_egyptian_frac(Fraction(4, 13))) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/253.py b/Solutions/253.py new file mode 100644 index 0000000..c4ff675 --- /dev/null +++ b/Solutions/253.py @@ -0,0 +1,65 @@ +""" +Problem: + +Given a string and a number of lines k, print the string in zigzag form. In zigzag, +characters are printed out diagonally from top left to bottom right until reaching the +kth line, then back up to top right, and so on. + +For example, given the sentence "thisisazigzag" and k = 4, you should print: + +t a g + h s z a + i i i z + s g +""" + + +def clamp(num: int, min_value: int, max_value: int) -> int: + return max(min(num, max_value), min_value) + + +def print_zigzag_string(string: str, k: int) -> None: + if k < 1: + return + + length = len(string) + matrix = [[" " for _ in range(length)] for _ in range(k)] + i, j = 0, 0 + is_increasing = True + # generating zigzag string matrix + for char in string: + matrix[i][j] = char + j += 1 + if is_increasing: + i += 1 + else: + i -= 1 + if i == k or i == -1: + is_increasing = not is_increasing + if i == k: + i = clamp(i - 2, 0, k - 1) + else: + i = clamp(i + 2, 0, k - 1) + # displaying the string matrix + for row in matrix: + for elem in row: + print(elem, end="") + print() + + +if __name__ == "__main__": + print_zigzag_string("thisisazigzag", 4) + print() + print_zigzag_string("thisisazigzag", 3) + print() + print_zigzag_string("thisisazigzag", 2) + print() + print_zigzag_string("thisisazigzag", 1) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x k) +SPACE COMPLEXITY: O(n x k) +""" diff --git a/Solutions/254.py b/Solutions/254.py new file mode 100644 index 0000000..5e47bd4 --- /dev/null +++ b/Solutions/254.py @@ -0,0 +1,81 @@ +""" +Probelm: + +Recall that a full binary tree is one in which each node is either a leaf node, or has +two children. Given a binary tree, convert it to a full one by removing nodes with only +one child. + +For example, given the following tree: + + a + / \ + b c + / \ +d e + \ / \ + f g h +You should convert it to: + + a + / \ +f e + / \ + g h +""" + +from DataStructures.Tree import Node, BinaryTree + + +def create_full_bin_tree_helper(node: Node) -> None: + # if a node with one missing child is encountered, the value is replaced by its + # child and the children of the current node overwritten with the child's children + if node.right is None and node.left is None: + return + elif node.left is not None and node.right is None: + node.val = node.left.val + node.right = node.left.right + node.left = node.left.left + create_full_bin_tree_helper(node) + elif node.left is None and node.right is not None: + node.val = node.right.val + node.left = node.right.left + node.right = node.right.right + create_full_bin_tree_helper(node) + elif node.left is not None and node.right is not None: + create_full_bin_tree_helper(node.left) + create_full_bin_tree_helper(node.right) + + +def create_full_bin_tree(tree: BinaryTree) -> None: + if tree.root: + create_full_bin_tree_helper(tree.root) + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node("a") + + tree.root.left = Node("b") + tree.root.right = Node("c") + + tree.root.left.left = Node("d") + tree.root.left.left.right = Node("f") + + tree.root.right.right = Node("e") + + tree.root.right.right.left = Node("g") + tree.root.right.right.right = Node("h") + + print(tree) + + create_full_bin_tree(tree) + + print(tree) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/255.py b/Solutions/255.py new file mode 100644 index 0000000..2af7a5f --- /dev/null +++ b/Solutions/255.py @@ -0,0 +1,66 @@ +""" +Problem: + +The transitive closure of a graph is a measure of which vertices are reachable from +other vertices. It can be represented as a matrix M, where M[i][j] == 1 if there is a +path between vertices i and j, and otherwise 0. + +For example, suppose we are given the following graph in adjacency list form: + +graph = [ + [0, 1, 3], + [1, 2], + [2], + [3] +] +The transitive closure of this graph would be: + +[1, 1, 1, 1] +[0, 1, 1, 0] +[0, 0, 1, 0] +[0, 0, 0, 1] +Given a graph, find its transitive closure. +""" + + +from typing import List, Set + + +def get_transitive_matrix_helper( + origin: int, + curr_node: int, + graph: List[List[int]], + transitive_matrix: List[List[int]], + visited: Set[int], +) -> None: + # helper function to generate the transitive matrix using dfs + for node in graph[curr_node]: + transitive_matrix[origin][node] = 1 + if node not in visited: + visited.add(node) + get_transitive_matrix_helper( + origin, node, graph, transitive_matrix, visited + ) + + +def get_transitive_matrix(graph: List[List[int]]) -> List[List[int]]: + num_nodes = len(graph) + transitive_matrix = [[0 for _ in range(num_nodes)] for _ in range(num_nodes)] + for node in range(num_nodes): + get_transitive_matrix_helper(node, node, graph, transitive_matrix, set([node])) + return transitive_matrix + + +if __name__ == "__main__": + graph = [[0, 1, 3], [1, 2], [2], [3]] + + for row in get_transitive_matrix(graph): + print(*row) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/256.py b/Solutions/256.py new file mode 100644 index 0000000..fdc15a7 --- /dev/null +++ b/Solutions/256.py @@ -0,0 +1,42 @@ +""" +Problem: + +Given a linked list, rearrange the node values such that they appear in alternating +low -> high -> low -> high ... form. For example, given 1 -> 2 -> 3 -> 4 -> 5, you +should return 1 -> 3 -> 2 -> 5 -> 4. +""" + +from DataStructures.LinkedList import Node, LinkedList + + +def rearrange(ll: LinkedList) -> None: + nodes_count = len(ll) + nodes = [int(node) for node in ll] + nodes.sort() + + for i in range(2, nodes_count, 2): + nodes[i], nodes[i - 1] = nodes[i - 1], nodes[i] + + curr = ll.head + for i in range(nodes_count): + curr.val = nodes[i] + curr = curr.next + + +if __name__ == "__main__": + LL = LinkedList() + + for i in range(1, 6): + LL.add(i) + + print(LL) + rearrange(LL) + print(LL) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/257.py b/Solutions/257.py new file mode 100644 index 0000000..76c20a9 --- /dev/null +++ b/Solutions/257.py @@ -0,0 +1,96 @@ +""" +Problem: + +Given an array of integers out of order, determine the bounds of the smallest window +that must be sorted in order for the entire array to be sorted. For example, given +[3, 7, 5, 6, 9], you should return (1, 3). +""" + +from time import perf_counter +from random import randint +from typing import List, Tuple + + +def get_sort_range(arr: List[int]) -> Tuple[int, int]: + arr_sorted = sorted(arr) + if arr_sorted == arr: + return -1, -1 + # getting the start and end of the unsorted part of the array + start, end = 0, 0 + for i in range(len(arr)): + if arr[i] != arr_sorted[i]: + start = i + break + for i in range(start, len(arr)): + if arr[i] != arr_sorted[i]: + end = i + return start, end + + +def get_sort_range_optimized(arr: List[int]) -> Tuple[int, int]: + # Find rightmost possible index of left bound + left = 0 + while left < len(arr) - 1 and arr[left] < arr[left + 1]: + left += 1 + + # Check if sorted + if left == len(arr) - 1: + return -1, -1 + + # Find leftmost possible index of right bound + right = len(arr) - 1 + while right > 0 and arr[right] > arr[right - 1]: + right -= 1 + + # Find the minimum and the maximum of the current window + i = left + 1 + min_val = max_val = arr[left] + while i <= right: + if arr[i] < min_val: + min_val = arr[i] + if arr[i] > max_val: + max_val = arr[i] + i += 1 + + # Expand the window leftwards to include all elements greater than the min, + # so that everything remaining to the left is less than the smallest element to the right + while left > 0 and arr[left - 1] > min_val: + left -= 1 + + # Expand the window rightwards to include all elements less than the max, + # so that everything remaining to the right is greater than the largest element to the left + while right < len(arr) - 1 and arr[right + 1] < max_val: + right += 1 + + return left, right + + +def print_both(arr: List[int]) -> None: + for f in [get_sort_range, get_sort_range_optimized]: + start = perf_counter() + result = f(arr) + end = perf_counter() + print(f"{result} ({end - start:.3} sec)") + + +if __name__ == "__main__": + print_both([3, 5, 6, 7, 9]) + print_both([3, 7, 5, 6, 9]) + print_both([5, 4, 3, 2, 1]) + print_both([0, 1, 3, 4, 2, 7, 5, 6, 8, 9]) + print_both( + [0] + list([randint(1, 10**7 - 1) for _ in range(10**7 - 1)]) + [10**7] + ) # Expecting (1, 9999999) + + +""" +SPECS: + +get_sort_range: +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) + +get_sort_range_optimized: +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) (auxiliary) +""" diff --git a/Solutions/258.py b/Solutions/258.py new file mode 100644 index 0000000..b5e57f0 --- /dev/null +++ b/Solutions/258.py @@ -0,0 +1,75 @@ +""" +Problem: + +In Ancient Greece, it was common to write text with the first line going left to right, +the second line going right to left, and continuing to go back and forth. This style +was called "boustrophedon". + +Given a binary tree, write an algorithm to print the nodes in boustrophedon order. + +For example, given the following tree: + + 1 + / \ + 2 3 + / \ / \ +4 5 6 7 + +You should return [1, 3, 2, 4, 5, 6, 7]. +""" + +from typing import Dict, List +from DataStructures.Tree import Node, BinaryTree + + +def get_boustrophedon_helper( + node: Node, level: int, accumulator: Dict[int, List[int]] +) -> None: + # using dfs to store a list of values by level + if level not in accumulator: + accumulator[level] = [] + accumulator[level].append(node.val) + if node.left: + get_boustrophedon_helper(node.left, level + 1, accumulator) + if node.right: + get_boustrophedon_helper(node.right, level + 1, accumulator) + + +def get_boustrophedon(tree: BinaryTree) -> List[int]: + if not tree.root: + return [] + # generating the nodes by level + level_data = {} + get_boustrophedon_helper(tree.root, 1, level_data) + result = [] + # adding the even levels in reverse order in the result + for level in sorted(list(level_data.keys())): + if level % 2 == 0: + result.extend(reversed(level_data[level])) + else: + result.extend(level_data[level]) + return result + + +if __name__ == "__main__": + tree = BinaryTree() + tree.root = Node(1) + + tree.root.left = Node(2) + tree.root.right = Node(3) + + tree.root.left.left = Node(4) + tree.root.left.right = Node(5) + + tree.root.right.left = Node(6) + tree.root.right.right = Node(7) + + print(get_boustrophedon(tree)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/259.py b/Solutions/259.py new file mode 100644 index 0000000..fcf8d2f --- /dev/null +++ b/Solutions/259.py @@ -0,0 +1,53 @@ +""" +Problem: + +Ghost is a two-person word game where players alternate appending letters to a word. +The first person who spells out a word, or creates a prefix for which there is no +possible continuation, loses. Here is a sample game: + +Player 1: g +Player 2: h +Player 1: o +Player 2: s +Player 1: t [loses] +Given a dictionary of words, determine the letters the first player should start with, +such that with optimal play they cannot lose. + +For example, if the dictionary is ["cat", "calf", "dog", "bear"], the only winning +start letter would be b. +""" + + +from typing import List, Set + + +def get_winning_letters(words: List[str]) -> Set[str]: + # requirements for winning start letter: + # - the length is even for all words starting with the character + starting_char_freq = {} + for word in words: + if word[0] not in starting_char_freq: + starting_char_freq[word[0]] = [] + starting_char_freq[word[0]].append(word) + + winning_start_letters = set() + for starting_char in starting_char_freq: + for word in starting_char_freq[starting_char]: + if len(word) % 2 != 0: + break + else: + winning_start_letters.add(starting_char) + return winning_start_letters + + +if __name__ == "__main__": + print(get_winning_letters(["cat", "calf", "dog", "bear"])) + print(get_winning_letters(["something", "hi", "cat", "dog", "bear", "hola"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/260.py b/Solutions/260.py new file mode 100644 index 0000000..6806040 --- /dev/null +++ b/Solutions/260.py @@ -0,0 +1,40 @@ +""" +Problem: + +The sequence [0, 1, ..., N] has been jumbled, and the only clue you have for its order +is an array representing whether each number is larger or smaller than the last. Given +this information, reconstruct an array that is consistent with it. For example, given +[None, +, +, -, +], you could return [1, 2, 3, 0, 4]. +""" + + +from typing import List, Optional + + +def get_sequence(relative_arr: List[Optional[str]]) -> List[int]: + length = len(relative_arr) + larger_count = relative_arr.count("+") + first_num = length - 1 - larger_count + larger_num, smaller_num = first_num + 1, first_num - 1 + + result = [first_num] + for elem in relative_arr[1:]: + if elem == "+": + result.append(larger_num) + larger_num += 1 + else: + result.append(smaller_num) + smaller_num -= 1 + return result + + +if __name__ == "__main__": + print(get_sequence([None, "+", "+", "-", "+"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/262.py b/Solutions/262.py new file mode 100644 index 0000000..082b154 --- /dev/null +++ b/Solutions/262.py @@ -0,0 +1,91 @@ +""" +Problem: + +A bridge in a connected (undirected) graph is an edge that, if removed, causes the +graph to become disconnected. Find all the bridges in a graph. +""" + +from sys import maxsize +from typing import Dict, List, Optional, Set, Tuple + +from DataStructures.Graph import GraphUndirectedUnweighted + + +def get_bridges_helper( + graph: GraphUndirectedUnweighted, + node: int, + visited: Set[int], + parent: Dict[int, Optional[int]], + low: Dict[int, int], + disc: Dict[int, int], + bridges: List[Tuple[int, int]], +) -> None: + # find all bridges using dfs + visited.add(node) + disc[node] = graph.time + low[node] = graph.time + graph.time += 1 + for neighbour in graph.connections[node]: + if neighbour not in visited: + parent[neighbour] = node + get_bridges_helper(graph, neighbour, visited, parent, low, disc, bridges) + # check if the subtree rooted with neighbour has a connection to one of the + # ancestors of node + low[node] = min(low[node], low[neighbour]) + # if the lowest vertex reachable from subtree under neighbour is below node + # in DFS tree, then node-neighbour is a bridge + if low[neighbour] > disc[node]: + bridges.append((node, neighbour)) + elif neighbour != parent[node]: + low[node] = min(low[node], disc[neighbour]) + + +def get_bridges(graph: GraphUndirectedUnweighted) -> List[Tuple[int, int]]: + visited = set() + disc = {node: maxsize for node in graph.connections} + low = {node: maxsize for node in graph.connections} + parent = {node: None for node in graph.connections} + bridges = [] + graph.time = 0 + for node in graph.connections: + if node not in visited: + get_bridges_helper(graph, node, visited, parent, low, disc, bridges) + return bridges + + +if __name__ == "__main__": + g1 = GraphUndirectedUnweighted() + g1.add_edge(1, 0) + g1.add_edge(0, 2) + g1.add_edge(2, 1) + g1.add_edge(0, 3) + g1.add_edge(3, 4) + print("Bridges in first graph:") + print(*get_bridges(g1)) + + g2 = GraphUndirectedUnweighted() + g2.add_edge(0, 1) + g2.add_edge(1, 2) + g2.add_edge(2, 3) + print("\nBridges in second graph:") + print(*get_bridges(g2)) + + g3 = GraphUndirectedUnweighted() + g3.add_edge(0, 1) + g3.add_edge(1, 2) + g3.add_edge(2, 0) + g3.add_edge(1, 3) + g3.add_edge(1, 4) + g3.add_edge(1, 6) + g3.add_edge(3, 5) + g3.add_edge(4, 5) + print("\nBridges in third graph:") + print(*get_bridges(g3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(v + e) +SPACE COMPLEXITY: O(v) +""" diff --git a/Solutions/263.py b/Solutions/263.py new file mode 100644 index 0000000..7355d6f --- /dev/null +++ b/Solutions/263.py @@ -0,0 +1,56 @@ +""" +Problem: + +Create a basic sentence checker that takes in a stream of characters and determines +whether they form valid sentences. If a sentence is valid, the program should print it +out. + +We can consider a sentence valid if it conforms to the following rules: + +The sentence must start with a capital letter, followed by a lowercase letter or a +space. +All other characters must be lowercase letters, separators (,,;,:) or terminal marks +(.,?,!,‽). +There must be a single space between each word. +The sentence must end with a terminal mark immediately following a word. +""" + +TERMINALS = [".", "?", "!", "‽"] +SEPARATORS = [",", ";", ":"] + + +def check_sentence(sentence: str) -> None: + if len(sentence) < 2 or not sentence[0].isupper(): + return + if not sentence[1].islower() and not sentence[1].isspace(): + return + + space_flag = False + for char in sentence[1:-1]: + if char.isspace(): + if space_flag: + return + space_flag = True + continue + space_flag = False + if not char.islower() and char not in SEPARATORS: + return + + if sentence[-1] in TERMINALS: + print(sentence) + + +if __name__ == "__main__": + check_sentence("This, will, pass.") + check_sentence("ThiS Should fail.") + check_sentence("this Should fail Too.") + check_sentence("This too should fail") + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = number of characters in the string] +""" diff --git a/Solutions/264.py b/Solutions/264.py new file mode 100644 index 0000000..8a6c63e --- /dev/null +++ b/Solutions/264.py @@ -0,0 +1,75 @@ +""" +Problem: + +Given a set of characters C and an integer k, a De Bruijn sequence is a cyclic sequence +in which every possible k-length string of characters in C occurs exactly once. + +For example, suppose C = {0, 1} and k = 3. Then our sequence should contain the +substrings {'000', '001', '010', '011', '100', '101', '110', '111'}, and one possible +solution would be 00010111. + +Create an algorithm that finds a De Bruijn sequence. +""" + +from typing import List, Set + + +def generate_all_combinations( + characters: Set[str], size: int, accumulator: List[str] +) -> None: + if not accumulator: + accumulator.extend(characters) + size -= 1 + while size > 0: + updated_acc = [] + for _ in range(len(accumulator)): + temp = accumulator.pop(0) + for char in characters: + updated_acc.append(temp + char) + size -= 1 + accumulator.extend(updated_acc) + + +def get_de_bruijn_helper( + characters: Set[str], combinations_set: Set[str], k: int, context: str = "" +) -> Set[str]: + if not combinations_set: + return set([context]) + + dseqs = set() + if not context: + # if context is empty, it is initized using a combination + for combo in combinations_set: + child_dseqs = get_de_bruijn_helper( + characters, combinations_set - set([combo]), k, combo + ) + dseqs |= child_dseqs + return dseqs + + for character in characters: + combo = context[-(k - 1) :] + character + if combo in combinations_set: + child_dseqs = get_de_bruijn_helper( + characters, combinations_set - set([combo]), k, context + character + ) + dseqs |= child_dseqs + return dseqs + + +def get_de_bruijn(characters: Set[str], k: int) -> Set[str]: + combinations_list = [] + generate_all_combinations(characters, k, combinations_list) + combinations_set = set(combinations_list) + return get_de_bruijn_helper(characters, combinations_set, k) + + +if __name__ == "__main__": + print(get_de_bruijn({"0", "1"}, 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ k) +SPACE COMPLEXITY: O(n + k) +""" diff --git a/Solutions/265.py b/Solutions/265.py new file mode 100644 index 0000000..60d841b --- /dev/null +++ b/Solutions/265.py @@ -0,0 +1,84 @@ +""" +Problem: + +MegaCorp wants to give bonuses to its employees based on how many lines of codes they +have written. They would like to give the smallest positive amount to each worker +consistent with the constraint that if a developer has written more lines of code than +their neighbor, they should receive more money. + +Given an array representing a line of seats of employees at MegaCorp, determine how +much each one should get paid. + +For example, given [10, 40, 200, 1000, 60, 30], you should return [1, 2, 3, 4, 2, 1]. +""" + +from typing import List + + +def get_bonus(arr: List[int]) -> List[int]: + length = len(arr) + if length == 0: + return [] + if length == 1: + return [1] + + comparison = [None for _ in range(length)] + for i in range(1, length): + if arr[i] > arr[i - 1]: + comparison[i] = "+" + elif arr[i] < arr[i - 1]: + comparison[i] = "-" + else: + comparison[i] = "=" + + i = 0 + comparison[0] = comparison[1] + result = [0 for _ in range(length)] + while i < length: + # case: current element is larger than the previous element + if i < length and comparison[i] == "+": + j = i + 1 + while j < length and comparison[j] == "+": + j += 1 + j -= 1 + curr = 1 + for k in range(i, j + 1): + result[k] = curr + curr += 1 + i = j + 1 + # case: current element is smaller than the previous element + elif i < length and comparison[i] == "-": + j = i - 1 + while j > 0 and result[j] == 1: + result[j] += 1 + j -= 1 + j = i + 1 + while j < length and comparison[j] == "-": + j += 1 + j -= 1 + curr = 1 + for k in range(j, i - 1, -1): + result[k] = curr + curr += 1 + i = j + 1 + # case: current element is equal to the previous element + else: + result[i] = result[i - 1] + i += 1 + return result + + +if __name__ == "__main__": + print(get_bonus([1000])) + print(get_bonus([10, 40, 200, 1000, 60, 30])) + print(get_bonus([10, 40, 200, 1000, 900, 800, 30])) + print(get_bonus([10, 40, 200, 1000, 900, 800, 30, 30])) + print(get_bonus([10, 40, 200, 1000, 800, 800, 30])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/266.py b/Solutions/266.py new file mode 100644 index 0000000..06752e7 --- /dev/null +++ b/Solutions/266.py @@ -0,0 +1,61 @@ +""" +Problem: + +A step word is formed by taking a given word, adding a letter, and anagramming the +result. For example, starting with the word "APPLE", you can add an "A" and anagram +to get "APPEAL". + +Given a dictionary of words and an input word, create a function that returns all valid +step words. +""" + +from typing import Dict, List + + +def get_character_count(string: str) -> Dict[str, int]: + freq = {} + for char in string: + if char not in freq: + freq[char] = 0 + freq[char] += 1 + return freq + + +def is_step_word(word1: str, word2: str) -> bool: + freq1 = get_character_count(word1) + freq2 = get_character_count(word2) + for char in freq1: + if char in freq2: + freq2[char] -= freq1[char] + if freq2[char] == 0: + del freq2[char] + else: + return False + # checking if word2 is a step word of word1 + if len(freq2) == 1: + [char] = freq2.keys() + return freq2[char] == 1 + return False + + +def get_step_words(word: str, dictionary: List[str]) -> List[str]: + step_words = [] + for test_word in dictionary: + if is_step_word(word, test_word): + step_words.append(test_word) + return step_words + + +if __name__ == "__main__": + print(get_step_words("APPLE", ["APPEAL"])) + print(get_step_words("APPLE", ["APPEAL", "APPLICT"])) + print(get_step_words("APPLE", ["APPEAL", "APPLICT", "APPLES"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n.words) +SPACE COMPLEXITY: O(n) +[n = length of the longest word] +""" diff --git a/Solutions/267.py b/Solutions/267.py new file mode 100644 index 0000000..cc2d3a3 --- /dev/null +++ b/Solutions/267.py @@ -0,0 +1,113 @@ +""" +Problem: + +You are presented with an 8 by 8 matrix representing the positions of pieces on a chess +board. The only pieces on the board are the black king and various white pieces. Given +this matrix, determine whether the king is in check. + +For details on how each piece moves, see here. + +For example, given the following matrix: + +...K.... +........ +.B...... +......P. +.......R +..N..... +........ +.....Q.. +You should return True, since the bishop is attacking the king diagonally. +""" + +from typing import List + + +def is_attacking(board: List[List[str]]) -> bool: + for i in range(8): + for j in range(8): + # case pawn + if board[i][j] == "P": + if j > 0 and board[i - 1][j - 1] == "K": + return True + if j < 8 and board[i - 1][j + 1] == "K": + return True + # case rook + elif board[i][j] == "R": + for k in range(8): + if board[i][k] == "K" or board[k][j] == "K": + return True + # case knight + elif board[i][j] == "N": + moves = [ + (i + 2, j + 1), + (i + 2, j - 1), + (i - 2, j + 1), + (i - 2, j - 1), + (i + 1, j + 2), + (i + 1, j - 2), + (i - 1, j + 2), + (i - 1, j - 2), + ] + for y, x in moves: + if 0 <= y < 8 and 0 <= x < 8 and board[y][x] == "K": + return True + # case bishop + elif board[i][j] == "B": + for y, x in zip(range(i, -1, -1), range(j, -1, -1)): + if board[y][x] == "K": + return True + for y, x in zip(range(i, 8), range(j, -1, -1)): + if board[y][x] == "K": + return True + for y, x in zip(range(i, 8), range(j, 8)): + if board[y][x] == "K": + return True + for y, x in zip(range(i, -1, -1), range(j, 8)): + if board[y][x] == "K": + return True + # case queen + elif board[i][j] == "Q": + for y, x in zip(range(i, -1, -1), range(j, -1, -1)): + if board[y][x] == "K": + return True + for y, x in zip(range(i, 8), range(j, -1, -1)): + if board[y][x] == "K": + return True + for y, x in zip(range(i, 8), range(j, 8)): + if board[y][x] == "K": + return True + for y, x in zip(range(i, -1, -1), range(j, 8)): + if board[y][x] == "K": + return True + for k in range(8): + if board[i][k] == "K" or board[k][j] == "K": + return True + return False + + +if __name__ == "__main__": + print( + is_attacking( + [ + [".", ".", ".", "K", ".", ".", ".", "."], + [".", ".", ".", ".", ".", ".", ".", "."], + [".", "B", ".", ".", ".", ".", ".", "."], + [".", ".", ".", ".", ".", ".", "P", "."], + [".", ".", ".", ".", ".", ".", ".", "R"], + [".", ".", "N", ".", ".", ".", ".", "."], + [".", ".", ".", ".", ".", ".", ".", "."], + [".", ".", ".", ".", ".", "Q", ".", "."], + ] + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +[n = number of pieces on the board (as the board is of dimension 8 x 8, all checks +for if a piece is attacking the king take O(1) time)] +""" diff --git a/Solutions/268.py b/Solutions/268.py new file mode 100644 index 0000000..2791c2b --- /dev/null +++ b/Solutions/268.py @@ -0,0 +1,31 @@ +""" +Problem: + +Given a 32-bit positive integer N, determine whether it is a power of four in faster +than O(log N) time. +""" + +# for details visit: https://stackoverflow.com/a/19611541/8650340 + + +def is_power_of_4(num: int) -> bool: + return ((num & -num) & 0x55555554) == num + + +if __name__ == "__main__": + print(is_power_of_4(2)) + print(is_power_of_4(4)) # 4 ^ 1 + print(is_power_of_4(8)) + print(is_power_of_4(16)) # 4 ^ 2 + print(is_power_of_4(32)) + print(is_power_of_4(64)) # 4 ^ 3 + print(is_power_of_4(128)) + print(is_power_of_4(256)) # 4 ^ 4 + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/269.py b/Solutions/269.py new file mode 100644 index 0000000..72884e7 --- /dev/null +++ b/Solutions/269.py @@ -0,0 +1,63 @@ +""" +Problem: + +You are given an string representing the initial conditions of some dominoes. Each +element can take one of three values: + +L, meaning the domino has just been pushed to the left, +R, meaning the domino has just been pushed to the right, or +., meaning the domino is standing still. +Determine the orientation of each tile when the dominoes stop falling. Note that if a +domino receives a force from the left and right side simultaneously, it will remain +upright. + +For example, given the string .L.R....L, you should return LL.RRRLLL. + +Given the string ..R...L.L, you should return ..RR.LLLL. +""" + +from typing import List + + +def get_config_helper(dominos: List[str], length: int) -> List[str]: + has_been_updated = False + updated_dominos = dominos.copy() + for i in range(length): + if ( + dominos[i] == "L" + and i > 0 + and dominos[i - 1] == "." + and ((i > 1 and dominos[i - 2] != "R") or i <= 1) + ): + updated_dominos[i - 1] = "L" + has_been_updated = True + elif ( + dominos[i] == "R" + and i < length - 1 + and dominos[i + 1] == "." + and ((i < length - 2 and dominos[i + 2] != "L") or i >= length - 2) + ): + updated_dominos[i + 1] = "R" + has_been_updated = True + if has_been_updated: + return get_config_helper(updated_dominos, length) + return dominos + + +def get_config(initial_state: str) -> str: + dominoes = list(initial_state) + return "".join(get_config_helper(dominoes, len(dominoes))) + + +if __name__ == "__main__": + print(get_config(".L.R....L")) + print(get_config("..R...L.L")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n ^ 2) +[each iteration takes O(n) in both time & space and there can be n such iterations] +""" diff --git a/Solutions/270.py b/Solutions/270.py new file mode 100644 index 0000000..50009ff --- /dev/null +++ b/Solutions/270.py @@ -0,0 +1,79 @@ +""" +Problem: + +A network consists of nodes labeled 0 to N. You are given a list of edges (a, b, t), +describing the time t it takes for a message to be sent from node a to node b. Whenever +a node receives a message, it immediately passes the message on to a neighboring node, +if possible. + +Assuming all nodes are connected, determine how long it will take for every node to +receive a message that begins at node 0. + +For example, given N = 5, and the following edges: + +edges = [ + (0, 1, 5), + (0, 2, 3), + (0, 5, 4), + (1, 3, 8), + (2, 3, 1), + (3, 5, 10), + (3, 4, 5) +] +You should return 9, because propagating the message from 0 -> 2 -> 3 -> 4 will take +that much time +""" + +from sys import maxsize +from typing import Dict, List, Optional, Tuple + +from DataStructures.Graph import GraphDirectedWeighted +from DataStructures.PriorityQueue import MinPriorityQueue + + +def dijkstra( + graph: GraphDirectedWeighted, start: int +) -> Tuple[Dict[int, int], Dict[int, Optional[int]]]: + dist = {node: maxsize for node in graph.connections} + parent = {node: None for node in graph.connections} + dist[start] = 0 + priority_queue = MinPriorityQueue() + [priority_queue.push(node, weight) for node, weight in dist.items()] + while not priority_queue.isEmpty(): + node = priority_queue.extract_min() + for neighbour in graph.connections[node]: + if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: + dist[neighbour] = dist[node] + graph.connections[node][neighbour] + priority_queue.update_key(neighbour, dist[neighbour]) + parent[neighbour] = node + return dist, parent + + +def get_propagation_time(edges: List[Tuple[int, int, int]]) -> int: + graph = GraphDirectedWeighted() + for src, dest, wt in edges: + graph.add_edge(src, dest, wt) + + time, _ = dijkstra(graph, 0) + return max(time.values()) + + +if __name__ == "__main__": + edges = [ + (0, 1, 5), + (0, 2, 3), + (0, 5, 4), + (1, 3, 8), + (2, 3, 1), + (3, 5, 10), + (3, 4, 5), + ] + print(get_propagation_time(edges)) + + +""" +SPECS: + +TIME COMPLEXITY: O(v + e x log(v)) +SPACE COMPLEXITY: O(v) +""" diff --git a/Solutions/271.py b/Solutions/271.py new file mode 100644 index 0000000..cd17194 --- /dev/null +++ b/Solutions/271.py @@ -0,0 +1,60 @@ +""" +Problem: + +Given a sorted list of integers of length N, determine if an element x is in the list +without performing any multiplication, division, or bit-shift operations. + +Do this in O(log N) time. +""" + +from typing import List + + +def fibo_search(arr: List[int], val: int) -> int: + # fibo search to search an element in a sorted array in O(log(n)) time [without + # multiplication, division, or bit-shift operations] + length = len(arr) + if length == 0: + return 0 + fib_N_2 = 0 + fib_N_1 = 1 + fibNext = fib_N_1 + fib_N_2 + + while fibNext < len(arr): + fib_N_2 = fib_N_1 + fib_N_1 = fibNext + fibNext = fib_N_1 + fib_N_2 + + index = -1 + while fibNext > 1: + i = min(index + fib_N_2, (length - 1)) + if arr[i] == val: + return i + fibNext = fib_N_1 + if arr[i] < val: + fib_N_1 = fib_N_2 + index = i + elif arr[i] > val: + fib_N_1 = fib_N_1 - fib_N_2 + fib_N_2 = fibNext - fib_N_1 + + if (fib_N_1 and index < length - 1) and (arr[index + 1] == val): + return index + 1 + return -1 + + +if __name__ == "__main__": + print(fibo_search([1, 3, 5, 7, 9], 3)) + print(fibo_search([1, 3, 5, 7, 9], 1)) + print(fibo_search([1, 3, 5, 7, 9], 7)) + + print(fibo_search([1, 3, 5, 7, 9], 6)) + print(fibo_search([1, 3, 5, 7, 9], 0)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/272.py b/Solutions/272.py new file mode 100644 index 0000000..ddf156d --- /dev/null +++ b/Solutions/272.py @@ -0,0 +1,31 @@ +""" +Problem: + +Write a function, throw_dice(N, faces, total), that determines how many ways it is +possible to throw N dice with some number of faces each to get a specific total. + +For example, throw_dice(3, 6, 7) should equal 15. +""" + + +def throw_dice(N: int, faces: int, total: int, accumulator: int = 0) -> int: + if N == 0 and total == 0: + return accumulator + 1 + elif total < 0: + return accumulator + # dfs to calculate the answer + for i in range(1, faces + 1): + accumulator = throw_dice(N - 1, faces, total - i, accumulator) + return accumulator + + +if __name__ == "__main__": + print(throw_dice(3, 6, 7)) + + +""" +SPECS: + +TIME COMPLEXITY: O(faces ^ log(total)) +SPACE COMPLEXITY: O(total) [call stack included] +""" diff --git a/Solutions/273.py b/Solutions/273.py new file mode 100644 index 0000000..b894a2c --- /dev/null +++ b/Solutions/273.py @@ -0,0 +1,38 @@ +""" +Problem: + +A fixed point in an array is an element whose value is equal to its index. Given a +sorted array of distinct elements, return a fixed point, if one exists. Otherwise, +return False. + +For example, given [-6, 0, 2, 40], you should return 2. Given [1, 5, 7, 8], you should +return False. +""" + +from typing import List, Union + + +def get_fixed_point(arr: List[int]) -> Union[int, False]: + for index, value in enumerate(arr): + if value == index: + # fixed point found + return value + elif value > index: + # since the array is sorted and has distinct elements, once the value + # exceeds the index, the index can never be equal to the value at any + # position + break + return False + + +if __name__ == "__main__": + print(get_fixed_point([-6, 0, 2, 40])) + print(get_fixed_point([1, 5, 7, 8])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/274.py b/Solutions/274.py new file mode 100644 index 0000000..82d512d --- /dev/null +++ b/Solutions/274.py @@ -0,0 +1,59 @@ +""" +Problem: + +Given a string consisting of parentheses, single digits, and positive and negative +signs, convert the string into a mathematical expression to obtain the answer. + +Don't use eval or a similar built-in parser. + +For example, given '-1 + (2 + 3)', you should return 4. +""" + + +def evaluate_expression(expression: str) -> int: + result = 0 + add = True + sub_eval_string = "" + number_of_parentheses = 0 + for char in expression: + if number_of_parentheses > 0: + # inside a set of parentheses + if char == "(": + number_of_parentheses += 1 + elif char == ")": + number_of_parentheses -= 1 + if number_of_parentheses == 0: + if add: + result += evaluate_expression(sub_eval_string) + else: + result -= evaluate_expression(sub_eval_string) + sub_eval_string = "" + else: + sub_eval_string += char + else: + if char == "-": + add = False + elif char == "+": + add = True + elif char == "(": + number_of_parentheses = 1 + elif char.isdigit(): + if add: + result += int(char) + else: + result -= int(char) + return result + + +if __name__ == "__main__": + print(evaluate_expression("-1 + (2 + 3)")) + print(evaluate_expression("-1 + (2 + 3) + (2 - 3)")) + print(evaluate_expression("-1 + (2 + 3) + ((2 - 3) + 1)")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/275.py b/Solutions/275.py new file mode 100644 index 0000000..42a740c --- /dev/null +++ b/Solutions/275.py @@ -0,0 +1,64 @@ +""" +Problem: + +The "look and say" sequence is defined as follows: beginning with the term 1, each +subsequent term visually describes the digits appearing in the previous term. The first +few terms are as follows: + +1 +11 +21 +1211 +111221 +As an example, the fourth term is 1211, since the third term consists of one 2 and one +1. + +Given an integer N, print the Nth term of this sequence. +""" + +from functools import lru_cache + + +def generate_look_and_say_term(num: str) -> str: + result = "" + temp = "" + for char in num[::-1]: + if temp: + if char == temp[0]: + temp += char + else: + result = f"{len(temp)}{temp[0]}" + result + temp = char + else: + temp = char + result = f"{len(temp)}{temp[0]}" + result + return result + + +# cache is unnecessary for small sizes, but in case of large value of n, it drastically +# speeds up the process using memorization +@lru_cache(maxsize=5) +def get_look_and_say_term(n: int) -> str: + num = "1" + for _ in range(n - 1): + num = generate_look_and_say_term(num) + return num + + +if __name__ == "__main__": + for i in range(1, 6): + print(f"{i}th term = {get_look_and_say_term(i)}") + + +""" +SPECS: + +[n = number of terms, m = longest look and say term] +TIME COMPLEXITY: O(n + m) +SPACE COMPLEXITY: O(n + m) +[with cache] + +TIME COMPLEXITY: O(n * m) +SPACE COMPLEXITY: O(m) +[without cache] +""" diff --git a/Solutions/276.py b/Solutions/276.py new file mode 100644 index 0000000..c5f3ed1 --- /dev/null +++ b/Solutions/276.py @@ -0,0 +1,64 @@ +""" +Problem: + +Implement an efficient string matching algorithm. + +That is, given a string of length N and a pattern of length k, write a program that +searches for the pattern in the string with less than O(N * k) worst-case time +complexity. + +If the pattern is found, return the start index of its location. If not, return False. +""" + +from typing import List, Union + + +def kmp_search(text: str, pattern: str) -> Union[int, bool]: + # modified kmp search to return the first match only + len_pattern = len(pattern) + len_text = len(text) + lps = compute_lps(pattern, len_pattern) + + j = 0 + i = 0 + while i < len_text: + if pattern[j] == text[i]: + i += 1 + j += 1 + if j == len_pattern: + return i - j + elif i < len_text and pattern[j] != text[i]: + if j != 0: + j = lps[j - 1] + else: + i += 1 + return False + + +def compute_lps(pattern: str, len_pattern: int) -> List[int]: + # computing the Longest Prefix which is also a Suffix + lps = [0 for _ in range(len_pattern)] + length = 0 + i = 1 + while i < (len_pattern): + if pattern[i] == pattern[length]: + length += 1 + lps[i] = length + else: + lps[i] = length + i += 1 + return lps + + +if __name__ == "__main__": + print(kmp_search("abcabcabcd", "abcd")) + print(kmp_search("abcabcabc", "abcd")) + + +""" +SPECS: + +[n = length of text, m = length of pattern] +TIME COMPLEXITY: O(n + m) +SPACE COMPLEXITY: O(m) +""" diff --git a/Solutions/277.py b/Solutions/277.py new file mode 100644 index 0000000..eaf176b --- /dev/null +++ b/Solutions/277.py @@ -0,0 +1,69 @@ +""" +Problem: + +UTF-8 is a character encoding that maps each symbol to one, two, three, or four bytes. + +For example, the Euro sign, €, corresponds to the three bytes 11100010 10000010 +10101100. The rules for mapping characters are as follows: + +For a single-byte character, the first bit must be zero. +For an n-byte character, the first byte starts with n ones and a zero. The other n - 1 +bytes all start with 10. Visually, this can be represented as follows. + Bytes | Byte format +----------------------------------------------- + 1 | 0xxxxxxx + 2 | 110xxxxx 10xxxxxx + 3 | 1110xxxx 10xxxxxx 10xxxxxx + 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx +Write a program that takes in an array of integers representing byte values, and +returns whether it is a valid UTF-8 encoding. +""" + +from re import compile +from typing import List + +# acceptable expressions +EXPRESSIONS = [ + compile("0.{7}"), + compile("110.{5}10.{6}"), + compile("1110.{4}10.{6}10.{6}"), + compile("11110.{3}10.{6}10.{6}10.{6}"), +] + + +def is_utf8(bin_num: str) -> bool: + # using regular expression to match the input string + for expression in EXPRESSIONS: + if expression.match(bin_num): + return True + return False + + +def is_arr_utf8(arr: List[int]) -> bool: + # the array cannot hold an utf8 symbol if the length of the array is more than 4 or + # if any of the elements is larger than 255 (binary number contains more than 8 + # characters) + if len(arr) > 4 or any([elem > 255 for elem in arr]): + return False + # generating the binary number + bin_num = "" + for elem in arr: + num = bin(elem)[2:] + bin_num += num.zfill(8) + return is_utf8(bin_num) + + +if __name__ == "__main__": + print(is_arr_utf8([127])) + print(is_arr_utf8([226, 130, 172])) + print(is_arr_utf8([226, 127, 172])) + print(is_arr_utf8([256, 130, 172])) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +[its constant as the maximum size is 32 characters (constant)] +""" diff --git a/Solutions/279.py b/Solutions/279.py new file mode 100644 index 0000000..c54fbe9 --- /dev/null +++ b/Solutions/279.py @@ -0,0 +1,77 @@ +""" +Problem: + +A classroom consists of N students, whose friendships can be represented in an +adjacency list. For example, the following descibes a situation where 0 is friends +with 1 and 2, 3 is friends with 6, and so on. + +{ + 0: [1, 2], + 1: [0, 5], + 2: [0], + 3: [6], + 4: [], + 5: [1], + 6: [3] +} +Each student can be placed in a friend group, which can be defined as the transitive +closure of that student's friendship relations. In other words, this is the smallest +set such that no student in the group has any friends outside this group. For the +example above, the friend groups would be {0, 1, 2, 5}, {3, 6}, {4}. + +Given a friendship list such as the one above, determine the number of friend groups +in the class. +""" + +from typing import Dict, List, Set + +from DataStructures.Graph import GraphUndirectedUnweighted + + +def get_components_dfs_helper( + graph: GraphUndirectedUnweighted, node: int, component: Set[int], visited: Set[int] +) -> None: + visited.add(node) + component.add(node) + for neighbour in graph.connections[node]: + if neighbour not in visited: + get_components_dfs_helper(graph, neighbour, component, visited) + + +def get_components(graph: GraphUndirectedUnweighted) -> List[Set[int]]: + components = [] + visited = set() + for node in graph.connections: + if node not in visited: + component = set() + get_components_dfs_helper(graph, node, component, visited) + components.append(component) + return components + + +def get_friendship_transitive_closure( + friendship_list: Dict[int, List[int]], +) -> List[Set[int]]: + graph = GraphUndirectedUnweighted() + for node in friendship_list: + graph.add_node(node) + for neighbour in friendship_list[node]: + graph.add_edge(node, neighbour) + return get_components(graph) + + +if __name__ == "__main__": + print( + get_friendship_transitive_closure( + {0: [1, 2], 1: [0, 5], 2: [0], 3: [6], 4: [], 5: [1], 6: [3]} + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n + e) +SPACE COMPLEXITY: O(n) +[n = nodes, e = edges] +""" diff --git a/Solutions/280.py b/Solutions/280.py new file mode 100644 index 0000000..ffac28c --- /dev/null +++ b/Solutions/280.py @@ -0,0 +1,60 @@ +""" +Problem: + +Given an undirected graph, determine if it contains a cycle. +""" + +from typing import Set + +from DataStructures.Graph import GraphUndirectedUnweighted + + +def get_components_helper( + graph: GraphUndirectedUnweighted, + node: int, + component: Set[int], + visited: Set[int], + degree: int = 0, +) -> int: + # function to get the degree of the component + # generating the degree recursively using dfs + visited.add(node) + component.add(node) + for neighbour in graph.connections[node]: + degree += 1 + if neighbour not in visited: + degree += get_components_helper(graph, neighbour, component, visited) + return degree + + +def is_cyclic(graph: GraphUndirectedUnweighted) -> bool: + visited = set() + for node in graph.connections: + if node not in visited: + component = set() + component_degree = get_components_helper(graph, node, component, visited) + if component_degree > 2 * (len(component) - 1): + return False + return True + + +if __name__ == "__main__": + graph = GraphUndirectedUnweighted() + graph.add_edge(1, 2) + graph.add_edge(1, 3) + graph.add_edge(1, 4) + + print(is_cyclic(graph)) + + graph.add_edge(2, 4) + + print(is_cyclic(graph)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n + e) +SPACE COMPLEXITY: O(n) +[n = nodes, e = edges] +""" diff --git a/Solutions/281.py b/Solutions/281.py new file mode 100644 index 0000000..fcd0c00 --- /dev/null +++ b/Solutions/281.py @@ -0,0 +1,70 @@ +""" +Problem: + +A wall consists of several rows of bricks of various integer lengths and uniform +height. Your goal is to find a vertical line going from the top to the bottom of the +wall that cuts through the fewest number of bricks. If the line goes through the edge +between two bricks, this does not count as a cut. + +For example, suppose the input is as follows, where values in each row represent the +lengths of bricks in that row: + +[[3, 5, 1, 1], + [2, 3, 3, 2], + [5, 5], + [4, 4, 2], + [1, 3, 3, 3], + [1, 1, 6, 1, 1]] +The best we can we do here is to draw a line after the eighth brick, which will only +require cutting through the bricks in the third and fifth row. + +Given an input consisting of brick lengths for each row such as the one above, return +the fewest number of bricks that must be cut to create a vertical line. +""" + +from typing import List + + +def get_min_cut_position(wall: List[List[int]]) -> int: + rows = len(wall) + if rows == 1: + cols = len(wall[0]) + if cols > 1: + return wall[0][0] + return wall[0][0] - 1 + # generating a hash map containing the positions with no bricks at any row + no_brick_loaction = {} + for i in range(rows): + curr = 0 + for j in range(len(wall[i]) - 1): + curr += wall[i][j] + if curr not in no_brick_loaction: + no_brick_loaction[curr] = 0 + no_brick_loaction[curr] += 1 + # the position with minimum bricks is returned + if no_brick_loaction: + key, _ = max(no_brick_loaction.items(), key=lambda x: x[1]) + return key + # if all the rows contain 1 brick its cut from the length - 1 position + return wall[0][0] - 1 + + +if __name__ == "__main__": + wall = [ + [3, 5, 1, 1], + [2, 3, 3, 2], + [5, 5], + [4, 4, 2], + [1, 3, 3, 3], + [1, 1, 6, 1, 1], + ] + print(get_min_cut_position(wall)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +[n = number of elements in the matrix] +""" diff --git a/Solutions/282.py b/Solutions/282.py new file mode 100644 index 0000000..54e79c5 --- /dev/null +++ b/Solutions/282.py @@ -0,0 +1,43 @@ +""" +Problem: + +Given an array of integers, determine whether it contains a Pythagorean triplet. Recall +that a Pythogorean triplet (a, b, c) is defined by the equation a^2 + b^2 = c^2. +""" + +from math import sqrt +from typing import List, Optional, Tuple + + +def get_pythogorean_triplet( + arr: List[int], +) -> Tuple[Optional[int], Optional[int], Optional[int]]: + length = len(arr) + if length < 3: + return False + # generating the set of squared values for O(1) access + squared_arr = [elem * elem for elem in arr] + value_set = set(squared_arr) + + for i in range(length - 1): + for j in range(i + 1, length): + if squared_arr[i] + squared_arr[j] in value_set: + return ( + int(sqrt(squared_arr[i])), + int(sqrt(squared_arr[j])), + int(sqrt(squared_arr[i] + squared_arr[j])), + ) + return None, None, None + + +if __name__ == "__main__": + print(get_pythogorean_triplet([3, 4, 5, 6, 7])) + print(get_pythogorean_triplet([3, 5, 6, 7])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/283.py b/Solutions/283.py new file mode 100644 index 0000000..97b0a4f --- /dev/null +++ b/Solutions/283.py @@ -0,0 +1,60 @@ +""" +Problem: + +A regular number in mathematics is defined as one which evenly divides some power of +60. Equivalently, we can say that a regular number is one whose only prime divisors are +2, 3, and 5. + +These numbers have had many applications, from helping ancient Babylonians keep time to +tuning instruments according to the diatonic scale. + +Given an integer N, write a program that returns, in order, the first N regular +numbers. +""" + +from typing import List, Set + + +def get_prime_factors(num: int) -> Set[int]: + factors = set() + curr = 2 + while num > 1: + while num > 1 and num % curr == 0: + num = num // curr + factors.add(curr) + curr += 1 + return factors + + +def get_regular_numbers(N: int) -> List[int]: + # using Sieve of Eratosthenes Method to optimally find the required numbers + total_range = 2 * N + SoE = [False for _ in range(total_range)] + result = [] + count = 0 + factors = set([2, 3, 5]) + + for factor in factors: + for i in range(factor, total_range, factor): + if not SoE[i] and not (get_prime_factors(i) - factors): + SoE[i] = True + + for index, value in enumerate(SoE): + if value: + result.append(index) + count += 1 + if count == N: + break + return result + + +if __name__ == "__main__": + print(get_regular_numbers(10)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/284.py b/Solutions/284.py new file mode 100644 index 0000000..0d24647 --- /dev/null +++ b/Solutions/284.py @@ -0,0 +1,121 @@ +""" +Problem: + +Two nodes in a binary tree can be called cousins if they are on the same level of the +tree but have different parents. For example, in the following diagram 4 and 6 are +cousins. + + 1 + / \ + 2 3 + / \ \ +4 5 6 +Given a binary tree and a particular node, find all cousins of that node. +""" + +from typing import List, Optional + +from DataStructures.Tree import BinaryTree, Node + + +def get_depth_dfs_helper( + node: Node, search_node_val: int, depth: int, parent_val: Optional[int] = None +) -> Optional[int]: + if node.val == search_node_val: + return depth, parent_val + if node.left: + left_depth, parent = get_depth_dfs_helper( + node.left, search_node_val, depth + 1, node + ) + if left_depth: + return left_depth, parent + if node.right: + right_depth, parent = get_depth_dfs_helper( + node.right, search_node_val, depth + 1, node + ) + if right_depth: + return right_depth, parent + return None, None + + +def get_node_by_depth( + node: Node, + curr_depth: int, + depth: int, + search_node_val: int, + accumulator: int, + ignore_parent_val: int, + parent_val: Optional[int] = None, +) -> None: + # getting all nodes where the depth is equal to the input depth (except the node + # with black-listed parent ["ignore_parent_val"]) + if parent_val == ignore_parent_val: + return + if node.val == search_node_val: + return + if curr_depth == depth: + accumulator.append(node.val) + return + if node.left: + get_node_by_depth( + node.left, + curr_depth + 1, + depth, + search_node_val, + accumulator, + ignore_parent_val, + node, + ) + if node.right: + get_node_by_depth( + node.right, + curr_depth + 1, + depth, + search_node_val, + accumulator, + ignore_parent_val, + node, + ) + + +def dfs_get_depth(tree: BinaryTree, search_node_val: int): + return get_depth_dfs_helper(tree.root, search_node_val, 0) + + +def get_cousins(tree: BinaryTree, node_val: int) -> List[int]: + depth, parent = dfs_get_depth(tree, node_val) + if depth is None: + raise ValueError("Node not present in Tree") + cousins = [] + get_node_by_depth(tree.root, 0, depth, node_val, cousins, parent) + return cousins + + +if __name__ == "__main__": + tree = BinaryTree() + + tree.root = Node(1) + + tree.root.left = Node(2) + tree.root.right = Node(3) + + tree.root.left.left = Node(4) + tree.root.left.right = Node(5) + + tree.root.right.right = Node(6) + + print(tree) + print(get_cousins(tree, 4)) + + tree.root.right.left = Node(7) + + print(tree) + print(get_cousins(tree, 4)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/285.py b/Solutions/285.py new file mode 100644 index 0000000..85493cd --- /dev/null +++ b/Solutions/285.py @@ -0,0 +1,48 @@ +""" +Problem: + +You are given an array representing the heights of neighboring buildings on a city +street, from east to west. The city assessor would like you to write an algorithm that +returns how many of these buildings have a view of the setting sun, in order to +properly value the street. + +For example, given the array [3, 7, 8, 3, 6, 1], you should return 3, since the top +floors of the buildings with heights 8, 6, and 1 all have an unobstructed view to the +west. + +Can you do this using just one forward pass through the array? +""" + +from sys import maxsize +from typing import List + +from DataStructures.Stack import Stack + + +def get_view_sunset(arr: List[int]) -> int: + # the buildings can view the sunset when the elements are chosen in-order, keeping + # only the ones that allow decending order selection + stack = Stack() + for elem in arr: + if not stack.is_empty(): + last = stack.peek() + while not stack.is_empty() and last < elem: + stack.pop() + last = maxsize + if not stack.is_empty(): + last = stack.peek() + if stack.is_empty() or stack.peek() > elem: + stack.push(elem) + return len(stack) + + +if __name__ == "__main__": + print(get_view_sunset([3, 7, 8, 3, 6, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/286.py b/Solutions/286.py new file mode 100644 index 0000000..cd07c08 --- /dev/null +++ b/Solutions/286.py @@ -0,0 +1,64 @@ +""" +Problem: + +The skyline of a city is composed of several buildings of various widths and heights, +possibly overlapping one another when viewed from a distance. We can represent the +buildings using an array of (left, right, height) tuples, which tell us where on an +imaginary x-axis a building begins and ends, and how tall it is. The skyline itself can +be described by a list of (x, height) tuples, giving the locations at which the height +visible to a distant observer changes, and each new height. + +Given an array of buildings as described above, create a function that returns the +skyline. + +For example, suppose the input consists of the buildings +[(0, 15, 3), (4, 11, 5), (19, 23, 4)]. In aggregate, these buildings would create a +skyline that looks like the one below. + + ______ + | | ___ + ___| |___ | | +| | B | | | C | +| A | | A | | | +| | | | | | +------------------------ +As a result, your function should return +[(0, 3), (4, 5), (11, 3), (15, 0), (19, 4), (23, 0)]. +""" + +from sys import maxsize +from typing import List, Tuple + + +def get_skyline(arr: List[Tuple[int, int, int]]) -> List[Tuple[int, int]]: + # getting the bounds of the skyline + start = maxsize + end = -maxsize + for start_curr, end_curr, _ in arr: + start = min(start, start_curr) + end = max(end, end_curr) + # generating the skyline + skyline = [0 for _ in range(start, end + 1)] + offset = start + for start_curr, end_curr, height in arr: + for i in range(start_curr - offset, end_curr - offset): + skyline[i] = max(skyline[i], height) + # generating result from the skyline + result = [] + for i in range(start - offset, end - offset): + if i == 0 or skyline[i] != skyline[i - 1]: + result.append((i + offset, skyline[i])) + result.append((end, 0)) + return result + + +if __name__ == "__main__": + print(get_skyline([(0, 15, 3), (4, 11, 5), (19, 23, 4)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(max(arr) - min(arr)) +SPACE COMPLEXITY: O(max(arr) - min(arr)) +""" diff --git a/Solutions/287.py b/Solutions/287.py new file mode 100644 index 0000000..8d40db7 --- /dev/null +++ b/Solutions/287.py @@ -0,0 +1,109 @@ +""" +Problem: + +You are given a list of (website, user) pairs that represent users visiting websites. +Come up with a program that identifies the top k pairs of websites with the greatest +similarity. + +For example, suppose k = 1, and the list of tuples is: + +[('a', 1), ('a', 3), ('a', 5), + ('b', 2), ('b', 6), + ('c', 1), ('c', 2), ('c', 3), ('c', 4), ('c', 5), + ('d', 4), ('d', 5), ('d', 6), ('d', 7), + ('e', 1), ('e', 3), ('e', 5), ('e', 6)] +Then a reasonable similarity metric would most likely conclude that a and e are the +most similar, so your program should return [('a', 'e')]. +""" + +from typing import Dict, List, Set, Tuple + + +def get_similarity_score( + visited_map: Dict[str, Set[int]], site1: str, site2: str +) -> float: + union = visited_map[site1] | visited_map[site2] + intersection = visited_map[site1] & visited_map[site2] + return len(intersection) / len(union) + + +def create_visit_map(visited_websites: List[Tuple[str, int]]) -> Dict[str, Set[int]]: + visited_map = {} + for site, user in visited_websites: + if site not in visited_map: + visited_map[site] = set() + visited_map[site].add(user) + return visited_map + + +def get_similar_websites_helper( + visited_websites: List[Tuple[str, int]] +) -> Dict[str, Dict[str, float]]: + similarity = {} + visited_map = create_visit_map(visited_websites) + for site1 in visited_map: + for site2 in visited_map: + if site1 not in similarity: + similarity[site1] = {} + if site2 not in similarity: + similarity[site2] = {} + if site1 != site2 and site2 not in similarity[site1]: + similarity_score = get_similarity_score(visited_map, site1, site2) + similarity[site1][site2] = similarity_score + similarity[site2][site1] = similarity_score + return similarity + + +def get_similar_websites( + visited_websites: List[Tuple[str, int]], k: int +) -> List[Tuple[str, str]]: + similarity_map = get_similar_websites_helper(visited_websites) + # generating the similar sites array + arr = [ + (site1, site2, similarity_map[site1][site2]) + for site2 in similarity_map + for site1 in similarity_map + if site1 != site2 + ] + arr.sort(reverse=True, key=lambda x: x[2]) + # generating the top k similar websites + result = [] + for i in range(k): + # choosing every 2nd element as every 2 consecutive elements are the equivalent + # ("a", "b") is equivalent to ("b", "a") + site1, site2, _ = arr[2 * i] + result.append((site1, site2)) + return result + + +if __name__ == "__main__": + visited_websites = [ + ("a", 1), + ("a", 3), + ("a", 5), + ("b", 2), + ("b", 6), + ("c", 1), + ("c", 2), + ("c", 3), + ("c", 4), + ("c", 5), + ("d", 4), + ("d", 5), + ("d", 6), + ("d", 7), + ("e", 1), + ("e", 3), + ("e", 5), + ("e", 6), + ] + print(get_similar_websites(visited_websites, 1)) + print(get_similar_websites(visited_websites, 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/288.py b/Solutions/288.py new file mode 100644 index 0000000..29aaaff --- /dev/null +++ b/Solutions/288.py @@ -0,0 +1,47 @@ +""" +Problem: + +The number 6174 is known as Kaprekar's contant, after the mathematician who discovered +an associated property: for all four-digit numbers with at least two distinct digits, +repeatedly applying a simple procedure eventually results in this value. The procedure +is as follows: + +For a given input x, create two new numbers that consist of the digits in x in +ascending and descending order. Subtract the smaller number from the larger number. +For example, this algorithm terminates in three steps when starting from 1234: + +4321 - 1234 = 3087 +8730 - 0378 = 8352 +8532 - 2358 = 6174 +Write a function that returns how many steps this will take for a given input N. +""" + +KAPREKAR_CONSTANT = 6174 + + +def get_num_steps(num: int, steps: int = 0) -> int: + if len(set(list(str(num)))) < 2: + raise ValueError( + "Kaprekar's operation requires at least 2 distinct digits in the number" + ) + if num == KAPREKAR_CONSTANT: + return steps + # applying Kaprekar's operation + digits = list(str(num)) + digits.sort() + num1 = int("".join(digits[::-1])) + num2 = int("".join(digits)) + return get_num_steps(num1 - num2, steps + 1) + + +if __name__ == "__main__": + print(get_num_steps(1234)) + print(get_num_steps(1204)) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) [as it does not exceed 7] +SPACE COMPLEXITY: O(1) [as the number of digits is 4] +""" diff --git a/Solutions/289.py b/Solutions/289.py new file mode 100644 index 0000000..5cda85f --- /dev/null +++ b/Solutions/289.py @@ -0,0 +1,52 @@ +""" +Problem: + +This problem was asked by Google. + +The game of Nim is played as follows. Starting with three heaps, each containing a +variable number of items, two players take turns removing one or more items from a +single pile. The player who eventually is forced to take the last stone loses. For +example, if the initial heap sizes are 3, 4, and 5, a game could be played as shown +below: + +A B C +3 4 5 +3 1 5 +3 1 3 +0 1 3 +0 1 0 +0 0 0 +In other words, to start, the first player takes three items from pile B. The second +player responds by removing two stones from pile C. The game continues in this way +until player one takes last stone and loses. + +Given a list of non-zero starting values [a, b, c], and assuming optimal play, +determine whether the first player has a forced win. +""" + +# Source: https://en.wikipedia.org/wiki/Nim#Mathematical_theory + +from typing import Tuple + + +def is_forced_win(heaps: Tuple[int, int, int]) -> bool: + x = 0 + for heap in heaps: + x = x ^ heap + for heap in heaps: + xa = heap ^ x + if xa < heap: + return True + return False + + +if __name__ == "__main__": + print(is_forced_win((3, 4, 5))) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/290.py b/Solutions/290.py new file mode 100644 index 0000000..20203c8 --- /dev/null +++ b/Solutions/290.py @@ -0,0 +1,64 @@ +""" +Problem: + +On a mysterious island there are creatures known as Quxes which come in three colors: +red, green, and blue. One power of the Qux is that if two of them are standing next to +each other, they can transform into a single creature of the third color. + +Given N Quxes standing in a line, determine the smallest number of them remaining after +any possible sequence of such transformations. + +For example, given the input ['R', 'G', 'B', 'G', 'B'], it is possible to end up with a +single Qux through the following steps: + + Arrangement | Change +---------------------------------------- +['R', 'G', 'B', 'G', 'B'] | (R, G) -> B +['B', 'B', 'G', 'B'] | (B, G) -> R +['B', 'R', 'B'] | (R, B) -> G +['B', 'G'] | (B, G) -> R +['R'] | +""" + +from typing import List + +from DataStructures.Stack import Stack + + +QUXES = set(["R", "G", "B"]) + + +def generate_new_qux(qux1: str, qux2: str) -> str: + if qux1 == qux2: + raise ValueError("Cannot form new Qux") + result = QUXES - set([qux1, qux2]) + return result.pop() + + +def get_transformation(arrangement: List[str]) -> List[str]: + stack = Stack() + for qux in arrangement: + if stack.is_empty() or stack.peek() == qux: + stack.push(qux) + else: + qux_last = stack.pop() + while True: + # backpropagating in case the previous quxes needs to be updated + qux = generate_new_qux(qux_last, qux) + if stack.is_empty() or stack.peek() == qux: + break + qux_last = stack.pop() + stack.push(qux) + return stack + + +if __name__ == "__main__": + print(get_transformation(["R", "G", "B", "G", "B"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/291.py b/Solutions/291.py new file mode 100644 index 0000000..7dc6415 --- /dev/null +++ b/Solutions/291.py @@ -0,0 +1,50 @@ +""" +Problem: + +An imminent hurricane threatens the coastal town of Codeville. If at most two people +can fit in a rescue boat, and the maximum weight limit for a given boat is k, +determine how many boats will be needed to save everyone. + +For example, given a population with weights [100, 200, 150, 80] and a boat limit of +200, the smallest number of boats required will be three. +""" + +from typing import List + + +def calculate_boats(arr: List[int], k: int) -> int: + length = len(arr) + arr.sort() + + ptr1 = 0 + ptr2 = length - 1 + result = 0 + while ptr1 < ptr2: + if arr[ptr2] > k: + # weight greater than boat weight limit + raise ValueError(f"Cannot accomodate {arr[ptr2]} within limit of {k}") + elif arr[ptr2] + arr[ptr1] > k: + # 2 people CANNOT be accomodated in 1 boat + result += 1 + ptr2 -= 1 + else: + # 2 people CAN be accomodated in 1 boat + result += 1 + ptr1 += 1 + ptr2 -= 1 + if ptr1 == ptr2: + result += 1 + return result + + +if __name__ == "__main__": + print(calculate_boats([100, 200, 150, 80], 200)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n log(n)) +SPACE COMPLEXITY: O(1) +""" + diff --git a/Solutions/292.py b/Solutions/292.py new file mode 100644 index 0000000..8c66741 --- /dev/null +++ b/Solutions/292.py @@ -0,0 +1,77 @@ +""" +Problem: + +A teacher must divide a class of students into two teams to play dodgeball. +Unfortunately, not all the kids get along, and several refuse to be put on the same +team as that of their enemies. + +Given an adjacency list of students and their enemies, write an algorithm that finds a +satisfactory pair of teams, or returns False if none exists. + +For example, given the following enemy graph you should return the teams {0, 1, 4, 5} +and {2, 3}. + +students = { + 0: [3], + 1: [2], + 2: [1, 4], + 3: [0, 4, 5], + 4: [2, 3], + 5: [3] +} +On the other hand, given the input below, you should return False. + +students = { + 0: [3], + 1: [2], + 2: [1, 3, 4], + 3: [0, 2, 4, 5], + 4: [2, 3], + 5: [3] +} +""" + +from typing import Dict, List, Set, Tuple, Union + + +def divide_into_groups( + students: Dict[int, List[int]] +) -> Union[bool, Tuple[Set[int], Set[int]]]: + set1 = set() + set2 = set() + nemesis1 = set() + nemesis2 = set() + + for student in students: + if student in nemesis1 and student in nemesis2: + # satisfactory pair of teams doesn't exist + return False + # creating the necessary reference + if student in nemesis1: + set_curr = set2 + nemesis_curr = nemesis2 + else: + set_curr = set1 + nemesis_curr = nemesis1 + set_curr.add(student) + for nemesis in students[student]: + nemesis_curr.add(nemesis) + return set1, set2 + + +if __name__ == "__main__": + students = {0: [3], 1: [2], 2: [1, 4], 3: [0, 4, 5], 4: [2, 3], 5: [3]} + print(divide_into_groups(students)) + + students = {0: [3], 1: [2], 2: [1, 3, 4], 3: [0, 2, 4, 5], 4: [2, 3], 5: [3]} + print(divide_into_groups(students)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +[O(n) by amortized analysis, as the in the worst case (everyone wants to be alone), +the nested loop runs 2 times and breaks out as the nemesis contains all students] +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/293.py b/Solutions/293.py new file mode 100644 index 0000000..20ca780 --- /dev/null +++ b/Solutions/293.py @@ -0,0 +1,69 @@ +""" +Problem: + +You have N stones in a row, and would like to create from them a pyramid. This pyramid +should be constructed such that the height of each stone increases by one until +reaching the tallest stone, after which the heights decrease by one. In addition, the +start and end stones of the pyramid should each be one stone high. + +You can change the height of any stone by paying a cost of 1 unit to lower its height +by 1, as many times as necessary. Given this information, determine the lowest cost +method to produce this pyramid. + +For example, given the stones [1, 1, 3, 3, 2, 1], the optimal solution is to pay 2 to +create [0, 1, 2, 3, 2, 1]. +""" + +from typing import List + + +def get_min_pyramid_cost(arr: List[int]) -> int: + length = len(arr) + left = [0 for _ in range(length)] + right = [0 for _ in range(length)] + # calculate maximum height (left) + left[0] = min(arr[0], 1) + for i in range(1, length): + left[i] = min(arr[i], min(left[i - 1] + 1, i + 1)) + # calculate maximum height (right) + right[length - 1] = min(arr[length - 1], 1) + for i in range(length - 2, -1, -1): + right[i] = min(arr[i], min(right[i + 1] + 1, length - i)) + + # find minimum possible among calculated values + tot = [0 for _ in range(length)] + for i in range(length): + tot[i] = min(right[i], left[i]) + # find maximum height of pyramid + max_ind = 0 + for i in range(length): + if tot[i] > tot[max_ind]: + max_ind = i + + # calculate cost of this pyramid + cost = 0 + height = tot[max_ind] + # calculate cost of left half + for x in range(max_ind, -1, -1): + cost += arr[x] - height + height = max(0, height - 1) + # calculate cost of right half + height = tot[max_ind] - 1 + for x in range(max_ind + 1, length): + cost += arr[x] - height + height = max(0, height - 1) + return cost + + +if __name__ == "__main__": + print(get_min_pyramid_cost([1, 1, 3, 3, 2, 1])) + print(get_min_pyramid_cost([1, 1, 1, 1, 1])) + print(get_min_pyramid_cost([1, 1, 1, 5, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/294.py b/Solutions/294.py new file mode 100644 index 0000000..f5ab3a3 --- /dev/null +++ b/Solutions/294.py @@ -0,0 +1,108 @@ +""" +Problem: + +A competitive runner would like to create a route that starts and ends at his house, +with the condition that the route goes entirely uphill at first, and then entirely +downhill. + +Given a dictionary of places of the form {location: elevation}, and a dictionary +mapping paths between some of these locations to their corresponding distances, find +the length of the shortest route satisfying the condition above. Assume the runner's +home is location 0. + +For example, suppose you are given the following input: + +elevations = {0: 5, 1: 25, 2: 15, 3: 20, 4: 10} +paths = { + (0, 1): 10, + (0, 2): 8, + (0, 3): 15, + (1, 3): 12, + (2, 4): 10, + (3, 4): 5, + (3, 0): 17, + (4, 0): 10 +} +In this case, the shortest valid path would be 0 -> 2 -> 4 -> 0, with a distance of 28. +""" + +from sys import maxsize +from typing import Dict, List, Set, Tuple + + +def floyd_warshall(graph: List[List[int]]) -> List[List[int]]: + dist = [[elem for elem in row] for row in graph] + nodes = len(graph) + for i in range(nodes): + for j in range(nodes): + for k in range(nodes): + if ( + dist[i][j] < maxsize + and dist[i][k] < maxsize + and dist[k][j] < maxsize + ): + dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) + return dist + + +def generate_graph_adjacency_matix( + paths: Dict[Tuple[int, int], int], nodes: int +) -> List[List[int]]: + graph = [[maxsize for _ in range(nodes)] for _ in range(nodes)] + for src, dest in paths: + graph[src][dest] = paths[src, dest] + return graph + + +def get_route_dfs_helper( + curr_pos: int, + target: int, + acc_weight: int, + visited: Set[int], + graph: List[List[int]], + flag: bool = False, +) -> int: + # flag is used to bypass returning weight of 0 when we start (curr_pos and target + # is 0) + if curr_pos == target and flag: + return acc_weight + visited.add(curr_pos) + distance = maxsize + for neighbour, weight in enumerate(graph[curr_pos]): + if weight < maxsize: + distance = min( + distance, + get_route_dfs_helper( + neighbour, target, acc_weight + weight, visited.copy(), graph, True + ), + ) + return distance + + +def get_route(elevations: Dict[int, int], paths: Dict[Tuple[int, int], int]) -> int: + graph = generate_graph_adjacency_matix(paths, len(elevations)) + dist = floyd_warshall(graph) + return get_route_dfs_helper(0, 0, 0, set(), dist) + + +if __name__ == "__main__": + elevations = {0: 5, 1: 25, 2: 15, 3: 20, 4: 10} + paths = { + (0, 1): 10, + (0, 2): 8, + (0, 3): 15, + (1, 3): 12, + (2, 4): 10, + (3, 4): 5, + (3, 0): 17, + (4, 0): 10, + } + print(get_route(elevations, paths)) + + +""" +SPECS: + +TIME COMPLEXITY: O(v.e) +SPACE COMPLEXITY: O(v ^ 2) +""" diff --git a/Solutions/295.py b/Solutions/295.py new file mode 100644 index 0000000..5e25b01 --- /dev/null +++ b/Solutions/295.py @@ -0,0 +1,51 @@ +""" +Problem: + +Pascal's triangle is a triangular array of integers constructed with the following +formula: + +The first row consists of the number 1. For each subsequent row, each element is the +sum of the numbers directly above it, on either side. For example, here are the first +few rows: + + 1 + 1 1 + 1 2 1 + 1 3 3 1 +1 4 6 4 1 +Given an input k, return the kth row of Pascal's triangle. + +Bonus: Can you do this using only O(k) space? +""" + +from typing import List + + +def get_pascal(k: int) -> List[int]: + row = [1 for _ in range(k)] + curr = 1 + for _ in range(k): + # generating the value for each level + last = 0 + for i in range(curr - 1): + last, temp = row[i], last + row[i] += temp + curr += 1 + return row + + +if __name__ == "__main__": + print(get_pascal(1)) + print(get_pascal(2)) + print(get_pascal(3)) + print(get_pascal(4)) + print(get_pascal(5)) + print(get_pascal(6)) + + +""" +SPECS: + +TIME COMPLEXITY: O(k ^ 2) +SPACE COMPLEXITY: O(k) +""" diff --git a/Solutions/296.py b/Solutions/296.py new file mode 100644 index 0000000..b25eb19 --- /dev/null +++ b/Solutions/296.py @@ -0,0 +1,41 @@ +""" +Problem: + +Given a sorted array, convert it into a height-balanced binary search tree. +""" + +from typing import List + +from DataStructures.Tree import BinarySearchTree + + +def create_balanced_bst_helper(arr: List[int], tree: BinarySearchTree) -> None: + # based on the fact that a sorted array middle element has approximately (with at + # most difference of 1) equal number of elements on its either side + if len(arr) == 0: + return + mid = len(arr) // 2 + tree.add(arr[mid]) + create_balanced_bst_helper(arr[:mid], tree) + create_balanced_bst_helper(arr[mid + 1 :], tree) + + +def create_balanced_bst(arr: List[int]) -> BinarySearchTree: + tree = BinarySearchTree() + create_balanced_bst_helper(arr, tree) + return tree + + +if __name__ == "__main__": + print(create_balanced_bst([1, 2, 3, 4, 5])) + print(create_balanced_bst([1, 2, 3, 4, 5, 6, 7])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +[time complexity can be reduced to O(n) using node reference inplace of calling +tree.add()] +""" diff --git a/Solutions/298.py b/Solutions/298.py new file mode 100644 index 0000000..37481db --- /dev/null +++ b/Solutions/298.py @@ -0,0 +1,65 @@ +""" +Problem: + +A girl is walking along an apple orchard with a bag in each hand. She likes to pick +apples from each tree as she goes along, but is meticulous about not putting different +kinds of apples in the same bag. + +Given an input describing the types of apples she will pass on her path, in order, +determine the length of the longest portion of her path that consists of just two types +of apple trees. + +For example, given the input [2, 1, 2, 3, 3, 1, 3, 5], the longest portion will involve +types 1 and 3, with a length of four. +""" + +from typing import List + + +def get_longest_path_length(apples: List[int]) -> int: + curr_apples = {} + max_path = 0 + start = 0 + curr_apples[apples[start]] = 1 + length = len(apples) + # moving the pointer to the position where the apple is not the same as the 1st + # apple in the array + for i in range(1, length): + if apples[i] in curr_apples: + curr_apples[apples[i]] += 1 + else: + mismatch = i + break + else: + # only 1 type of apple present in the input + return length + curr_apples[apples[mismatch]] = 1 + # updating max_path to find the result + for i in range(mismatch + 1, length): + curr_apple = apples[i] + if curr_apple not in curr_apples: + max_path = max(max_path, i - start) + while len(curr_apples) > 1: + curr_apples[apples[start]] -= 1 + if not curr_apples[apples[start]]: + del curr_apples[apples[start]] + start += 1 + curr_apples[curr_apple] = 1 + else: + curr_apples[curr_apple] += 1 + max_path = max(max_path, length - start) + return max_path + + +if __name__ == "__main__": + print(get_longest_path_length([2, 1, 2, 3, 3, 1, 3, 5])) + print(get_longest_path_length([2, 1, 2, 2, 2, 1, 2, 1])) + print(get_longest_path_length([1, 2, 3, 4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/299.py b/Solutions/299.py new file mode 100644 index 0000000..a14f40a --- /dev/null +++ b/Solutions/299.py @@ -0,0 +1,93 @@ +""" +Problem: + +A group of houses is connected to the main water plant by means of a set of pipes. A +house can either be connected by a set of pipes extending directly to the plant, or +indirectly by a pipe to a nearby house which is otherwise connected. + +For example, here is a possible configuration, where A, B, and C are houses, and arrows +represent pipes: A <--> B <--> C <--> plant + +Each pipe has an associated cost, which the utility company would like to minimize. +Given an undirected graph of pipe connections, return the lowest cost configuration of +pipes such that each house has access to water. + +In the following setup, for example, we can remove all but the pipes from plant to A, +plant to B, and B to C, for a total cost of 16. + +pipes = { + 'plant': {'A': 1, 'B': 5, 'C': 20}, + 'A': {'C': 15}, + 'B': {'C': 10}, + 'C': {} +} +""" + +from sys import maxsize +from typing import Dict, Optional, Tuple + +from DataStructures.Graph import GraphUndirectedWeighted +from DataStructures.PriorityQueue import MinPriorityQueue + + +def dijkstra( + graph: GraphUndirectedWeighted, start: str +) -> Tuple[Dict[str, int], Dict[str, Optional[str]]]: + # dijkstra's algorithm for single source shortest path + dist = {node: maxsize for node in graph.connections} + parent = {node: None for node in graph.connections} + dist[start] = 0 + priority_queue = MinPriorityQueue() + [priority_queue.push(node, weight) for node, weight in dist.items()] + # running dijkstra's algorithm + while not priority_queue.isEmpty(): + node = priority_queue.extract_min() + for neighbour in graph.connections[node]: + if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: + dist[neighbour] = dist[node] + graph.connections[node][neighbour] + priority_queue.update_key(neighbour, dist[neighbour]) + parent[neighbour] = node + return dist, parent + + +def tree_weight_sum(dist: Dict[str, int], parent: Dict[str, Optional[str]]) -> int: + # function to calculate the total weight of the dijkstra's minimum spanning tree + weight_sum = 0 + for node in dist: + if parent[node]: + weight_sum += dist[node] - dist[parent[node]] + return weight_sum + + +def get_minimum_cost(pipes: Dict[str, Dict[str, int]]) -> int: + # function to get the minimum configuration distance of the pipes + # graph generation + graph = GraphUndirectedWeighted() + for src in pipes: + for dest in pipes[src]: + graph.add_edge(src, dest, pipes[src][dest]) + # minimum cost calculation + dist, parent = dijkstra(graph, "plant") + return tree_weight_sum(dist, parent) + + +if __name__ == "__main__": + print( + get_minimum_cost( + pipes={ + "plant": {"A": 1, "B": 5, "C": 20}, + "A": {"C": 15}, + "B": {"C": 10}, + "C": {}, + } + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(e + n.log(n)) +SPACE COMPLEXITY: O(n + e) +[n = number of nodes, e = number of edges] +""" diff --git a/Solutions/300/300.py b/Solutions/300/300.py new file mode 100644 index 0000000..f946152 --- /dev/null +++ b/Solutions/300/300.py @@ -0,0 +1,51 @@ +""" +Problem: + +On election day, a voting machine writes data in the form (voter_id, candidate_id) to a +text file. Write a program that reads this file as a stream and returns the top 3 +candidates at any given time. If you find a voter voting more than once, report this as +fraud. +""" + +from typing import List + + +class MultipleVoteError(Exception): + pass + + +class VotingMachine: + def __init__(self, filename: str = "data.txt") -> None: + with open(filename, "r") as f: + lines = f.readlines() + self.data = [line.rstrip("\n").split(",") for line in lines] + + def get_top_3(self) -> List[str]: + # runs in O(n) time and space + voters = set() + votes = {} + # calculating votes + for voter, candidate in self.data: + if voter in voters: + raise MultipleVoteError(f"Voter {voter} has voted multiple times") + voters.add(voter) + if candidate not in votes: + votes[candidate] = 0 + votes[candidate] += 1 + # geneating the top 3 participants + candidates = list(votes.items()) + candidates.sort(reverse=True, key=lambda x: x[1]) + return [candidate for candidate, _ in candidates[:3]] + + +if __name__ == "__main__": + print("Data Set 1:") + vm = VotingMachine() + print(vm.get_top_3()) + + print("\nData Set 2:") + try: + vm = VotingMachine("dataError.txt") + vm.get_top_3() + except MultipleVoteError as E: + print(E) diff --git a/Solutions/300/data.txt b/Solutions/300/data.txt new file mode 100644 index 0000000..3a2b513 --- /dev/null +++ b/Solutions/300/data.txt @@ -0,0 +1,10 @@ +0,0 +1,0 +2,1 +3,1 +4,1 +5,1 +6,2 +7,3 +8,3 +9,1 \ No newline at end of file diff --git a/Solutions/300/dataError.txt b/Solutions/300/dataError.txt new file mode 100644 index 0000000..a34db1d --- /dev/null +++ b/Solutions/300/dataError.txt @@ -0,0 +1,3 @@ +0,0 +1,1 +0,0 \ No newline at end of file diff --git a/Solutions/301.py b/Solutions/301.py new file mode 100644 index 0000000..554e452 --- /dev/null +++ b/Solutions/301.py @@ -0,0 +1,175 @@ +""" +Problem: + +Implement a data structure which carries out the following operations without resizing +the underlying array: +* add(value): Add a value to the set of values. +* check(value): Check whether a value is in the set. + +The check method may return occasional false positives (in other words, incorrectly +identifying an element as part of the set), but should always correctly identify a true +element. +""" + +# this is an improvised version of the method available at: +# https://www.geeksforgeeks.org/bloom-filters-introduction-and-python-implementation/ + +from bitarray import bitarray +from math import log +from random import shuffle + + +class BloomFilter: + + """ + Class for Bloom filter, using murmur3 hash function + """ + + def __init__(self, items_count: int, fp_prob: float) -> None: + """ + items_count : int + Number of items expected to be stored in bloom filter + fp_prob : float + False Positive probability in decimal + """ + # False posible probability in decimal + self.fp_prob = fp_prob + + # Size of bit array to use + self.size = BloomFilter.get_size(items_count, fp_prob) + + # number of hash functions to use + self.hash_count = BloomFilter.get_hash_count(self.size, items_count) + + # Bit array of given size + self.bit_array = bitarray(self.size) + + # initialize all bits as 0 + self.bit_array.setall(0) + + def add(self, item: str) -> None: + """ + Add an item in the filter + """ + digests = [] + for _ in range(self.hash_count): + + # create digest for given item. + # i work as seed to mmh3.hash() function + # With different seed, digest created is different + digest = hash(item) % self.size + digests.append(digest) + + # set the bit True in bit_array + self.bit_array[digest] = True + + def check(self, item: str) -> bool: + """ + Check for existence of an item in filter + """ + for _ in range(self.hash_count): + digest = hash(item) % self.size + if self.bit_array[digest] == False: + + # if any of bit is False then,its not present + # in filter + # else there is probability that it exist + return False + return True + + @staticmethod + def get_size(n: int, p: float) -> int: + """ + Return the size of bit array(m) to used using + following formula + m = -(n * lg(p)) / (lg(2)^2) + n : int + number of items expected to be stored in filter + p : float + False Positive probability in decimal + """ + m = -(n * log(p)) / (log(2) ** 2) + return int(m) + + @staticmethod + def get_hash_count(m: int, n: int) -> int: + """ + Return the hash function(k) to be used using + following formula + k = (m/n) * lg(2) + + m : int + size of bit array + n : int + number of items expected to be stored in filter + """ + k = (m / n) * log(2) + return int(k) + + +if __name__ == "__main__": + n = 20 # no of items to add + p = 0.05 # false positive probability + + bloomf = BloomFilter(n, p) + print("Size of bit array:{}".format(bloomf.size)) + print("False positive Probability:{}".format(bloomf.fp_prob)) + print("Number of hash functions:{}\n".format(bloomf.hash_count)) + + # words to be added + word_present = [ + "abound", + "abounds", + "abundance", + "abundant", + "accessable", + "bloom", + "blossom", + "bolster", + "bonny", + "bonus", + "bonuses", + "coherent", + "cohesive", + "colorful", + "comely", + "comfort", + "gems", + "generosity", + "generous", + "generously", + "genial", + ] + + # word not added + word_absent = [ + "bluff", + "cheater", + "hate", + "war", + "humanity", + "racism", + "hurt", + "nuke", + "gloomy", + "facebook", + "geeksforgeeks", + "twitter", + ] + + for item in word_present: + bloomf.add(item) + + shuffle(word_present) + shuffle(word_absent) + + test_words = word_present[:10] + word_absent + shuffle(test_words) + for word in test_words: + if bloomf.check(word): + if word in word_absent: + print("'{}' is a false positive!".format(word)) + else: + print("'{}' is probably present!".format(word)) + else: + print("'{}' is definitely not present!".format(word)) diff --git a/Solutions/302.py b/Solutions/302.py new file mode 100644 index 0000000..1cda999 --- /dev/null +++ b/Solutions/302.py @@ -0,0 +1,85 @@ +""" +Problem: + +You are given a 2-d matrix where each cell consists of either /, \, or an empty space. +Write an algorithm that determines into how many regions the slashes divide the space. + +For example, suppose the input for a three-by-six grid is the following: + +\ / + \ / + \/ +Considering the edges of the matrix as boundaries, this divides the grid into three +triangles, so you should return 3. +""" + +from typing import Set, Tuple + + +def explore_region( + position: Tuple[int, int], empty_spaces: Set, nrows: int, ncols: int +) -> None: + # dfs helper to remove all adjoining empty spaces for each region + if position not in empty_spaces: + return + # travelling to the adjoining spaces + empty_spaces.remove(position) + x, y = position + if x > 0: + explore_region((x - 1, y), empty_spaces, nrows, ncols) + if x < nrows - 1: + explore_region((x + 1, y), empty_spaces, nrows, ncols) + if y > 0: + explore_region((x, y - 1), empty_spaces, nrows, ncols) + if y < ncols - 1: + explore_region((x, y + 1), empty_spaces, nrows, ncols) + + +def get_region_count(matrix: str) -> int: + nrows, ncols = len(matrix), len(matrix[0]) + empty_spaces = set() + for row in range(nrows): + for col in range(ncols): + if matrix[row][col] == " ": + empty_spaces.add((row, col)) + # traversing through the empty spaces + regions = 0 + while empty_spaces: + # random position selection + for pos in empty_spaces: + position = pos + break + explore_region(position, empty_spaces, nrows, ncols) + regions += 1 + return regions + + +if __name__ == "__main__": + matrix = [ + list(r"\ /"), + list(r" \ / "), + list(r" \/ ") + ] + print(get_region_count(matrix)) + + matrix = [ + list(r" /"), + list(r" \ / "), + list(r" \/ ") + ] + print(get_region_count(matrix)) + + matrix = [ + list(r" /"), + list(r" \ / "), + list(r" \ ") + ] + print(get_region_count(matrix)) + + +""" +SPECS: + +TIME COMPLEXITY: O(row x column) +SPACE COMPLEXITY: O(row x column) +""" diff --git a/Solutions/303.py b/Solutions/303.py new file mode 100644 index 0000000..105085a --- /dev/null +++ b/Solutions/303.py @@ -0,0 +1,54 @@ +""" +Problem: + +Given a clock time in hh:mm format, determine, to the nearest degree, the angle between +the hour and the minute hands. + +Bonus: When, during the course of a day, will the angle be zero? +""" + + +HOUR_ANGLE = { + 1: (1 / 12) * 360, + 2: (2 / 12) * 360, + 3: (3 / 12) * 360, + 4: (4 / 12) * 360, + 5: (5 / 12) * 360, + 6: (6 / 12) * 360, + 7: (7 / 12) * 360, + 8: (8 / 12) * 360, + 9: (9 / 12) * 360, + 10: (10 / 12) * 360, + 11: (11 / 12) * 360, + 12: (12 / 12) * 360, +} + + +def get_displaced_hour_angle(mm: int) -> float: + return (mm / 60) * (360 / 12) + + +def get_minutes_angle(mm: int) -> float: + return (mm / 60) * 360 + + +def get_angle_between_arms(time: str) -> int: + hh, mm = [int(elem) for elem in time.split(":")] + hour_angle = (HOUR_ANGLE[hh] + get_displaced_hour_angle(mm)) % 360 + minute_angle = get_minutes_angle(mm) + return round(abs(hour_angle - minute_angle)) + + +if __name__ == "__main__": + print(get_angle_between_arms("12:20")) + print(get_angle_between_arms("12:00")) + print(get_angle_between_arms("6:30")) + print(get_angle_between_arms("3:45")) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/304.py b/Solutions/304.py new file mode 100644 index 0000000..7eaee39 --- /dev/null +++ b/Solutions/304.py @@ -0,0 +1,60 @@ +""" +Problem: + +A knight is placed on a given square on an 8 x 8 chessboard. It is then moved randomly +several times, where each move is a standard knight move. If the knight jumps off the +board at any point, however, it is not allowed to jump back on. + +After k moves, what is the probability that the knight remains on the board? +""" + +from typing import List, Tuple + + +def get_moves(position: Tuple[int, int]) -> List[Tuple[int, int]]: + i, j = position + moves = [ + (i + 2, j + 1), + (i + 2, j - 1), + (i - 2, j + 1), + (i - 2, j - 1), + (i + 1, j + 2), + (i + 1, j - 2), + (i - 1, j + 2), + (i - 1, j - 2), + ] + return moves + + +def get_knight_on_board_probability_helper(position: Tuple[int, int], k: int) -> int: + i, j = position + if not (0 <= i < 8) or not (0 <= j < 8): + return 0 + if k == 0: + return 1 + # generating total number of valid moves from current position + moves = get_moves(position) + accumulator = 0 + for pos in moves: + accumulator += get_knight_on_board_probability_helper(pos, k - 1) + return accumulator + + +def get_knight_on_board_probability(position: Tuple[int, int], k: int) -> float: + # P(knight remains on board) = (number of positions on board / total positions) + number_of_move_in_board = get_knight_on_board_probability_helper(position, k) + return number_of_move_in_board / pow(8, k) + + +if __name__ == "__main__": + print("{:.3f}".format(get_knight_on_board_probability((4, 4), 1))) + print("{:.3f}".format(get_knight_on_board_probability((4, 4), 2))) + print("{:.3f}".format(get_knight_on_board_probability((1, 1), 3))) + + +""" +SPECS: + +TIME COMPLEXITY: O(8 ^ k) +SPACE COMPLEXITY: O(k) +""" diff --git a/Solutions/306.py b/Solutions/306.py new file mode 100644 index 0000000..99a85f5 --- /dev/null +++ b/Solutions/306.py @@ -0,0 +1,44 @@ +""" +Problem: + +You are given a list of N numbers, in which each number is located at most k places +away from its sorted position. For example, if k = 1, a given element at index 4 might +end up at indices 3, 4, or 5. + +Come up with an algorithm that sorts this list in O(N log k) time. +""" + +from typing import List + +from DataStructures.Heap import MinHeap + + +def k_sort(arr: List[int], k: int) -> List[int]: + length = len(arr) + heap = MinHeap() + [heap.insert(elem) for elem in arr[: k + 1]] + # updating the values of the array (to hold sorted elements) + curr_index = 0 + for index in range(k + 1, length): + arr[curr_index] = heap.extract_min() + heap.insert(arr[index]) + curr_index += 1 + # updating the last k positions in the array by emptying the heap + while heap: + arr[curr_index] = heap.extract_min() + curr_index += 1 + return arr + + +if __name__ == "__main__": + print(k_sort([1, 0, 2, 4, 3], 2)) + print(k_sort([6, 5, 3, 2, 8, 10, 9], 3)) + print(k_sort([10, 9, 8, 7, 4, 70, 60, 50], 4)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n log(k)) +SPACE COMPLEXITY: O(k) +""" diff --git a/Solutions/307.py b/Solutions/307.py new file mode 100644 index 0000000..8cae402 --- /dev/null +++ b/Solutions/307.py @@ -0,0 +1,79 @@ +""" +Problem: + +Given a binary search tree, find the floor and ceiling of a given integer. The floor is +the highest element in the tree less than or equal to an integer, while the ceiling is +the lowest element in the tree greater than or equal to an integer. + +If either value does not exist, return None. +""" + +from typing import Optional, Tuple + +from DataStructures.Tree import BinarySearchTree, Node + + +def get_ceiling(node: Node, value: int) -> Optional[int]: + # function to get the ceiling of the input in a binary search tree + # using BST property to find the element optiomally + if node.val > value: + if node.left: + if node.left.val >= value: + return get_ceiling(node.left, value) + return node.val + return node.val + elif node.val == value: + return value + else: + if node.right: + return get_ceiling(node.right, value) + return None + + +def get_floor(node: Node, value: int) -> Optional[int]: + # function to get the floor of the input in a binary search tree + # using BST property to find the element optiomally + if node.val < value: + if node.right: + if node.right.val <= value: + return get_floor(node.right, value) + return node.val + return node.val + elif node.val == value: + return value + else: + if node.left: + return get_floor(node.left, value) + return None + + +def get_floor_and_ceiling( + tree: BinarySearchTree, value: int +) -> Tuple[Optional[int], Optional[int]]: + # function to get the ceiling and floor of the input in a binary search tree + if tree.root: + return get_floor(tree.root, value), get_ceiling(tree.root, value) + return None, None + + +if __name__ == "__main__": + tree = BinarySearchTree() + + tree.add(4) + tree.add(2) + tree.add(1) + tree.add(3) + tree.add(6) + + print(get_floor_and_ceiling(tree, 2)) + print(get_floor_and_ceiling(tree, 7)) + print(get_floor_and_ceiling(tree, -1)) + print(get_floor_and_ceiling(tree, 5)) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/308.py b/Solutions/308.py new file mode 100644 index 0000000..809b86f --- /dev/null +++ b/Solutions/308.py @@ -0,0 +1,61 @@ +""" +Problem: +You are presented with an array representing a Boolean expression. The elements are of +two kinds: + +T and F, representing the values True and False. +&, |, and ^, representing the bitwise operators for AND, OR, and XOR. +Determine the number of ways to group the array elements using parentheses so that the +entire expression evaluates to True. + +For example, suppose the input is ['F', '|', 'T', '&', 'T']. In this case, there are +two acceptable groupings: (F | T) & T and F | (T & T). +""" + +from typing import List + + +def evaluator(arr: List[str]) -> List[bool]: + expr = "".join(arr) + if len(arr) == 1 or len(arr) == 3: + return [eval(expr)] + + groupings = [] + # checking all possible arrangements + for i in range(len(arr) // 2): + pivot = i * 2 + 1 + left = arr[:pivot] + right = arr[pivot + 1 :] + for fe in evaluator(left): + for se in evaluator(right): + new_exp = str(fe) + arr[pivot] + str(se) + # adding the expression only if evaluates to True + if eval(new_exp): + groupings.append(True) + return groupings + + +def get_groupings(arr: List[str]) -> int: + # replacing the 'T's and 'F's + for ind in range(len(arr)): + if arr[ind] == "F": + arr[ind] = "False" + elif arr[ind] == "T": + arr[ind] = "True" + return len(evaluator(arr)) + + +if __name__ == "__main__": + print(get_groupings(["F", "|", "T", "&", "T"])) + print(get_groupings(["F", "|", "T", "&", "T", "^", "F"])) + print(get_groupings(["F", "|", "T", "&", "F", "^", "F"])) + print(get_groupings(["F", "|", "T", "|", "F", "^", "F"])) + print(get_groupings(["T", "^", "T", "&", "F"])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 3) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/309.py b/Solutions/309.py new file mode 100644 index 0000000..5c1ce07 --- /dev/null +++ b/Solutions/309.py @@ -0,0 +1,71 @@ +""" +Problem: + +There are M people sitting in a row of N seats, where M < N. Your task is to +redistribute people such that there are no gaps between any of them, while keeping +overall movement to a minimum. + +For example, suppose you are faced with an input of [0, 1, 1, 0, 1, 0, 0, 0, 1], where +0 represents an empty seat and 1 represents a person. In this case, one solution would +be to place the person on the right in the fourth seat. We can consider the cost of a +solution to be the sum of the absolute distance each person must move, so that the cost +here would be 5. + +Given an input such as the one above, return the lowest possible cost of moving people +to remove all gaps. +""" + +from itertools import permutations +from sys import maxsize +from typing import List, Set + + +def get_people_indices(arr: List[int]) -> Set[int]: + return set([index for index, occupied in enumerate(arr) if occupied]) + + +def get_min_dist(vacant_spots: List[int], available_people: List[int]) -> int: + # generating all permutations and returning the minumum cost + min_dist = maxsize + length = len(vacant_spots) + permutation_list = list(permutations(range(length))) + for permutation in permutation_list: + dist = 0 + for i in range(length): + k = permutation[i] + dist += abs(vacant_spots[i] - available_people[k]) + min_dist = min(min_dist, dist) + return min_dist + + +def get_lowest_cost(arr: List[int]) -> int: + num_people = sum(arr) + if num_people in (0, 1): + return 0 + starting_people_indices = get_people_indices(arr) + lowest_cost = maxsize + # generating all possible valid seating arrangements and getting the minimum cost + for offset in range(len(arr) - num_people + 1): + subarr = arr[offset : offset + num_people] + all_indices = set([offset + x for x in range(num_people)]) + people_indices = set([offset + x for x in get_people_indices(subarr)]) + + vacant_indices = list(all_indices - people_indices) + occupied_indices = list(starting_people_indices - people_indices) + lowest_cost = min(lowest_cost, get_min_dist(vacant_indices, occupied_indices)) + return lowest_cost + + +if __name__ == "__main__": + print(get_lowest_cost([0, 1, 1, 0, 1, 0, 0, 0, 1])) + print(get_lowest_cost([0, 1, 0, 0, 1, 0, 1, 0, 1])) + print(get_lowest_cost([1, 1, 0, 0, 1, 0, 1, 0, 1])) + print(get_lowest_cost([1, 1, 1, 1, 1, 0, 0, 0, 0])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x n!) +SPACE COMPLEXITY: O(n!) +""" diff --git a/Solutions/310.py b/Solutions/310.py new file mode 100644 index 0000000..a9f5af8 --- /dev/null +++ b/Solutions/310.py @@ -0,0 +1,77 @@ +""" +Problem: + +Write an algorithm that finds the total number of set bits in all integers between 1 +and N. +""" + +from math import log +from time import perf_counter + + +def get_set_bits(num: int) -> int: + bin_num = bin(num)[2:] + return sum([int(digit) for digit in bin_num]) + + +def get_total_set_bits(N: int) -> int: + result = 0 + for i in range(1, N + 1): + result += get_set_bits(i) + return result + + +def get_total_set_bits_optimized(N: int) -> int: + if N < 1: + return 0 + + # Find the greatest power of 2 less than or equal to n + exp = int(log(N, 2)) + pow = 2**exp + + # Initializations + extra_ones = 0 + sum = 0 + while True: + # Count the bits of the pow-many numbers starting from where we left off (or 1, if the first iteration) + # The logic here is that each of the least significant exp-many bits occurs in half those numbers, i.e. pow/2 times. Plus all the more significant bits that are constantly set throughout + sum += pow // 2 * exp + pow * extra_ones + + # All numbers above this will have an additional bit set + extra_ones += 1 + + # If n is a power of two, add its own bits and exit + if pow == N: + sum += extra_ones + break + + # Now set n to be the remainder after counting pow numbers... + N -= pow + # ...and calculate the greatest power of 2 that is less than or equal to our new n + while pow > N: + pow //= 2 + exp -= 1 + + return sum + + +if __name__ == "__main__": + for i in list(range(6)) + [10**6]: + for f in [get_total_set_bits, get_total_set_bits_optimized]: + start = perf_counter() + result = f(i) + end = perf_counter() + print(f"{result} ({end-start:.3} sec)") + + +""" +SPECS: + +get_total_set_bits: +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(1) + +get_total_set_bits_optimized: +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/311.py b/Solutions/311.py new file mode 100644 index 0000000..435306a --- /dev/null +++ b/Solutions/311.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given an unsorted array, in which all elements are distinct, find a "peak" element in +O(log N) time. + +An element is considered a peak if it is greater than both its left and right +neighbors. It is guaranteed that the first and last elements are lower than all others. +""" + +from typing import List + + +def get_peak(arr: List[int]) -> int: + # implement similar method as binary search [since the element being searched is + # not a concrete value (unlike binary search), but any value which is greater than + # its neighbours, it can only be found without sorting] + mid = len(arr) // 2 + if ( + mid > 0 + and arr[mid - 1] < arr[mid] + and mid < len(arr) + and arr[mid + 1] < arr[mid] + ): + return arr[mid] + elif mid > 0 and arr[mid - 1] < arr[mid]: + return get_peak(arr[mid:]) + return get_peak(arr[: mid + 1]) + + +if __name__ == "__main__": + print(get_peak([0, 2, 4, -1, 3, 1])) + print(get_peak([0, 2, 4, 5, 3, 1])) + print(get_peak([0, 2, 6, 5, 3, 1])) + print(get_peak([0, 2, 4, 5, 7, 1])) + print(get_peak([0, 8, 7, 5, 16, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(log(n)) +SPACE COMPLEXITY: O(1) +""" + diff --git a/Solutions/312.py b/Solutions/312.py new file mode 100644 index 0000000..dc00e60 --- /dev/null +++ b/Solutions/312.py @@ -0,0 +1,37 @@ +""" +Problem: + +You are given a 2 x N board, and instructed to completely cover the board with the +following shapes: + +Dominoes, or 2 x 1 rectangles. +Trominoes, or L-shapes. +For example, if N = 4, here is one possible configuration, where A is a domino, and B +and C are trominoes. + +A B B C +A B C C +Given an integer N, determine in how many ways this task is possible. +""" + + +def count_arragements(N: int) -> int: + dp = [0 for _ in range(max(3, N + 1))] + # base cases + dp[0] = 1 # no domino/trominoes selected + dp[1] = 1 + dp[2] = 2 + # updating the lookup table + for i in range(3, N + 1): + dp[i] = 2 * dp[i - 1] + dp[i - 3] + # returning the required value + return dp[N] + + +if __name__ == "__main__": + print(count_arragements(0)) + print(count_arragements(1)) + print(count_arragements(2)) + print(count_arragements(3)) + print(count_arragements(4)) + print(count_arragements(5)) diff --git a/Solutions/313.py b/Solutions/313.py new file mode 100644 index 0000000..9930c4d --- /dev/null +++ b/Solutions/313.py @@ -0,0 +1,90 @@ +""" +Problem: + +You are given a circular lock with three wheels, each of which display the numbers 0 +through 9 in order. Each of these wheels rotate clockwise and counterclockwise. + +In addition, the lock has a certain number of "dead ends", meaning that if you turn the +wheels to one of these combinations, the lock becomes stuck in that state and cannot be +opened. + +Let us consider a "move" to be a rotation of a single wheel by one digit, in either +direction. Given a lock initially set to 000, a target combination, and a list of dead +ends, write a function that returns the minimum number of moves required to reach the +target state, or None if this is impossible. +""" + +from sys import maxsize +from typing import List, Tuple, Set + + +def turn_wheel_up(val: int) -> int: + return (val + 1) % 10 + + +def turn_wheel_down(val: int) -> int: + return (val - 1 + 10) % 10 + + +def get_min_moves_helper( + curr: List[int], + pattern: List[int], + dead_ends: Set[Tuple[int, int, int]], + seen: Set[str], + accumulator: int = 0, +) -> int: + if curr == pattern: + return accumulator + curr_val = "".join([str(x) for x in curr]) + if curr_val in seen: + # if a loop back occours, the target pattern cannot be reached + return maxsize + seen.add(curr_val) + + moves = [] + for i in range(3): + temp = curr.copy() + if temp[i] != pattern[i]: + temp[i] = turn_wheel_up(temp[i]) + if tuple(temp) not in dead_ends: + moves.append(temp) + temp = curr.copy() + if temp[i] != pattern[i]: + temp[i] = turn_wheel_down(temp[i]) + if tuple(temp) not in dead_ends: + moves.append(temp) + + temp = maxsize + for move in moves: + temp = min( + temp, get_min_moves_helper(move, pattern, dead_ends, seen, accumulator + 1), + ) + return temp + + +def get_min_moves(pattern, dead_ends): + result = get_min_moves_helper([0, 0, 0], pattern, dead_ends, set()) + if result == maxsize: + return None + return result + + +if __name__ == "__main__": + print(get_min_moves([3, 4, 5], set([]))) + print(get_min_moves([3, 4, 5], set([(0, 0, 1), (0, 1, 0), (1, 0, 0)]))) + print( + get_min_moves( + [3, 4, 5], + set([(0, 0, 1), (0, 1, 0), (1, 0, 0), (0, 0, 9), (0, 9, 0), (9, 0, 0)]), + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ n) +SPACE COMPLEXITY: O(n ^ n) +[n = max(pattern)] +""" + diff --git a/Solutions/314.py b/Solutions/314.py new file mode 100644 index 0000000..0573c75 --- /dev/null +++ b/Solutions/314.py @@ -0,0 +1,41 @@ +""" +Problem: + +You are the technical director of WSPT radio, serving listeners nationwide. For +simplicity's sake we can consider each listener to live along a horizontal line +stretching from 0 (west) to 1000 (east). + +Given a list of N listeners, and a list of M radio towers, each placed at various +locations along this line, determine what the minimum broadcast range would have to be +in order for each listener's home to be covered. + +For example, suppose listeners = [1, 5, 11, 20], and towers = [4, 8, 15]. In this case +the minimum range would be 5, since that would be required for the tower at position 15 +to reach the listener at position 20. +""" + +from sys import maxsize +from typing import List + + +def get_min_range(listeners: List[int], towers: List[int]) -> int: + # distance map storing the distance of listener from the nearest tower + listeners_distance = {listener: maxsize for listener in listeners} + for listener in listeners: + for tower in towers: + listeners_distance[listener] = min( + listeners_distance[listener], abs(tower - listener) + ) + return max(listeners_distance.values()) + + +if __name__ == "__main__": + print(get_min_range([1, 5, 11, 20], [4, 8, 15])) + + +""" +SPECS: + +TIME COMPLEXITY: O(listeners x towers) +SPACE COMPLEXITY: O(listeners) +""" diff --git a/Solutions/315.py b/Solutions/315.py new file mode 100644 index 0000000..467c5fd --- /dev/null +++ b/Solutions/315.py @@ -0,0 +1,66 @@ +""" +Problem: + +In linear algebra, a Toeplitz matrix is one in which the elements on any given diagonal +from top left to bottom right are identical. + +Here is an example: + +1 2 3 4 8 +5 1 2 3 4 +4 5 1 2 3 +7 4 5 1 2 +Write a program to determine whether a given input is a Toeplitz matrix. +""" + +from typing import List + + +def is_toeplitz_matrix(matrix: List[List[int]]) -> bool: + n = len(matrix) + m = len(matrix[0]) + # checking the diagonals starting from the left edge + for i in range(n): + val = matrix[i][0] + for row, col in zip(range(i, n), range(m)): + if matrix[row][col] != val: + return False + # checking the diagonals starting from the top edge + for i in range(1, m): + val = matrix[0][i] + for row, col in zip(range(n), range(i, m)): + if matrix[row][col] != val: + return False + return True + + +if __name__ == "__main__": + print( + is_toeplitz_matrix( + [ + [1, 2, 3, 4, 8], + [5, 1, 2, 3, 4], + [4, 5, 1, 2, 3], + [7, 4, 5, 1, 2] + ] + ) + ) + + print( + is_toeplitz_matrix( + [ + [1, 2, 3, 4, 8], + [5, 1, 2, 3, 4], + [4, 5, 1, 2, 3], + [7, 4, 5, 1, 1] + ] + ) + ) + + +""" +SPECS: +TIME COMPLEXITY: O(n x m) +SPACE COMPLEXITY: O(1) [as zip and range both are generator functions] +[n = rows, m = columns] +""" diff --git a/Solutions/316.py b/Solutions/316.py new file mode 100644 index 0000000..1428d20 --- /dev/null +++ b/Solutions/316.py @@ -0,0 +1,61 @@ +""" +Problem: + +You are given an array of length N, where each element i represents the number of ways +we can produce i units of change. For example, [1, 0, 1, 1, 2] would indicate that +there is only one way to make 0, 2, or 3 units, and two ways of making 4 units. + +Given such an array, determine the denominations that must be in use. In the case +above, for example, there must be coins with value 2, 3, and 4. +""" + +from typing import List + + +def count_ways_to_generate_change(changes: List[int], target: int) -> int: + length = len(changes) + if not length: + return 0 + table = [[0 for x in range(length)] for x in range(target + 1)] + for i in range(length): + table[0][i] = 1 + for i in range(1, target + 1): + for j in range(length): + if i - changes[j] >= 0: + x = table[i - changes[j]][j] + else: + x = 0 + if j >= 1: + y = table[i][j - 1] + else: + y = 0 + table[i][j] = x + y + return table[target][length - 1] + + +def get_changes(num_ways_to_get_change: List[int]) -> List[int]: + length = len(num_ways_to_get_change) + changes_list = [] + + for i in range(1, length): + if num_ways_to_get_change[i] > 0: + count = count_ways_to_generate_change(changes_list, i) + if count == 0 or count + 1 == num_ways_to_get_change[i]: + changes_list.append(i) + return changes_list + + +if __name__ == "__main__": + print(get_changes([1, 0, 1, 1, 2])) + print(get_changes([1, 0, 1, 1, 2, 1, 3])) + print(get_changes([1, 0, 1, 1, 2, 1, 4])) + print(get_changes([1, 0, 1, 1, 2, 1, 4, 2])) + print(get_changes([1, 0, 1, 1, 2, 1, 4, 3])) + + +""" +SPECS: +TIME COMPLEXITY: O(n ^ 3) +SPACE COMPLEXITY: O(n ^ 2) +[n = number of elements] +""" diff --git a/Solutions/317.py b/Solutions/317.py new file mode 100644 index 0000000..8ebcb0e --- /dev/null +++ b/Solutions/317.py @@ -0,0 +1,30 @@ +""" +Problem: + +Write a function that returns the bitwise AND of all integers between M and N, +inclusive. +""" + + +def bitwise_and_on_range(start: int, end: int) -> int: + # using naive approach + result = start + for num in range(start + 1, end + 1): + result = result & num + return result + + +if __name__ == "__main__": + print(bitwise_and_on_range(3, 4)) + print(bitwise_and_on_range(5, 6)) + print(bitwise_and_on_range(126, 127)) + print(bitwise_and_on_range(127, 215)) + print(bitwise_and_on_range(129, 215)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/318.py b/Solutions/318.py new file mode 100644 index 0000000..c8fd08a --- /dev/null +++ b/Solutions/318.py @@ -0,0 +1,45 @@ +""" +Problem: + +You are going on a road trip, and would like to create a suitable music playlist. The +trip will require N songs, though you only have M songs downloaded, where M < N. A +valid playlist should select each song at least once, and guarantee a buffer of B songs +between repeats. + +Given N, M, and B, determine the number of valid playlists. +""" + + +def get_num_of_valid_playlist(N: int, M: int, B: int) -> int: + # possible ways of selecting each song = [ + # (N), (N - 1), (N - 2) ... (N - B), (N - B), (N - B), ... till M songs + # ] + if B >= N: + return 0 + result = 1 + curr = N + for i in range(M): + result = result * curr + # after B songs, 1 new song will be available and 1 will be off limits, so the + # number of available songs will be locked at (N - B) + if i < B: + curr -= 1 + return result + + +if __name__ == "__main__": + # (1, 2, 1), (2, 1, 2) + print(get_num_of_valid_playlist(2, 3, 1)) + + # (1, 2, 3, 1), (1, 3, 2, 1), + # (2, 1, 3, 2), (2, 3, 1, 2), + # (3, 1, 2, 3), (3, 2, 1, 3) + print(get_num_of_valid_playlist(3, 4, 2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(m) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/319.py b/Solutions/319.py new file mode 100644 index 0000000..5e88761 --- /dev/null +++ b/Solutions/319.py @@ -0,0 +1,260 @@ +""" +Problem: + +An 8-puzzle is a game played on a 3 x 3 board of tiles, with the ninth tile missing. +The remaining tiles are labeled 1 through 8 but shuffled randomly. Tiles may slide +horizontally or vertically into an empty space, but may not be removed from the board. + +Design a class to represent the board, and find a series of steps to bring the board +to the state [[1, 2, 3], [4, 5, 6], [7, 8, None]]. +""" +# this is an improvised version of the method available at: +# https://gist.github.com/flatline/838202 + +from __future__ import annotations +from math import sqrt +from typing import Callable, List, Mapping, Tuple, Union + +FINAL_STATE = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] + + +def index(item: EightPuzzle, seq: List[EightPuzzle]) -> int: + """ + Helper function that returns -1 for non-found index value of a seq + """ + if item in seq: + return seq.index(item) + return -1 + + +class EightPuzzle: + def __init__(self, board: List[List[int]]) -> None: + # heuristic value + self._hval = 0 + # search depth of current instance + self._depth = 0 + # parent node in search path + self._parent = None + self.adj_matrix = [] + self.adj_matrix = board + + def __eq__(self, other: EightPuzzle) -> bool: + return self.adj_matrix == other.adj_matrix + + def __str__(self) -> str: + res = "" + for row in range(3): + res += " ".join(map(str, self.adj_matrix[row])) + res += "\r\n" + return res + + def _clone(self) -> EightPuzzle: + copy = [[elem for elem in row] for row in self.adj_matrix] + p = EightPuzzle(copy) + return p + + def _get_legal_moves(self) -> List[Tuple[int, int]]: + """ + Returns list of tuples with which the free space may be swapped + """ + # get row and column of the empty piece + row, col = self.find(0) + free = [] + # find which pieces can move there + if row > 0: + free.append((row - 1, col)) + if col > 0: + free.append((row, col - 1)) + if row < 2: + free.append((row + 1, col)) + if col < 2: + free.append((row, col + 1)) + + return free + + def _generate_moves(self) -> Mapping[EightPuzzle]: + free = self._get_legal_moves() + zero = self.find(0) + + def swap_and_clone(a: int, b: int) -> EightPuzzle: + p = self._clone() + p.swap(a, b) + p._depth = self._depth + 1 + p._parent = self + return p + + return map(lambda pair: swap_and_clone(zero, pair), free) + + def _generate_solution_path(self, path: List[EightPuzzle]): + if self._parent is None: + return path + path.append(self) + return self._parent._generate_solution_path(path) + + def solve(self, h: Callable) -> Tuple[List[EightPuzzle], int]: + """ + Performs A* search for goal state. + h(puzzle) - heuristic function, returns an integer + """ + + def is_solved(puzzle: EightPuzzle) -> bool: + return puzzle.adj_matrix == FINAL_STATE + + openl = [self] + closedl = [] + move_count = 0 + while len(openl) > 0: + x = openl.pop(0) + move_count += 1 + if is_solved(x): + if len(closedl) > 0: + return x._generate_solution_path([]), move_count + else: + return [x] + + succ = x._generate_moves() + idx_open = idx_closed = -1 + for move in succ: + # have we already seen this node? + idx_open = index(move, openl) + idx_closed = index(move, closedl) + hval = h(move) + fval = hval + move._depth + + if idx_closed == -1 and idx_open == -1: + move._hval = hval + openl.append(move) + elif idx_open > -1: + copy = openl[idx_open] + if fval < copy._hval + copy._depth: + # copy move's values over existing + copy._hval = hval + copy._parent = move._parent + copy._depth = move._depth + elif idx_closed > -1: + copy = closedl[idx_closed] + if fval < copy._hval + copy._depth: + move._hval = hval + closedl.remove(copy) + openl.append(move) + + closedl.append(x) + openl = sorted(openl, key=lambda p: p._hval + p._depth) + # if finished state not found, return failure + return [], 0 + + def find(self, value: int) -> Tuple[int, int]: + """ + returns the row, col coordinates of the specified value in the graph + """ + if value < 0 or value > 8: + raise Exception("value out of range") + + for row in range(3): + for col in range(3): + if self.adj_matrix[row][col] == value: + return row, col + + def peek(self, row: int, col: int) -> int: + """ + returns the value at the specified row and column + """ + return self.adj_matrix[row][col] + + def poke(self, row: int, col: int, value: int) -> int: + """ + sets the value at the specified row and column + """ + self.adj_matrix[row][col] = value + + def swap(self, pos_a: Tuple[int, int], pos_b: Tuple[int, int]) -> None: + """ + swaps values at the specified coordinates + """ + temp = self.peek(*pos_a) + self.poke(pos_a[0], pos_a[1], self.peek(*pos_b)) + self.poke(pos_b[0], pos_b[1], temp) + + +def heur( + puzzle: EightPuzzle, item_total_calc: Callable, total_calc: Callable +) -> Union[int, float]: + """ + Heuristic template that provides the current and target position for each number + and the total function. + + Parameters: + puzzle - the puzzle + item_total_calc - takes 4 parameters: current row, target row, current col, target + col. + Returns int. + total_calc - takes 1 parameter, the sum of item_total_calc over all entries, and + returns int. + This is the value of the heuristic function + """ + t = 0 + for row in range(3): + for col in range(3): + val = puzzle.peek(row, col) - 1 + target_col = val % 3 + target_row = val / 3 + # account for 0 as blank + if target_row < 0: + target_row = 2 + t += item_total_calc(row, target_row, col, target_col) + return total_calc(t) + + +# some heuristic functions, the best being the standard manhattan distance in this +# case, as it comes closest to maximizing the estimated distance while still being +# admissible. + + +def h_manhattan(puzzle: EightPuzzle) -> Union[int, float]: + return heur(puzzle, lambda r, tr, c, tc: abs(tr - r) + abs(tc - c), lambda t: t) + + +def h_manhattan_lsq(puzzle: EightPuzzle) -> Union[int, float]: + return heur( + puzzle, + lambda r, tr, c, tc: (abs(tr - r) + abs(tc - c)) ** 2, + lambda t: sqrt(t), + ) + + +def h_linear(puzzle: EightPuzzle) -> Union[int, float]: + return heur( + puzzle, + lambda r, tr, c, tc: sqrt(sqrt((tr - r) ** 2 + (tc - c) ** 2)), + lambda t: t, + ) + + +def h_linear_lsq(puzzle: EightPuzzle) -> Union[int, float]: + return heur( + puzzle, lambda r, tr, c, tc: (tr - r) ** 2 + (tc - c) ** 2, lambda t: sqrt(t), + ) + + +def solve_8_puzzle(board: List[List[int]]) -> None: + transformed_board = [[elem if elem else 0 for elem in row] for row in board] + p = EightPuzzle(transformed_board) + print(p) + + path, count = p.solve(h_manhattan) + path.reverse() + for i in path: + print(i) + + print("Solved with Manhattan distance exploring", count, "states") + path, count = p.solve(h_manhattan_lsq) + print("Solved with Manhattan least squares exploring", count, "states") + path, count = p.solve(h_linear) + print("Solved with linear distance exploring", count, "states") + path, count = p.solve(h_linear_lsq) + print("Solved with linear least squares exploring", count, "states") + + +if __name__ == "__main__": + board = [[4, 1, 2], [7, 5, 3], [None, 8, 6]] + solve_8_puzzle(board) diff --git a/Solutions/321.py b/Solutions/321.py new file mode 100644 index 0000000..1fc8ac9 --- /dev/null +++ b/Solutions/321.py @@ -0,0 +1,53 @@ +""" +Problem: + +Given a positive integer N, find the smallest number of steps it will take to reach 1. + +There are two kinds of permitted steps: + +You may decrement N to N - 1. +If a * b = N, you may decrement N to the larger of a and b. +For example, given 100, you can reach 1 in five steps with the following route: +100 -> 10 -> 9 -> 3 -> 2 -> 1. +""" + + +from typing import Tuple + + +def get_closest_factors(num: int) -> Tuple[int, int]: + a, b = 1, num + factor_1, factor_2 = 1, 1 + while b > a: + if num % a == 0: + factor_1, factor_2 = a, num // a + b = num / a + a += 1 + return (factor_1, factor_2) + + +def get_step_size(num: int, steps: int = 0) -> int: + if num < 1: + raise ValueError(f"Cannot reach 1 from {num}") + if num == 1: + return steps + # generating the sequence to get the least number of steps + largest_factor = max(get_closest_factors(num)) + if largest_factor == num: + return get_step_size(num - 1, steps + 1) + return min( + get_step_size(num - 1, steps + 1), get_step_size(largest_factor, steps + 1) + ) + + +if __name__ == "__main__": + print(get_step_size(100)) # 100 -> 10 -> 9 -> 3 -> 2 -> 1 + print(get_step_size(64)) # 64 -> 8 -> 4 -> 2 -> 1 + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) [considering call-stack] +""" diff --git a/Solutions/322.py b/Solutions/322.py new file mode 100644 index 0000000..8528088 --- /dev/null +++ b/Solutions/322.py @@ -0,0 +1,44 @@ +""" +Problem: + +Starting from 0 on a number line, you would like to make a series of jumps that lead +to the integer N. + +On the ith jump, you may move exactly i places to the left or right. + +Find a path with the fewest number of jumps required to get from 0 to N. +""" + + +def get_sum_till_n(n: int) -> int: + return (n * (n + 1)) // 2 + + +def count_jumps(n: int) -> int: + # answer will be same either it is positive or negative + n = abs(n) + ans = 0 + # continue till number is lesser or not in same parity + while get_sum_till_n(ans) < n or (get_sum_till_n(ans) - n) & 1: + ans += 1 + return ans + + +if __name__ == "__main__": + print(count_jumps(-3)) + print(count_jumps(0)) + print(count_jumps(1)) + print(count_jumps(2)) + print(count_jumps(3)) + print(count_jumps(4)) + print(count_jumps(5)) + print(count_jumps(9)) + print(count_jumps(10)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/323.py b/Solutions/323.py new file mode 100644 index 0000000..0facd6b --- /dev/null +++ b/Solutions/323.py @@ -0,0 +1,42 @@ +""" +Problem: + +Create an algorithm to efficiently compute the approximate median of a list of numbers. + +More precisely, given an unordered list of N numbers, find an element whose rank is +between N / 4 and 3 * N / 4, with a high level of certainty, in less than O(N) time. +""" + +# checkout the following link for complexity analysis: +# https://www.geeksforgeeks.org/randomized-algorithms-set-3-12-approximate-median/ + +from math import log10 +from random import randint +from typing import List + + +def get_approx_median(arr: List[int]) -> int: + length = len(arr) + elements = min(int(10 * log10(length)), length) + unique_elems = set() + # selecting random log(n) * 10 elements + for _ in range(elements): + unique_elems.add(arr[randint(0, length - 1)]) + # getting the median of the selected elements + sorted_unique_elems = sorted(list(unique_elems)) + return sorted_unique_elems[len(sorted_unique_elems) // 2] + + +if __name__ == "__main__": + print( + get_approx_median( + [3, 4, 3, 2, 4, 3, 1, 4, 3, 4, 2, 3, 4, 3, 0, 4, 0, 0, 1, 1, 0, 1, 2] + ) + ) + print(get_approx_median([1, 3, 2, 4, 5, 6, 8, 7])) + + +""" +Time: O(log(n) x log(log(n))) +Space: O(log(n)) +""" diff --git a/Solutions/325.py b/Solutions/325.py new file mode 100644 index 0000000..fb2c10e --- /dev/null +++ b/Solutions/325.py @@ -0,0 +1,67 @@ +""" +Problem: + +The United States uses the imperial system of weights and measures, which means that +there are many different, seemingly arbitrary units to measure distance. There are 12 +inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on. + +Create a data structure that can efficiently convert a certain quantity of one unit to +the correct amount of any other unit. You should also allow for additional units to be +added to the system. +""" + +from typing import Union + + +class UnitConverter: + def __init__(self) -> None: + # default available metrics + self.metrics = { + "inch": 1, + "foot": 1 * 12, + "yard": 3 * 1 * 12, + "chain": 22 * 3 * 1 * 12, + } + + def add_unit( + self, new_unit: str, available_unit: str, value: Union[int, float] + ) -> None: + # add a new unit with respect to an unit already present + if available_unit not in self.metrics: + raise ValueError(f"Unit not found: {available_unit}") + self.metrics[new_unit] = self.metrics[available_unit] * value + + def convert( + self, + source_unit: str, + result_unit: str, + value: Union[int, float], + precision: int = 4, + ) -> float: + # convert one metric to another, rounds off the result to required decimal + # places + if source_unit not in self.metrics: + raise ValueError(f"Unit not found: {source_unit}") + if result_unit not in self.metrics: + raise ValueError(f"Unit not found: {result_unit}") + return round( + value * self.metrics[source_unit] / self.metrics[result_unit], precision + ) + + +if __name__ == "__main__": + uc = UnitConverter() + print(uc.convert("inch", "foot", 24)) + print(uc.convert("inch", "yard", 36)) + + uc.add_unit("furlong", "chain", 10) + + print(uc.convert("inch", "furlong", 4 * 36 * 22 * 10)) + print(uc.convert("foot", "yard", 4)) + print(uc.convert("chain", "inch", 2)) + print(uc.convert("chain", "foot", 3)) + + # NOTE: "centimeter" is not a part of imperial system, its used to show that + # smaller units works too + uc.add_unit("centimeter", "inch", 0.394) + print(uc.convert("centimeter", "foot", 1)) diff --git a/Solutions/326.py b/Solutions/326.py new file mode 100644 index 0000000..74970fe --- /dev/null +++ b/Solutions/326.py @@ -0,0 +1,58 @@ +""" +Problem: + +A Cartesian tree with sequence S is a binary tree defined by the following two +properties: + +It is heap-ordered, so that each parent value is strictly less than that of its +children. An in-order traversal of the tree produces nodes with values that correspond +exactly to S. For example, given the sequence [3, 2, 6, 1, 9], the resulting Cartesian +tree would be: + + 1 + / \ + 2 9 + / \ +3 6 +Given a sequence S, construct the corresponding Cartesian tree. +""" + +from typing import List, Optional + +from DataStructures.Tree import Node, BinaryTree + + +def generate_cartesian_tree_helper( + arr: List[int], last: Optional[Node] = None, root: Optional[Node] = None +) -> Node: + if not arr: + return root + # Cartesian tree generation + node = Node(arr[0]) + if not last: + # root of the tree + return generate_cartesian_tree_helper(arr[1:], node, node) + if last.val > node.val: + # property of Cartesian tree + node.left = last + return generate_cartesian_tree_helper(arr[1:], node, node) + last.right = node + return generate_cartesian_tree_helper(arr[1:], last, last) + + +def generate_cartesian_tree(sequence: List[int]) -> BinaryTree: + tree = BinaryTree() + tree.root = generate_cartesian_tree_helper(sequence) + return tree + + +if __name__ == "__main__": + print(generate_cartesian_tree([3, 2, 6, 1, 9])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/327.py b/Solutions/327.py new file mode 100644 index 0000000..d715513 --- /dev/null +++ b/Solutions/327.py @@ -0,0 +1,83 @@ +""" +Problem: + +Write a program to merge two binary trees. Each node in the new tree should hold a +value equal to the sum of the values of the corresponding nodes of the input trees. + +If only one input tree has a node in a given position, the corresponding node in the +new tree should match that input node. +""" + +from DataStructures.Tree import BinaryTree, Node + + +def merge_trees_helper(node: Node, node1: Node, node2: Node) -> None: + n1_l_val, n1_r_val = 0, 0 + n2_l_val, n2_r_val = 0, 0 + n1_l, n1_r = None, None + n2_l, n2_r = None, None + # tree1 node related data generation + if node1: + if node1.left: + n1_l_val = node1.left.val + n1_l = node1.left + if node1.right: + n1_r_val = node1.right.val + n1_r = node1.right + # tree2 node related data generation + if node2: + if node2.left: + n2_l_val = node2.left.val + n2_l = node2.left + if node2.right: + n2_r_val = node2.right.val + n2_r = node2.right + # left node generation + if n1_l is not None or n2_l is not None: + node.left = Node(n1_l_val + n2_l_val) + merge_trees_helper(node.left, n1_l, n2_l) + # right node generation + if n1_r is not None or n2_r is not None: + node.right = Node(n1_r_val + n2_r_val) + merge_trees_helper(node.right, n1_r, n2_r) + + +def merge_trees(tree1: BinaryTree, tree2: BinaryTree) -> BinaryTree: + tree = BinaryTree() + if not tree1.root and not tree2.root: + return tree + # root generation + r1, r2 = 0, 0 + if tree1.root: + r1 = tree1.root.val + if tree2.root: + r2 = tree2.root.val + tree.root = Node(r1 + r2) + # generating rest of the tree + merge_trees_helper(tree.root, tree1.root, tree2.root) + return tree + + +if __name__ == "__main__": + tree1 = BinaryTree() + tree1.root = Node(1) + tree1.root.left = Node(2) + tree1.root.right = Node(3) + tree1.root.left.right = Node(4) + print(tree1) + + tree2 = BinaryTree() + tree2.root = Node(2) + tree2.root.right = Node(-3) + tree2.root.right.right = Node(10) + print(tree2) + + print(merge_trees(tree1, tree2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(nodes_tree1 + nodes_tree2) +SPACE COMPLEXITY: O(height_tree1 + height_tree2) +""" diff --git a/Solutions/328.py b/Solutions/328.py new file mode 100644 index 0000000..74170e2 --- /dev/null +++ b/Solutions/328.py @@ -0,0 +1,81 @@ +""" +Problem: + +In chess, the Elo rating system is used to calculate player strengths based on game +results. + +A simplified description of the Elo system is as follows. Every player begins at the +same score. For each subsequent game, the loser transfers some points to the winner, +where the amount of points transferred depends on how unlikely the win is. For example, +a 1200-ranked player should gain much more points for beating a 2000-ranked player than +for beating a 1300-ranked player. + +Implement this system. +""" + +from typing import Optional + + +class EloRating: + INITIAL_POINTS = 1400 + MEAN_SCORE_CHANGE = 30 + + def __init__(self) -> None: + self.scores = {} + + def add_player(self, id: int) -> None: + self.scores[id] = EloRating.INITIAL_POINTS + + def update_points( + self, p1_id: int, p2_id: int, winner: Optional[int] = None + ) -> None: + if p1_id not in self.scores or p2_id not in self.scores: + raise ValueError("Player not found") + if winner is None: + return + temp = set([p1_id, p2_id]) - set([winner]) + if len(temp) != 1: + raise ValueError("Invalid player & winner combination") + # updating points + loser = temp.pop() + if self.scores[loser] > 0: + ratio = self.scores[loser] / self.scores[winner] + # lock to ensure there is no negative points + points = min(self.scores[loser], int(ratio * EloRating.MEAN_SCORE_CHANGE)) + self.scores[winner] += points + self.scores[loser] -= points + + def display_points(self) -> None: + print("\n" + "=" * 15) + print("POINTS") + print("=" * 15) + for player in self.scores: + print(f"{player}\t{self.scores[player]}") + print("=" * 15) + + +if __name__ == "__main__": + elo = EloRating() + + elo.add_player(1) + elo.add_player(2) + elo.add_player(3) + + elo.display_points() + + elo.update_points(1, 2, 1) + elo.update_points(1, 3, 1) + + elo.display_points() + + elo.update_points(1, 2, 1) + + elo.display_points() + + elo.update_points(3, 2, 3) + + elo.display_points() + + elo.update_points(3, 2) # TIE + + elo.display_points() diff --git a/Solutions/330.py b/Solutions/330.py new file mode 100644 index 0000000..4ac4fb3 --- /dev/null +++ b/Solutions/330.py @@ -0,0 +1,76 @@ +""" +Problem: + +A Boolean formula can be said to be satisfiable if there is a way to assign truth +values to each variable such that the entire formula evaluates to true. + +For example, suppose we have the following formula, where the symbol ¬ is used to +denote negation: + +(¬c OR b) AND (b OR c) AND (¬b OR c) AND (¬c OR ¬a) +One way to satisfy this formula would be to let a = False, b = True, and c = True. + +This type of formula, with AND statements joining tuples containing exactly one OR, is +known as 2-CNF. + +Given a 2-CNF formula, find a way to assign truth values to satisfy it, or return False +if this is impossible. +""" + +from typing import Dict, List, Union + + +def generate_combinations(num: int) -> List[List[bool]]: + # generate all boolean combinations for the given number of variables + numbers = [num for num in range(pow(2, num))] + combinations = [] + for number in numbers: + bin_number = bin(number)[2:].zfill(num) + combinations.append(list(bool(int(i)) for i in bin_number)) + return combinations + + +def validation_problem(expression: str) -> Union[Dict[str, bool], bool]: + # getting the variables + formatted_expression = "" + variables = {} + for index, char in enumerate(expression): + formatted_expression += char.lower() + if char.isalpha() and char not in "OR AND": + if char not in variables: + variables[char] = set() + variables[char].add(index) + # generating all combinations for the given variables + variables_set = set(variables.keys()) + variables_list = list(variables_set) + variables_count = len(variables_list) + combinations = generate_combinations(variables_count) + # checking expression satisfiablity using all combinations + for combination in combinations: + calulation_expression = "" + for index, char in enumerate(formatted_expression): + if char == "¬": + calulation_expression += "not " + elif char in variables_set and index in variables[char]: + position = variables_list.index(char) + calulation_expression += str(combination[position]) + else: + calulation_expression += char + if eval(calulation_expression): + return {key: value for key, value in zip(variables_list, combination)} + # returning False if the expression cannot be satisfied + return False + + +if __name__ == "__main__": + print(validation_problem("(¬c OR b) AND (b OR c) AND (¬b OR c) AND (¬c OR ¬a)")) + print(validation_problem("a AND a")) + print(validation_problem("a AND ¬a")) + + +""" +SPECS: + +TIME COMPLEXITY: O(length x (2 ^ variables)) +SPACE COMPLEXITY: O(2 ^ variables) +""" diff --git a/Solutions/331.py b/Solutions/331.py new file mode 100644 index 0000000..e005872 --- /dev/null +++ b/Solutions/331.py @@ -0,0 +1,51 @@ +""" +Problem: + +You are given a string consisting of the letters x and y, such as xyxxxyxyy. In +addition, you have an operation called flip, which changes a single x to y or vice +versa. + +Determine how many times you would need to apply this operation to ensure that all x's +come before all y's. In the preceding example, it suffices to flip the second and sixth +characters, so you should return 2. +""" + +from sys import maxsize + + +def get_minimum_flips(string: str) -> int: + length = len(string) + # lookup table for dp + flips_from_left = [0 for i in range(length)] + flips_from_right = [0 for i in range(length)] + # updating flips from left + flips = 0 + for i in range(length): + if string[i] == "y": + flips = flips + 1 + flips_from_left[i] = flips + # updating flips from right + flips = 0 + for i in range(length - 1, -1, -1): + if string[i] == "x": + flips = flips + 1 + flips_from_right[i] = flips + # generating the minimum number of flips (using minimum flips is the minimum flips + # on the left + minimum flips on the right) + minFlips = maxsize + for i in range(1, length): + minFlips = min(minFlips, flips_from_left[i - 1] + flips_from_right[i]) + return minFlips + + +if __name__ == "__main__": + print(get_minimum_flips("xyxxxyxyy")) + print(get_minimum_flips("xyxxxyxxxxxxxxxxxyyyyyyyyyyyyyyyx")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/332.py b/Solutions/332.py new file mode 100644 index 0000000..8ea7968 --- /dev/null +++ b/Solutions/332.py @@ -0,0 +1,31 @@ +""" +Problem: + +Given integers M and N, write a program that counts how many positive integer pairs +(a, b) satisfy the following conditions: + +a + b = M +a XOR b = N +""" + + +def get_count(M: int, N: int) -> int: + count = 0 + for i in range(1, M): + # (a, b) and (b, a) are considered different entities. + # To consider them only once, use range(1, M // 2) + if i ^ (M - i) == N: + count += 1 + return count + + +if __name__ == "__main__": + print(get_count(100, 4)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/333.py b/Solutions/333.py new file mode 100644 index 0000000..3671ee8 --- /dev/null +++ b/Solutions/333.py @@ -0,0 +1,56 @@ +""" +Problem: + +At a party, there is a single person who everyone knows, but who does not know anyone +in return (the "celebrity"). To help figure out who this is, you have access to an O(1) +method called knows(a, b), which returns True if person a knows person b, else False. + +Given a list of N people and the above operation, find a way to identify the celebrity +in O(N) time. +""" + +from typing import Dict, Set + + +class Party: + def __init__(self, people: Dict[str, Set[str]]) -> None: + self.people = people + + def knows(self, a: str, b: str) -> bool: + # function to check if a knows b [runs in O(1)] + return b in self.people[a] + + def get_celebrity(self) -> str: + # runs in O(v + e) time & space (e = the maximum people a person knows, + # v = number of people) + celebrity_candidates = {} + for person in self.people: + if celebrity_candidates == {}: + # getting potential celebrities if the celebrity candidates is empty + # the values are filled with people the 1st person knows who doesn't + # know him (celebrity candidates will contain all popular people + # including the celebrity) + for person2 in self.people[person]: + if not self.knows(person2, person): + celebrity_candidates[person2] = 1 + continue + # checking for the person known by most people in case there is other + # popular people + for potential_celebrity in celebrity_candidates: + if potential_celebrity in self.people[person]: + celebrity_candidates[potential_celebrity] += 1 + return max( + celebrity_candidates.keys(), + key=lambda candidate: celebrity_candidates[candidate], + ) + + +if __name__ == "__main__": + people = { + "a": {"b"}, # popular person (but not the celebrity) + "b": set(), # celebrity + "c": {"a", "b", "d"}, + "d": {"a", "b"}, + } + party = Party(people) + print(party.get_celebrity()) diff --git a/Solutions/334.py b/Solutions/334.py new file mode 100644 index 0000000..2a34ffd --- /dev/null +++ b/Solutions/334.py @@ -0,0 +1,54 @@ +""" +Problem: + +The 24 game is played as follows. You are given a list of four integers, each between 1 +and 9, in a fixed order. By placing the operators +, -, *, and / between the numbers, +and grouping them with parentheses, determine whether it is possible to reach the value +24. + +For example, given the input [5, 2, 7, 8], you should return True, since +(5 * 2 - 7) * 8 = 24. + +Write a function that plays the 24 game. +""" + +from typing import List + +OPERATORS = set(["+", "-", "*", "/"]) + + +def game_24(arr: List[int]) -> bool: + if len(arr) == 1: + return arr[0] == 24 + # checking if 24 can be reached + possibilities = [] + for si in range(len(arr) - 1): + # checking all possibilities + for operator in OPERATORS: + num_1 = arr[si] + num_2 = arr[si + 1] + try: + possibility = ( + arr[:si] + + [eval("{} {} {}".format(num_1, operator, num_2))] + + arr[si + 2 :] + ) + possibilities.append(possibility) + except ZeroDivisionError: + pass + return any([game_24(x) for x in possibilities]) + + +if __name__ == "__main__": + print(game_24([5, 2, 7, 8])) + print(game_24([1, 1, 1, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(operations) +SPACE COMPLEXITY: O(operations) +[the passed array contains 4 (constant) numbers, else it would have been +O(operations x (n ^ n)) in time & space] +""" diff --git a/Solutions/335.py b/Solutions/335.py new file mode 100644 index 0000000..a709f0c --- /dev/null +++ b/Solutions/335.py @@ -0,0 +1,76 @@ +""" +Problem: + +PageRank is an algorithm used by Google to rank the importance of different websites. +While there have been changes over the years, the central idea is to assign each site +a score based on the importance of other pages that link to that page. + +More mathematically, suppose there are N sites, and each site i has a certain count Ci +of outgoing links. Then the score for a particular site Sj is defined as : + +score(Sj) = (1 - d) / N + d * (score(Sx) / Cx+ score(Sy) / Cy+ ... + score(Sz) / Cz)) +Here, Sx, Sy, ..., Sz denote the scores of all the other sites that have outgoing links +to Sj, and d is a damping factor, usually set to around 0.85, used to model the +probability that a user will stop searching. + +Given a directed graph of links between various websites, write a program that +calculates each site's page rank. +""" + +from typing import Dict, List, Union + +from DataStructures.Graph import GraphDirectedUnweighted + +DAMPING_FACTOR = 0.85 + + +def calculate_score( + node: Union[int, str], + graph: GraphDirectedUnweighted, + page_scores: Dict[Union[int, str], float], +) -> float: + # caclulate the page score of the given page + aggregate_score = 0 + for other in graph.connections: + if node in graph.connections[other]: + if page_scores[other] is None: + # considering there is no cyclic dependency + page_scores[other] = calculate_score(other, graph, page_scores) + aggregate_score += page_scores[other] / len(graph.connections[other]) + score = ((1 - DAMPING_FACTOR) / len(graph)) + (DAMPING_FACTOR * aggregate_score) + return round(score, 2) + + +def get_page_rank(graph: GraphDirectedUnweighted) -> List[Union[int, str]]: + page_scores = {node: None for node in graph.connections} + for node in graph.connections: + page_scores[node] = calculate_score(node, graph, page_scores) + # returning the pages sorted in the reverse order of their page scores + return sorted( + [page for page in page_scores], + key=lambda page: page_scores[page], + reverse=True, + ) + + +if __name__ == "__main__": + graph = GraphDirectedUnweighted() + + graph.add_edge("a", "b") + graph.add_edge("a", "c") + + graph.add_edge("b", "c") + + graph.add_edge("d", "a") + graph.add_edge("d", "b") + graph.add_edge("d", "c") + + print(get_page_rank(graph)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/336.py b/Solutions/336.py new file mode 100644 index 0000000..06ae2e3 --- /dev/null +++ b/Solutions/336.py @@ -0,0 +1,81 @@ +""" +Problem: + +Write a program to determine how many distinct ways there are to create a max heap from +a list of N given integers. + +For example, if N = 3, and our integers are [1, 2, 3], there are two ways, shown below. + + 3 3 + / \ / \ +1 2 2 1 +""" + +from math import log2 +from typing import List + + +def choose(n: int, k: int, nCk: List[List[int]]) -> int: + # get nCk using dynamic programming + if k > n: + return 0 + if n <= 1: + return 1 + if k == 0: + return 1 + if nCk[n][k] != -1: + return nCk[n][k] + + answer = choose(n - 1, k - 1, nCk) + choose(n - 1, k, nCk) + nCk[n][k] = answer + return answer + + +def get_nodes_left(n: int) -> int: + if n == 1: + return 0 + h = int(log2(n)) + # max number of elements that can be present in the hth level of any heap + num_h = 1 << h # (2 ^ h) + # number of elements that are actually present in the last level + # [hth level (2 ^ h - 1)] + last = n - ((1 << h) - 1) + if last >= (num_h // 2): + # if more than half of the last level is filled + return (1 << h) - 1 + return (1 << h) - 1 - ((num_h // 2) - last) + + +def number_of_heaps(n: int, dp: List[int], nCk: List[List[int]]) -> int: + if n <= 1: + return 1 + if dp[n] != -1: + return dp[n] + + left = get_nodes_left(n) + ans = ( + choose(n - 1, left, nCk) + * number_of_heaps(left, dp, nCk) + * number_of_heaps(n - 1 - left, dp, nCk) + ) + dp[n] = ans + return ans + + +def get_number_of_heaps(n: int) -> int: + dp = [-1 for _ in range(n + 1)] + nCk = [[-1 for _ in range(n + 1)] for _ in range(n + 1)] + return number_of_heaps(n, dp, nCk) + + +if __name__ == "__main__": + print(get_number_of_heaps(3)) + print(get_number_of_heaps(10)) + + +""" +SPECS: + +TIME COMPLEXITY: O(2 ^ n) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/337.py b/Solutions/337.py new file mode 100644 index 0000000..f95910a --- /dev/null +++ b/Solutions/337.py @@ -0,0 +1,45 @@ +""" +Problem: + +Given a linked list, uniformly shuffle the nodes. What if we want to prioritize space +over time? +""" + +from random import randint + +from DataStructures.LinkedList import LinkedList + + +def shuffle(ll: LinkedList) -> LinkedList: + length = len(ll) + if length in (0, 1): + return ll + + for _ in range(length): + pos1, pos2 = randint(0, length - 1), randint(0, length - 1) + node1, node2 = ll.head, ll.head + for _ in range(pos1): + node1 = node1.next + for _ in range(pos2): + node2 = node2.next + node1.val, node2.val = node2.val, node1.val + return ll + + +if __name__ == "__main__": + ll = LinkedList() + + for i in range(1, 6): + ll.add(i) + + print(ll) + shuffle(ll) + print(ll) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/338.py b/Solutions/338.py new file mode 100644 index 0000000..4dce3ad --- /dev/null +++ b/Solutions/338.py @@ -0,0 +1,33 @@ +""" +Problem: + +Given an integer n, find the next biggest integer with the same number of 1-bits on. +For example, given the number 6 (0110 in binary), return 9 (1001). +""" + + +def get_set_bits(num: int) -> int: + # get the number of bits set in a number [runs in O(log(n))] + bin_num = bin(num)[2:] + return sum([int(digit) for digit in bin_num]) + + +def get_next_number_with_same_count_of_set_bits(num: int) -> int: + num_of_set_bits = get_set_bits(num) + curr = num + 1 + while True: + if num_of_set_bits == get_set_bits(curr): + return curr + curr += 1 + + +if __name__ == "__main__": + print(get_next_number_with_same_count_of_set_bits(6)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) [as the result always lies between n and 2n] +SPACE COMPLEXITY: O(log(n)) +""" diff --git a/Solutions/339.py b/Solutions/339.py new file mode 100644 index 0000000..c411481 --- /dev/null +++ b/Solutions/339.py @@ -0,0 +1,51 @@ +""" +Problem: + +Given an array of numbers and a number k, determine if there are three entries in the +array which add up to the specified number k. For example, given [20, 303, 3, 4, 25] +and k = 49, return true as 20 + 4 + 25 = 49. +""" + +from typing import List + + +def target_sum_of_two(arr: List[int], k: int, index_1: int, index_2: int) -> bool: + while index_1 < index_2: + elem_1, elem_2 = arr[index_1], arr[index_2] + curr_sum = elem_1 + elem_2 + if curr_sum == k: + return True + elif curr_sum < k: + index_1 += 1 + else: + index_2 -= 1 + return False + + +def target_sum_of_three(arr: List[int], k: int) -> bool: + length = len(arr) + # sorting the array to utilize the optimizations offered by a sorted array to find + # target sum of 2 numbers + arr.sort() + + for index_1, elem in enumerate(arr): + index_2, index_3 = index_1 + 1, length - 1 + if elem >= k: + break + if target_sum_of_two(arr, k - elem, index_2, index_3): + return True + return False + + +if __name__ == "__main__": + print(target_sum_of_three([20, 303, 3, 4, 25], 49)) + print(target_sum_of_three([20, 303, 3, 4, 25], 50)) + print(target_sum_of_three([20, 300, -300, 4, 25], 25)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/340.py b/Solutions/340.py new file mode 100644 index 0000000..659ce64 --- /dev/null +++ b/Solutions/340.py @@ -0,0 +1,48 @@ +""" +Problem: + +Given a set of points (x, y) on a 2D cartesian plane, find the two closest points. For +example, given the points [(1, 1), (-1, -1), (3, 4), (6, 1), (-1, -6), (-4, -3)], +return [(-1, -1), (1, 1)]. +""" + +from math import sqrt +from sys import maxsize +from typing import List, Tuple + + +Point = Tuple[int, int] + + +def get_distance(pt1: Point, pt2: Point) -> float: + x1, y1 = pt1 + x2, y2 = pt2 + dist = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)) + return dist + + +def get_nearest_points(pts_arr: List[Point]) -> List[Point]: + length = len(pts_arr) + dist = maxsize + pt1, pt2 = None, None + + for index_1 in range(length): + for index_2 in range(index_1 + 1, length): + pt1_temp, pt2_temp = pts_arr[index_1], pts_arr[index_2] + dist_temp = get_distance(pt1_temp, pt2_temp) + if dist_temp < dist: + dist = dist_temp + pt1, pt2 = pt1_temp, pt2_temp + return [pt1, pt2] + + +if __name__ == "__main__": + print(get_nearest_points([(1, 1), (-1, -1), (3, 4), (6, 1), (-1, -6), (-4, -3)])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/341.py b/Solutions/341.py new file mode 100644 index 0000000..be88850 --- /dev/null +++ b/Solutions/341.py @@ -0,0 +1,133 @@ +""" +Problem: + +You are given an N by N matrix of random letters and a dictionary of words. Find the +maximum number of words that can be packed on the board from the given dictionary. + +A word is considered to be able to be packed on the board if: + +It can be found in the dictionary +It can be constructed from untaken letters by other words found so far on the board +The letters are adjacent to each other (vertically and horizontally, not diagonally). +Each tile can be visited only once by any word. +For example, given the following dictionary: + +{ 'eat', 'rain', 'in', 'rat' } +and matrix: + +[['e', 'a', 'n'], + ['t', 't', 'i'], + ['a', 'r', 'a']] +Your function should return 3, since we can make the words 'eat', 'in', and 'rat' +without them touching each other. We could have alternatively made 'eat' and 'rain', +but that would be incorrect since that's only 2 words. +""" + +from typing import List, Optional, Set, Tuple, Union + + +def get_neighbours( + pos: Tuple[int, int], dim: Tuple[int, int], seen: Set[int] +) -> List[Tuple[int, int]]: + n, m = dim + i, j = pos + positions = [ + (i - 1, j), + (i + 1, j), + (i, j - 1), + (i, j + 1), + ] + valid_positions = [] + for position in positions: + y, x = position + if (0 <= y < n and 0 <= x < m) and (position not in seen): + valid_positions.append(position) + return valid_positions + + +def can_generate_word( + matrix: List[List[str]], + pos: Tuple[int, int], + word: str, + seen: Set[int], + dim: Tuple[int, int], +) -> Union[bool, Optional[Set[int]]]: + # check if the current word can be generated from the matrix + if word == "": + return True, seen + neighbours = get_neighbours(pos, dim, seen) + for neighbour in neighbours: + i, j = neighbour + if matrix[i][j] == word[0]: + generated, seen_pos = can_generate_word( + matrix, neighbour, word[1:], seen | set([neighbour]), dim + ) + if generated: + return generated, seen_pos + return False, None + + +def get_power_set(words: List[str]) -> List[List[str]]: + # generate the power set of the given list except the empty set + num_of_words = len(words) + accumulator = [] + pow_set_size = pow(2, num_of_words) + + for counter in range(pow_set_size): + temp = [] + for j in range(num_of_words): + if (counter & (1 << j)) > 0: + temp.append(words[j]) + if temp: + # adding only valid sets + accumulator.append(temp) + return accumulator + + +def get_max_packed_helper(matrix: List[List[str]], words: Set[str]) -> int: + n, m = len(matrix), len(matrix[0]) + count = 0 + seen = set() + + for i in range(n): + for j in range(m): + char = matrix[i][j] + for word in words: + if word[0] == char: + # a match has been found, trying to generate the entire word from + # the first character in the matrix + generated, seen_temp = can_generate_word( + matrix, (i, j), word[1:], seen, (n, m) + ) + if generated: + count += 1 + seen = seen_temp + return count + + +def get_max_packed(matrix: List[List[str]], words: Set[str]) -> int: + words_list = get_power_set(list(words)) + max_words = 0 + for word_list in words_list: + max_words = max(max_words, get_max_packed_helper(matrix, word_list)) + return max_words + + +if __name__ == "__main__": + print( + get_max_packed( + [ + ["e", "a", "n"], + ["t", "t", "i"], + ["a", "r", "a"] + ], {"eat", "rain", "in", "rat"}, + ) + ) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x m x words x len(longest word)) +SPACE COMPLEXITY: O(n x m) +""" diff --git a/Solutions/342.py b/Solutions/342.py new file mode 100644 index 0000000..c02a3b7 --- /dev/null +++ b/Solutions/342.py @@ -0,0 +1,51 @@ +""" +Problem: + +reduce (also known as fold) is a function that takes in an array, a combining function, +and an initial value and builds up a result by calling the combining function on each +element of the array, left to right. For example, we can write sum() in terms of +reduce: + +def add(a, b): + return a + b + +def sum(lst): + return reduce(lst, add, 0) + +This should call add on the initial value with the first element of the array, and then +the result of that with the second element of the array, and so on until we reach the +end, when we return the sum of the array. + +Implement your own version of reduce. +""" + +from typing import Any, Callable, Iterable + + +def reduce(iterable: Iterable, func: Callable, initial_value: int) -> int: + value = initial_value + for item in iterable: + value = func(value, item) + return value + + +def add(a: int, b: int) -> int: + return a + b + + +def sum(lst: Iterable) -> int: + return reduce(lst, add, 0) + + +if __name__ == "__main__": + print(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +[for the reduce function only (considering the iterable doesn't contain a nested +iterable)] +""" diff --git a/Solutions/343.py b/Solutions/343.py new file mode 100644 index 0000000..744a236 --- /dev/null +++ b/Solutions/343.py @@ -0,0 +1,62 @@ +""" +Problem: + +Given a binary search tree and a range [a, b] (inclusive), return the sum of the +elements of the binary search tree within the range. + +For example, given the following tree: + + 5 + / \ + 3 8 + / \ / \ +2 4 6 10 +and the range [4, 9], return 23 (5 + 4 + 6 + 8). +""" + +from typing import Tuple + +from DataStructures.Tree import BinarySearchTree, Node + + +def get_sum_over_range_helper(node: Node, low: int, high: int) -> int: + if node is None: + return 0 + if low <= node.val <= high: + return ( + node.val + + get_sum_over_range_helper(node.left, low, high) + + get_sum_over_range_helper(node.right, low, high) + ) + elif low > node.val: + return get_sum_over_range_helper(node.right, low, high) + return get_sum_over_range_helper(node.left, low, high) + + +def get_sum_over_range(tree: BinarySearchTree, sum_range: Tuple[int, int]) -> int: + if tree.root is None: + return 0 + low, high = sum_range + return get_sum_over_range_helper(tree.root, low, high) + + +if __name__ == "__main__": + tree = BinarySearchTree() + + tree.add(5) + tree.add(3) + tree.add(8) + tree.add(2) + tree.add(4) + tree.add(6) + tree.add(10) + + print(get_sum_over_range(tree, (4, 9))) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(height_of_the_tree) [due to recursion] +""" diff --git a/Solutions/344.py b/Solutions/344.py new file mode 100644 index 0000000..178a3d0 --- /dev/null +++ b/Solutions/344.py @@ -0,0 +1,87 @@ +""" +Problem: + +You are given a tree with an even number of nodes. Consider each connection between a +parent and child node to be an "edge". You would like to remove some of these edges, +such that the disconnected subtrees that remain each have an even number of nodes. + +For example, suppose your input was the following tree: + + 1 + / \ + 2 3 + / \ + 4 5 + / | \ +6 7 8 + +In this case, removing the edge (3, 4) satisfies our requirement. + +Write a function that returns the maximum number of edges you can remove while still +satisfying this requirement. +""" + +from __future__ import annotations +from typing import List, Tuple + + +class Node: + def __init__(self, val: int) -> None: + self.val = val + self.children = [] + + def add_children(self, children: List[Node] = []) -> None: + self.children = [*children] + + +class Tree: + def __init__(self) -> None: + self.root = None + + +def get_even_edge_split_helper(node: Node) -> Tuple[int, int]: + nodes_count = 0 + even_splits = 0 + for child in node.children: + child_nodes, child_even_splits = get_even_edge_split_helper(child) + nodes_count += child_nodes + even_splits += child_even_splits + if child_nodes != 0 and child_nodes % 2 == 0: + even_splits += 1 + return nodes_count + 1, even_splits + + +def get_even_edge_split(tree: Tree) -> int: + if tree.root: + _, result = get_even_edge_split_helper(tree.root) + return result + return 0 + + +if __name__ == "__main__": + tree = Tree() + + a = Node(1) + b = Node(2) + c = Node(3) + d = Node(4) + e = Node(5) + f = Node(6) + g = Node(7) + h = Node(8) + + a.add_children([b, c]) + c.add_children([d, e]) + d.add_children([f, g, h]) + + tree.root = a + + print(get_even_edge_split(tree)) # possible splits at (1, 3) and (3, 4) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/345.py b/Solutions/345.py new file mode 100644 index 0000000..25a318d --- /dev/null +++ b/Solutions/345.py @@ -0,0 +1,71 @@ +""" +Problem: + +You are given a set of synonyms, such as (big, large) and (eat, consume). Using this +set, determine if two sentences with the same number of words are equivalent. + +For example, the following two sentences are equivalent: + +"He wants to eat food." +"He wants to consume food." +Note that the synonyms (a, b) and (a, c) do not necessarily imply (b, c): consider the +case of (coach, bus) and (coach, teacher). + +Follow-up: what if we can assume that (a, b) and (a, c) do in fact imply (b, c)? +""" + +from typing import List, Tuple, Union + +from DataStructures.Graph import GraphUndirectedUnweighted + + +def generate_graph(synonyms: List[Tuple[str, str]]) -> GraphUndirectedUnweighted: + graph = GraphUndirectedUnweighted() + for word_1, word_2 in synonyms: + graph.add_edge(word_1, word_2) + return graph + + +def check_equivalence( + sentence_1: str, sentence_2: str, synonyms: List[Tuple[str, str]] +) -> bool: + graph = generate_graph(synonyms) + word_list_1 = sentence_1.strip().split() + word_list_2 = [word for word in word_list_1] + + if len(word_list_1) != len(word_list_2): + return False + for word_1, word_2 in zip(word_list_1, word_list_2): + if word_1 != word_2: + if word_1 not in graph.connections or word_2 not in graph.connections: + return False + if word_2 not in graph.connections[word_1]: + return False + return True + + +if __name__ == "__main__": + print( + check_equivalence( + "He wants to eat food.", "He wants to consume food.", [("eat", "consume")] + ) + ) + print( + check_equivalence( + "He is waiting for the bus.", + "He is waiting for the teacher.", + [("coach", "bus"), ("coach", "teacher")], + ) + ) + +# if we can assume that (a, b) and (a, c) do in fact imply (b, c), then for each word, +# we would have to run a dfs/bfs to get all words similar to any given word, instead of +# simply comparing: 'word_2 not in graph.connections[word_1]' + + +""" +SPECS: + +TIME COMPLEXITY: O(characters) +SPACE COMPLEXITY: O(words ^ 2) +""" diff --git a/Solutions/346.py b/Solutions/346.py new file mode 100644 index 0000000..cedc87d --- /dev/null +++ b/Solutions/346.py @@ -0,0 +1,102 @@ +""" +Problem: + +You are given a huge list of airline ticket prices between different cities around the +world on a given day. These are all direct flights. Each element in the list has the +format (source_city, destination, price). + +Consider a user who is willing to take up to k connections from their origin city A to +their destination B. Find the cheapest fare possible for this journey and print the +itinerary for that journey. + +For example, our traveler wants to go from JFK to LAX with up to 3 connections, and our +input flights are as follows: + +[ + ('JFK', 'ATL', 150), + ('ATL', 'SFO', 400), + ('ORD', 'LAX', 200), + ('LAX', 'DFW', 80), + ('JFK', 'HKG', 800), + ('ATL', 'ORD', 90), + ('JFK', 'LAX', 500), +] +Due to some improbably low flight prices, the cheapest itinerary would be +JFK -> ATL -> ORD -> LAX, costing $440. +""" + +from sys import maxsize +from typing import Dict, List, Optional, Tuple + +from DataStructures.Graph import GraphDirectedWeighted +from DataStructures.PriorityQueue import MinPriorityQueue + + +def modified_dijkstra( + graph: GraphDirectedWeighted, start: str, k: int +) -> Tuple[Dict[str, int], Dict[str, Optional[str]]]: + dist = {node: maxsize for node in graph.connections} + parent = {node: None for node in graph.connections} + dist[start] = 0 + priority_queue = MinPriorityQueue() + [priority_queue.push(node, weight) for node, weight in dist.items()] + + while not priority_queue.is_empty(): + node = priority_queue.extract_min() + ancestors = 0 + parent_node = parent[node] + # calculating ancestors + while parent_node: + ancestors += 1 + parent_node = parent[parent_node] + # limiting distance update till k moves + if ancestors <= k: + for neighbour in graph.connections[node]: + if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: + dist[neighbour] = dist[node] + graph.connections[node][neighbour] + parent[neighbour] = node + priority_queue.update_key(neighbour, dist[neighbour]) + return dist, parent + + +def generate_path( + flights: List[Tuple[str, str, int]], start: str, dest: str, k: int +) -> Tuple[int, List[str]]: + # graph generation + graph = GraphDirectedWeighted() + for src, dest, wt in flights: + graph.add_edge(src, dest, wt) + # running dijkstra's algorithm + dist, parent = modified_dijkstra(graph, start, k) + # getting the cost and path + if not parent[dest]: + return [] + path, cost = [dest], dist[dest] + curr = parent[dest] + while curr: + path.append(curr) + curr = parent[curr] + return cost, path[::-1] + + +if __name__ == "__main__": + flights = [ + ("JFK", "ATL", 150), + ("ATL", "SFO", 400), + ("ORD", "LAX", 200), + ("LAX", "DFW", 80), + ("JFK", "HKG", 800), + ("ATL", "ORD", 90), + ("JFK", "LAX", 500), + ] + print(generate_path(flights, "JFK", "LAX", 3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(e x v x log(v)) +SPACE COMPLEXITY: O(v ^ 2) +[even though dijkstra's algorithm runs in O(e x log(v)) to lock maximum k moves, the +compleity increases to O(e x v x log(v))] +""" diff --git a/Solutions/347.py b/Solutions/347.py new file mode 100644 index 0000000..d750a8e --- /dev/null +++ b/Solutions/347.py @@ -0,0 +1,43 @@ +""" +Problem: + +You are given a string of length N and a parameter k. The string can be manipulated by +taking one of the first k letters and moving it to the end. + +Write a program to determine the lexicographically smallest string that can be created +after an unlimited number of moves. + +For example, suppose we are given the string daily and k = 1. The best we can create in +this case is ailyd. +""" + + +def generate_next(string: str, k: int) -> str: + return string[k:] + string[:k] + + +def get_lexicographically_smallest_string(string: str, k: int) -> str: + seen = set() + result = string + curr = generate_next(string, k) + + while curr not in seen: + result = min(result, curr) + seen.add(curr) + curr = generate_next(curr, k) + return result + + +if __name__ == "__main__": + print(get_lexicographically_smallest_string("daily", 1)) + print(get_lexicographically_smallest_string("salloo", 2)) + # unlimited number of moves allowed (so the word of length 5 and k = 2 goes round) + print(get_lexicographically_smallest_string("daily", 2)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 2) +SPACE COMPLEXITY: O(n ^ 2) +""" diff --git a/Solutions/348.py b/Solutions/348.py new file mode 100644 index 0000000..52f4721 --- /dev/null +++ b/Solutions/348.py @@ -0,0 +1,127 @@ +""" +Problem: + +A ternary search tree is a trie-like data structure where each node may have up to +three children. Here is an example which represents the words code, cob, be, ax, war +and we. + + c + / | \ + b o w + / | | | +a e d a +| / | | \ +x b e r e +The tree is structured according to the following rules: + +left child nodes link to words lexicographically earlier than the parent prefix +right child nodes link to words lexicographically later than the parent prefix +middle child nodes continue the current word +For instance, since code is the first word inserted in the tree, and cob +lexicographically precedes cod, cob is represented as a left child extending from cod. + +Implement insertion and search functions for a ternary search tree. +""" + +from random import shuffle, random +from typing import Optional + + +class Node: + def __init__(self, val: Optional[str] = None) -> None: + self.val = val + self.left = None + self.mid = None + self.right = None + + def __bool__(self) -> bool: + return bool(self.val) + + def insert_helper(self, string: str) -> None: + if not string: + return + + if self.left is None: + self.left = Node() + if self.mid is None: + self.mid = Node() + if self.right is None: + self.right = Node() + + char = string[0] + if not self: + self.val = char + self.mid.insert_helper(string[1:]) + if self.val == char: + self.mid.insert_helper(string[1:]) + elif self.val > char: + self.left.insert_helper(string) + else: + self.right.insert_helper(string) + + def search_helper(self, string: str) -> bool: + if not string: + return True + + char = string[0] + length = len(string) + if char == self.val: + if self.mid: + return self.mid.search_helper(string[1:]) + elif length == 1: + return True + return False + elif char < self.val: + if self.left: + return self.left.search_helper(string) + return False + else: + if self.right: + return self.right.search_helper(string) + return False + + +class TernarySearchTree: + def __init__(self) -> None: + self.root = None + + def insert(self, string: str) -> None: + if not string: + return + if not self.root: + self.root = Node(string[0]) + string = string[1:] + curr = self.root + for char in string: + curr.mid = Node(char) + curr = curr.mid + else: + self.root.insert_helper(string) + + def search(self, string: str) -> bool: + if not string: + return True + if not self.root: + return False + return self.root.search_helper(string) + + +if __name__ == "__main__": + words_present = ["ax", "be", "cob", "code", "war", "we"] + words_absent = ["axe", "bee", "creed", "hi", "see", "wax"] + + chosen_words = words_absent + words_present + shuffle(chosen_words) + chosen_words = [word for word in chosen_words if random() > 0.5] + shuffle(chosen_words) + + tree = TernarySearchTree() + + for word in words_present: + tree.insert(word) + + for word in chosen_words: + if tree.search(word): + print(f"'{word}' is PRESENT in the tree") + else: + print(f"'{word}' is NOT PRESENT in the tree") diff --git a/Solutions/349.py b/Solutions/349.py new file mode 100644 index 0000000..fa7eb90 --- /dev/null +++ b/Solutions/349.py @@ -0,0 +1,80 @@ +""" +Problem: + +Soundex is an algorithm used to categorize phonetically, such that two names that sound +alike but are spelled differently have the same representation. + +Soundex maps every name to a string consisting of one letter and three numbers, like +M460. + +One version of the algorithm is as follows: + +Remove consecutive consonants with the same sound (for example, change ck -> c). +Keep the first letter. The remaining steps only apply to the rest of the string. +Remove all vowels, including y, w, and h. +Replace all consonants with the following digits: +b, f, p, v -> 1 +c, g, j, k, q, s, x, z -> 2 +d, t -> 3 +l -> 4 +m, n -> 5 +r -> 6 +If you don't have three numbers yet, append zeros until you do. Keep the first three +numbers. Using this scheme, Jackson and Jaxen both map to J250. +""" + +IRRELEVANT_CHAR = {"a", "e", "i", "o", "u", "y", "w", "h"} +SIMILAR_SOUND_MAP = {"c": {"k", "s"}, "k": {"c"}, "s": {"c"}} +CHAR_DIGIT_MAP = { + "b": "1", + "f": "1", + "p": "1", + "v": "1", + "c": "2", + "g": "2", + "j": "2", + "k": "2", + "q": "2", + "s": "2", + "x": "2", + "z": "2", + "d": "3", + "t": "3", + "l": "4", + "m": "5", + "n": "5", + "r": "6", +} + + +def soundex(word: str) -> str: + # removing irrelevant characters from the word + word = "".join([char for char in word.lower() if char not in IRRELEVANT_CHAR]) + last_char = word[0] + transformed_word = last_char + soundex_map = "" + # eliminating similar sounding characters + for char in word[1:]: + if char in SIMILAR_SOUND_MAP: + if last_char in SIMILAR_SOUND_MAP[char]: + continue + transformed_word += char + last_char = char + # generating soundex + soundex_map = transformed_word[0].upper() + for char in transformed_word[1:]: + soundex_map += CHAR_DIGIT_MAP[char] + return soundex_map + "0" * (4 - len(soundex_map)) + + +if __name__ == "__main__": + print(soundex("Jackson")) + print(soundex("Jaxen")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/350.py b/Solutions/350.py new file mode 100644 index 0000000..9a9d632 --- /dev/null +++ b/Solutions/350.py @@ -0,0 +1,40 @@ +""" +Problem: + +Write a program that determines the smallest number of perfect squares that sum up to +N. + +Here are a few examples: + +Given N = 4, return 1 (4) +Given N = 17, return 2 (16 + 1) +Given N = 18, return 2 (9 + 9) +""" + +from math import ceil, sqrt + + +def get_min_squares_sum(N: int) -> int: + dp = [0, 1, 2, 3] + for i in range(4, N + 1): + dp.append(i) + for x in range(1, int(ceil(sqrt(i))) + 1): + square = pow(x, 2) + if square > i: + break + dp[i] = min(dp[i], 1 + dp[i - square]) + return dp[N] + + +if __name__ == "__main__": + print(get_min_squares_sum(4)) + print(get_min_squares_sum(17)) + print(get_min_squares_sum(18)) + + +""" +SPECS: + +TIME COMPLEXITY: O(n ^ 1.5) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/351.py b/Solutions/351.py new file mode 100644 index 0000000..e738a8d --- /dev/null +++ b/Solutions/351.py @@ -0,0 +1,71 @@ +""" +Problem: + +Word sense disambiguation is the problem of determining which sense a word takes on in +a particular setting, if that word has multiple meanings. For example, in the sentence +"I went to get money from the bank", bank probably means the place where people deposit +money, not the land beside a river or lake. + +Suppose you are given a list of meanings for several words, formatted like so: + +{ + "word_1": ["meaning one", "meaning two", ...], + ... + "word_n": ["meaning one", "meaning two", ...] +} +Given a sentence, most of whose words are contained in the meaning list above, create +an algorithm that determines the likely sense of each possibly ambiguous word. +""" + +from typing import Dict, List + + +def get_meaning( + sentence: str, meaning_map: Dict[str, List[str]] +) -> Dict[str, List[str]]: + # this is NOT a fool-proof solution + # the problem is incomplete + words = sentence.split() + words_set = set(words) + # selecting the words with multiple meanings + ambiguous_words = [ + word for word in words if word in meaning_map and len(meaning_map[word]) > 1 + ] + possible_context_meaning_map = {} + # generating the possible meaning of the words in the given context + for word in ambiguous_words: + for meaning in meaning_map[word]: + for meaning_word in meaning.split(): + if meaning_word in words_set: + if word not in possible_context_meaning_map: + possible_context_meaning_map[word] = [] + possible_context_meaning_map[word].append(meaning) + break + return possible_context_meaning_map + + +if __name__ == "__main__": + sentence = "I went to get money from the bank" + meaning_map = { + "bank": ["place where people deposit money", "land beside a river or lake"], + "get": ["acquire something"], + "money": ["medium of exchange"], + "went": ["to go (past)"], + } + print(get_meaning(sentence, meaning_map)) + + +""" +SPECS: + +TIME COMPLEXITY: O(sentence x meaning_map x meaning_words) +SPACE COMPLEXITY: O(sentence x meaning_map) +""" + +# NOTE: The problem is incomplete. +# We also need a source for which word appears in which context, to be able to infer +# this in the actual sentences. +# Once we have a set of strongly correlated words with each word-sense, we can search +# the context of a word in the target sentence. +# If there is a high overlap of those words with the already correlated words for a +# particular word sense, we can guess that that is the answer. diff --git a/Solutions/352.md b/Solutions/352.md new file mode 100644 index 0000000..28713ed --- /dev/null +++ b/Solutions/352.md @@ -0,0 +1,37 @@ +``` +Problem: + +A typical American-style crossword puzzle grid is an N x N matrix with black and white squares, which obeys the following rules: + +* Every white square must be part of an "across" word and a "down" word. +* No word can be fewer than three letters long. +* Every white square must be reachable from every other white square. + +The grid is rotationally symmetric (for example, the colors of the top left and bottom right squares must match). Write a program to determine whether a given matrix qualifies as a crossword grid. +``` + +## Steps for checking validity of white sqaure + +1. Generate a set (hash-list) of white square positions +2. Select a white square and run BFS/DFS for all adjoining white square and remove the + visited square positions from the white square position set. +3. If the set is non-empty after visiting all the adjoining white squares, the + crossword is invalid. + +## Pseudo-code for checking validity of rotationally symmetricity for grid + +```python +# NOTE: this is a PSEUDO-CODE +n = number of rows +m = number of columns + +for i in range(0, n / 2): + for j in range(0, m / 2): + if grid[i][j] != grid[n - 1 - i][m - 1 - j]: + return False +return True +``` + +## NOTE + +The question is vague without example diff --git a/Solutions/353.py b/Solutions/353.py new file mode 100644 index 0000000..f3be65e --- /dev/null +++ b/Solutions/353.py @@ -0,0 +1,60 @@ +""" +Problem: + +You are given a histogram consisting of rectangles of different heights. These heights +are represented in an input list, such that [1, 3, 2, 5] corresponds to the following +diagram: + + x + x + x x + x x x +x x x x +Determine the area of the largest rectangle that can be formed only from the bars of +the histogram. For the diagram above, for example, this would be six, representing the +2 x 3 area at the bottom right. +""" + +from typing import List + +from DataStructures.Stack import Stack + + +def max_area_histogram(histogram: List[int]): + stack = Stack() + max_area = 0 + index = 0 + + while index < len(histogram): + if stack.is_empty() or histogram[stack.peek()] <= histogram[index]: + stack.push(index) + index += 1 + else: + # if the current bar is lower than top of stack, the area of rectangle + # needs to be calculated with the stack top as the smallest (or minimum + # height) bar. + top_of_stack = stack.pop() + area = histogram[top_of_stack] * ( + (index - stack.peek() - 1) if not stack.is_empty() else index + ) + max_area = max(max_area, area) + # calculating the area formed by the indices still in the stack + while not stack.is_empty(): + top_of_stack = stack.pop() + area = histogram[top_of_stack] * ( + (index - stack.peek() - 1) if not stack.is_empty() else index + ) + max_area = max(max_area, area) + return max_area + + +if __name__ == "__main__": + print(max_area_histogram([1, 3, 2, 5])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/354.md b/Solutions/354.md new file mode 100644 index 0000000..e5a8958 --- /dev/null +++ b/Solutions/354.md @@ -0,0 +1,38 @@ +``` +Problem: + +Design a system to crawl and copy all of Wikipedia using a distributed network of machines. + +More specifically, suppose your server has access to a set of client machines. Your client machines can execute code you have written to access Wikipedia pages, download and parse their data, and write the results to a database. + +Some questions you may want to consider as part of your solution are: + +* How will you reach as many pages as possible? +* How can you keep track of pages that have already been visited? +* How will you deal with your client machines being blacklisted? +* How can you update your database when Wikipedia pages are added or updated? +``` + +# Wikipedia Crawler + +## System + +- Use the main page to generate a queue of links that is to be processed by the + server. +- Each link is put into a queue that is processed on the server. +- The processing involves just monitoring and sending each link to a client. +- The client downloads and parses the page, stores them in the database and adds new + URLs to the queue if the last update date is greater that the date the item was + stored in a distributed cache. + +## Questions + +- How will you reach as many pages as possible? + - Parse all URLs on each page and add them back to the queue. +- How can you keep track of pages that have already been visited? + - Distributed cache +- How will you deal with your client machines being blacklisted? + - Elastic Compute Cloud instance provisioning once `x` amount of requests get an + error code response. +- How can you update your database when Wikipedia pages are added or updated? + - Handled by the mechanism of distributed cache and last update time checking. diff --git a/Solutions/355.py b/Solutions/355.py new file mode 100644 index 0000000..9b73216 --- /dev/null +++ b/Solutions/355.py @@ -0,0 +1,59 @@ +""" +Problem: + +You are given an array X of floating-point numbers x1, x2, ... xn. These can be rounded +up or down to create a corresponding array Y of integers y1, y2, ... yn. + +Write an algorithm that finds an appropriate Y array with the following properties: + +The rounded sums of both arrays should be equal. +The absolute pairwise difference between elements is minimized. In other words, +|x1- y1| + |x2- y2| + ... + |xn- yn| should be as small as possible. +For example, suppose your input is [1.3, 2.3, 4.4]. In this case you cannot do better +than [1, 2, 5], which has an absolute difference of +|1.3 - 1| + |2.3 - 2| + |4.4 - 5| = 1. +""" + +from typing import List, Tuple + + +def get_fraction_from_tuple(tup: Tuple[int, float]) -> float: + _, elem = tup + return elem - int(elem) + + +def round_arr(arr: List[float]) -> List[int]: + rounded_arr = [round(elem) for elem in arr] + sum_arr = int(sum(arr)) + sum_rounded_arr = sum(rounded_arr) + # if the sums are equal, the rounding has been properly implemented + if sum_arr == sum_rounded_arr: + return rounded_arr + # eqalizing the sums + should_increment = sum_arr > sum_rounded_arr + num_map = sorted( + [(index, elem) for index, elem in enumerate(arr)], + key=get_fraction_from_tuple, + reverse=should_increment, + ) + # incrementing and decrementing the values as per requirement (while minimizing the + # pair-wise sum) + for i in range(sum_arr - sum_rounded_arr): + index, _ = num_map[i] + rounded_arr[index] = ( + rounded_arr[index] + 1 if should_increment else rounded_arr[index] - 1 + ) + return rounded_arr + + +if __name__ == "__main__": + print(round_arr([1.3, 2.3, 4.4])) + print(round_arr([1.8, 2.8, 4.4])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/356.py b/Solutions/356.py new file mode 100644 index 0000000..a65717a --- /dev/null +++ b/Solutions/356.py @@ -0,0 +1,73 @@ +""" +Problem: + +Implement a queue using a set of fixed-length arrays. + +The queue should support enqueue, dequeue, and get_size operations. +""" + +from typing import Any + + +class Queue: + def __init__(self, num_of_arr: int, size_of_arr: int) -> None: + # storing the fixed length arrays as matrix + self.matrix = [[None for _ in range(size_of_arr)] for _ in range(num_of_arr)] + self.size_of_arr, self.num_of_arr = size_of_arr, num_of_arr + self.head_pos, self.rear_pos = 0, 0 + + def enqueue(self, obj: Any) -> None: + if self.rear_pos == (self.num_of_arr * self.size_of_arr) - 1: + raise OverflowError("Queue is full") + + i = (self.rear_pos) // self.size_of_arr + j = (self.rear_pos) % self.size_of_arr + self.matrix[i][j] = obj + self.rear_pos += 1 + + def dequeue(self) -> Any: + if self.rear_pos == 0: + raise RuntimeError("Queue is empty") + + obj = self.matrix[0][0] + # resetting other elements' position + for pos in range(1, self.rear_pos + 1): + i = (pos) // self.size_of_arr + j = (pos) % self.size_of_arr + if j == 0: + self.matrix[i - 1][self.size_of_arr - 1] = self.matrix[i][j] + else: + self.matrix[i][j - 1] = self.matrix[i][j] + self.rear_pos -= 1 + return obj + + def get_size(self) -> int: + return self.rear_pos + + +if __name__ == "__main__": + queue = Queue(3, 2) + + queue.enqueue(1) + queue.enqueue(2) + queue.enqueue(3) + + print("SIZE:", queue.get_size()) + print(queue.dequeue()) + print("SIZE:", queue.get_size()) + + queue.enqueue(4) + + print(queue.dequeue()) + + queue.enqueue(5) + queue.enqueue(6) + + print("SIZE:", queue.get_size()) + + print(queue.dequeue()) + print(queue.dequeue()) + print(queue.dequeue()) + print(queue.dequeue()) + + print("SIZE:", queue.get_size()) diff --git a/Solutions/357.py b/Solutions/357.py new file mode 100644 index 0000000..d4b4fbb --- /dev/null +++ b/Solutions/357.py @@ -0,0 +1,44 @@ +""" +Problem: + +You are given a binary tree in a peculiar string representation. Each node is written +in the form (lr), where l corresponds to the left child and r corresponds to the right +child. + +If either l or r is null, it will be represented as a zero. Otherwise, it will be +represented by a new (lr) pair. + +Here are a few examples: + +A root node with no children: (00) +A root node with two children: ((00)(00)) +An unbalanced tree with three consecutive left children: ((((00)0)0)0) +Given this representation, determine the depth of the tree. +""" + + +def get_depth(tree_representation: str) -> int: + depth, max_depth = 0, 0 + for char in tree_representation: + if char == "(": + # entering a node (depth addition) + depth += 1 + elif char == ")": + # exiting a node (depth subtraction) + depth -= 1 + max_depth = max(max_depth, depth) + return max_depth + + +if __name__ == "__main__": + print(get_depth("(00)")) + print(get_depth("((00)(00))")) + print(get_depth("((((00)0)0)0)")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n) +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/358.py b/Solutions/358.py new file mode 100644 index 0000000..f1d6e11 --- /dev/null +++ b/Solutions/358.py @@ -0,0 +1,76 @@ +""" +Problem: + +Create a data structure that performs all the following operations in O(1) time: + +plus: Add a key with value 1. If the key already exists, increment its value by one. +minus: Decrement the value of a key. If the key's value is currently 1, remove it. +get_max: Return a key with the highest value. +get_min: Return a key with the lowest value. +""" + +from sys import maxsize + +from DataStructures.PriorityQueue import MaxPriorityQueue, MinPriorityQueue + + +class MagicDS: + def __init__(self) -> None: + self.map = {} + self.max_priority_queue = MaxPriorityQueue() + self.min_priority_queue = MinPriorityQueue() + + def plus(self, elem: int) -> None: + # runs in O(log(n)) [O(1) on Amortized analysis] + if elem not in self.map: + self.map[elem] = 1 + self.max_priority_queue.push(elem, 1) + self.min_priority_queue.push(elem, 1) + else: + self.map[elem] += 1 + self.max_priority_queue.update_key(elem, self.map[elem]) + self.min_priority_queue.update_key(elem, self.map[elem]) + + def minus(self, elem: int) -> None: + # runs in O(log(n)) [O(1) on Amortized analysis] + if elem not in self.map: + raise ValueError("Cannot decrement a non-existing key") + if self.map[elem] == 1: + del self.map[elem] + self.max_priority_queue.update_key(elem, maxsize) + self.max_priority_queue.extract_max() + self.min_priority_queue.update_key(elem, 0) + self.min_priority_queue.extract_min() + else: + self.map[elem] -= 1 + self.max_priority_queue.update_key(elem, self.map[elem]) + self.min_priority_queue.update_key(elem, self.map[elem]) + + def get_max(self) -> int: + # runs in O(1) + return self.max_priority_queue.peek_max() + + def get_min(self) -> int: + # runs in O(1) + return self.min_priority_queue.peek_min() + + +if __name__ == "__main__": + ds = MagicDS() + + ds.plus(1) + ds.plus(1) + ds.plus(1) + ds.plus(2) + ds.plus(2) + ds.plus(3) + + print(ds.get_max()) + print(ds.get_min()) + + ds.minus(1) + ds.minus(1) + ds.minus(1) + + print(ds.get_max()) + print(ds.get_min()) diff --git a/Solutions/359.py b/Solutions/359.py new file mode 100644 index 0000000..7bc2756 --- /dev/null +++ b/Solutions/359.py @@ -0,0 +1,72 @@ +""" +Problem: + +You are given a string formed by concatenating several words corresponding to the +integers zero through nine and then anagramming. + +For example, the input could be 'niesevehrtfeev', which is an anagram of +'threefiveseven'. Note that there can be multiple instances of each integer. + +Given this string, return the original integers in sorted order. In the example above, +this would be 357. +""" + +from collections import Counter +from sys import maxsize +from typing import Counter as C + +WORDS = [ + Counter("zero"), + Counter("one"), + Counter("two"), + Counter("three"), + Counter("four"), + Counter("five"), + Counter("six"), + Counter("seven"), + Counter("eight"), + Counter("nine"), +] + + +def generate_num_helper(counter: C[str]) -> C[int]: + # runs in O(1) as all the loops run in constant time + result = Counter() + for value, word_counter in enumerate(WORDS): + temp = maxsize + for key in word_counter: + # checking the number of occurance of current number + if counter[key] >= word_counter[key]: + temp = min(temp, counter[key] // word_counter[key]) + else: + temp = 0 + break + else: + # updating the input counter to remove the current number + curr_counter = Counter() + for key in word_counter: + curr_counter[key] = word_counter[key] * temp + counter = counter - curr_counter + result[value] = temp + return result + + +def generate_num(string: str) -> int: + str_counter = Counter(string) + numbers_counter = generate_num_helper(str_counter) + + numbers_list = [str(num) for num in sorted(numbers_counter.elements())] + return int("".join(numbers_list)) + + +if __name__ == "__main__": + print(generate_num("niesevehrtfeev")) + print(generate_num("niesveeviehertifennevf")) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/360.py b/Solutions/360.py new file mode 100644 index 0000000..224c7bb --- /dev/null +++ b/Solutions/360.py @@ -0,0 +1,62 @@ +""" +Problem: + +You have access to ranked lists of songs for various users. Each song is represented as +an integer, and more preferred songs appear earlier in each list. For example, the list +[4, 1, 7] indicates that a user likes song 4 the best, followed by songs 1 and 7. + +Given a set of these ranked lists, interleave them to create a playlist that satisfies +everyone's priorities. + +For example, suppose your input is {[1, 7, 3], [2, 1, 6, 7, 9], [3, 9, 5]}. In this +case a satisfactory playlist could be [2, 1, 6, 7, 3, 9, 5]. +""" + +from typing import List + +from DataStructures.PriorityQueue import MinPriorityQueue + + +def interleave_playlist(playlists: List[List[int]]) -> List[int]: + queue = MinPriorityQueue() + result = [] + # priority queue generation + # offset used to ensure that in case a song occours 2nd time (in different + # playlists), the priorities for all the songs in the 2nd playlist gets offset + for playlist in playlists: + offset = 0 + for priority, song in enumerate(playlist): + if song not in queue: + queue.push(song, offset + priority) + else: + old_priority = queue.get_priority(song) + offset += max(priority, old_priority) + queue.update_key(song, offset + priority) + # priority queue updation + # updating the queue is necessary to ensure if a song (occuring 2nd time in a + # different playlists) gets push down the queue, all the songs in the playlist + # (where the song appeared 1st) also get pushed down + for playlist in playlists: + offset = 0 + for priority, song in enumerate(playlist): + old_priority = queue.get_priority(song) + if old_priority > priority: + offset = max(offset, old_priority - priority) + queue.update_key(song, priority + offset) + + while not queue.is_empty(): + result.append(queue.extract_min()) + return result + + +if __name__ == "__main__": + print(interleave_playlist([[1, 7, 3], [2, 1, 6, 7, 9], [3, 9, 5]])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +[n = number of elements in the matrix] +""" diff --git a/Solutions/361.py b/Solutions/361.py new file mode 100644 index 0000000..5468944 --- /dev/null +++ b/Solutions/361.py @@ -0,0 +1,54 @@ +""" +Problem: + +Mastermind is a two-player game in which the first player attempts to guess the secret +code of the second. In this version, the code may be any six-digit number with all +distinct digits. + +Each turn the first player guesses some number, and the second player responds by +saying how many digits in this number correctly matched their location in the secret +code. For example, if the secret code were 123456, then a guess of 175286 would score +two, since 1 and 6 were correctly placed. + +Write an algorithm which, given a sequence of guesses and their scores, determines +whether there exists some secret code that could have produced them. + +For example, for the following scores you should return True, since they correspond to +the secret code 123456: {175286: 2, 293416: 3, 654321: 0} + +However, it is impossible for any key to result in the following scores, so in this +case you should return False: {123456: 4, 345678: 4, 567890: 4} +""" + +from typing import Dict + + +def validate_guess(guess: int, matches: Dict[int, int]) -> bool: + for match, match_count in matches.items(): + count = 0 + for char_1, char_2 in zip(str(guess).zfill(6), str(match).zfill(6)): + if char_1 == char_2: + count += 1 + if count != match_count: + return False + return True + + +def is_match_valid(matches: Dict[int, int]) -> bool: + for guess in range(1_000_000): + if validate_guess(guess, matches): + return True + return False + + +if __name__ == "__main__": + print(is_match_valid({175286: 2, 293416: 3, 654321: 0})) + print(is_match_valid({123456: 4, 345678: 4, 567890: 4})) + + +""" +SPECS: + +TIME COMPLEXITY: O(1) [As (1,000,000 x 6) is a constant] +SPACE COMPLEXITY: O(1) +""" diff --git a/Solutions/362.py b/Solutions/362.py new file mode 100644 index 0000000..bbac351 --- /dev/null +++ b/Solutions/362.py @@ -0,0 +1,43 @@ +""" +Problem: + +A strobogrammatic number is a positive number that appears the same after being rotated +180 degrees. For example, 16891 is strobogrammatic. + +Create a program that finds all strobogrammatic numbers with N digits. +""" + +from typing import List + + +def get_strobogrammatic_numbers_helper(N: int) -> List[str]: + if N == 0: + return [""] + if N == 1: + return ["1", "8", "0"] + + smaller_strobogrammatic_numbers = get_strobogrammatic_numbers_helper(N - 2) + strob_numbers = [] + for x in smaller_strobogrammatic_numbers: + strob_numbers.extend( + ["1" + x + "1", "6" + x + "9", "9" + x + "6", "8" + x + "8",] + ) + return strob_numbers + + +def get_strobogrammatic_numbers(N: int) -> List[int]: + return [int(num) for num in get_strobogrammatic_numbers_helper(N)] + + +if __name__ == "__main__": + print(get_strobogrammatic_numbers(1)) + print(get_strobogrammatic_numbers(2)) + print(get_strobogrammatic_numbers(3)) + + +""" +SPECS: + +TIME COMPLEXITY: O(4 ^ n) +SPACE COMPLEXITY: O(4 ^ n) +""" diff --git a/Solutions/363.py b/Solutions/363.py new file mode 100644 index 0000000..528a2c0 --- /dev/null +++ b/Solutions/363.py @@ -0,0 +1,39 @@ +""" +Problem: + +Write a function, add_subtract, which alternately adds and subtracts curried arguments. +Here are some sample operations: + +add_subtract(7) -> 7 +add_subtract(1)(2)(3) -> 1 + 2 - 3 -> 0 +add_subtract(-5)(10)(3)(9) -> -5 + 10 - 3 + 9 -> 11 +""" + +from __future__ import annotations + + +class CallableInt(int): + def __init__(self, value: int) -> None: + int.__init__(value) + self.should_add = True + + def __call__(self, value: int) -> CallableInt: + if self.should_add: + result = CallableInt(self + value) + else: + result = CallableInt(self - value) + result.update_should_add(not self.should_add) + return result + + def update_should_add(self, should_add: bool) -> None: + self.should_add = should_add + + +def add_subtract(value: int) -> CallableInt: + return CallableInt(value) + + +if __name__ == "__main__": + print(add_subtract(7)) + print(add_subtract(1)(2)(3)) + print(add_subtract(-5)(10)(3)(9)) diff --git a/Solutions/364.py b/Solutions/364.py new file mode 100644 index 0000000..9691e29 --- /dev/null +++ b/Solutions/364.py @@ -0,0 +1,56 @@ +""" +Problem: + +Describe an algorithm to compute the longest increasing subsequence of an array of +numbers in O(n log n) time. +""" + +from typing import List + + +def get_ceil_index(arr: List[int], l: int, r: int, key: int) -> int: + while r - l > 1: + m = l + (r - l) // 2 + if arr[m] >= key: + r = m + else: + l = m + return r + + +def get_longest_increasing_subsequence(arr: List[int]) -> int: + length = len(arr) + tail_table = [0 for i in range(length)] + tail_table[0] = arr[0] + result_length = 1 + + for i in range(1, length): + if arr[i] < tail_table[0]: + # new smallest value + tail_table[0] = arr[i] + elif arr[i] > tail_table[result_length - 1]: + # current element is a part of a increasing subsequence + tail_table[result_length] = arr[i] + result_length += 1 + else: + # current element is the last candidate of an existing subsequence and will + # replace ceil value in tail_table + tail_table[get_ceil_index(tail_table, -1, result_length - 1, arr[i])] = arr[ + i + ] + return result_length + + +if __name__ == "__main__": + print(get_longest_increasing_subsequence([1, 2, 3, 4, 5])) + print(get_longest_increasing_subsequence([1, 2, 3, 5, 4])) + print(get_longest_increasing_subsequence([1, 4, 1, 2, 3])) + print(get_longest_increasing_subsequence([5, 4, 3, 2, 1])) + + +""" +SPECS: + +TIME COMPLEXITY: O(n x log(n)) +SPACE COMPLEXITY: O(n) +""" diff --git a/Solutions/365.py b/Solutions/365.py new file mode 100644 index 0000000..9a1a6b5 --- /dev/null +++ b/Solutions/365.py @@ -0,0 +1,69 @@ +""" +Problem: + +A quack is a data structure combining properties of both stacks and queues. It can be +viewed as a list of elements written left to right such that three operations are +possible: + +push(x): add a new item x to the left end of the list +pop(): remove and return the item on the left end of the list +pull(): remove the item on the right end of the list. +Implement a quack using three stacks and O(1) additional memory, so that the amortized +time for any push, pop, or pull operation is O(1). +""" + +from DataStructures.Stack import Stack + + +class Quack: + def __init__(self) -> None: + self.stack_1 = Stack() + self.stack_2 = Stack() + self.stack_3 = Stack() + self.elements = 0 + + def __len__(self) -> int: + return self.elements + + def push(self, x: int) -> None: + self.stack_1.push(x) + self.stack_2.push(x) + self.elements += 1 + + def pop(self) -> int: + if self.elements == 0: + raise RuntimeWarning("Quack underflow") + if len(self.stack_2) == 0: + while not self.stack_3.is_empty(): + self.stack_2.push(self.stack_3.pop()) + self.elements -= 1 + self.stack_2.pop() + return self.stack_1.pop() + + def pull(self) -> int: + if self.elements == 0: + raise RuntimeWarning("Quack underflow") + if len(self.stack_3) == 0: + while not self.stack_2.is_empty(): + self.stack_3.push(self.stack_2.pop()) + self.elements -= 1 + return self.stack_3.pop() + + +if __name__ == "__main__": + quack = Quack() + + quack.push(1) + quack.push(2) + quack.push(3) + quack.push(4) + quack.push(5) + + print(quack.pop()) + print(quack.pull()) + + print(quack.pop()) + print(quack.pull()) + + print(quack.pull()) + print(f"Length: {len(quack)}") diff --git a/Solutions/DataStructures/Graph.py b/Solutions/DataStructures/Graph.py new file mode 100644 index 0000000..4c9b10b --- /dev/null +++ b/Solutions/DataStructures/Graph.py @@ -0,0 +1,135 @@ +from typing import Union + + +class GraphUndirectedUnweighted: + """ + Graph Undirected Unweighted Class + + Functions: + add_node: function to add a node in the graph + add_edge: function to add an edge between 2 nodes in the graph + """ + + def __init__(self) -> None: + self.connections = {} + self.nodes = 0 + + def __repr__(self) -> str: + return str(self.connections) + + def __len__(self) -> int: + return self.nodes + + def add_node(self, node: Union[int, str]) -> None: + # Add a node in the graph if it is not in the graph + if node not in self.connections: + self.connections[node] = set() + self.nodes += 1 + + def add_edge(self, node1: Union[int, str], node2: Union[int, str]) -> None: + # Add an edge between 2 nodes in the graph + self.add_node(node1) + self.add_node(node2) + self.connections[node1].add(node2) + self.connections[node2].add(node1) + + +class GraphDirectedUnweighted: + """ + Graph Directed Unweighted Class + + Functions: + add_node: function to add a node in the graph + add_edge: function to add an edge between 2 nodes in the graph + """ + + def __init__(self) -> None: + self.connections = {} + self.nodes = 0 + + def __repr__(self) -> str: + return str(self.connections) + + def __len__(self) -> int: + return self.nodes + + def add_node(self, node: Union[int, str]) -> None: + # Add a node in the graph if it is not in the graph + if node not in self.connections: + self.connections[node] = set() + self.nodes += 1 + + def add_edge(self, node1: Union[int, str], node2: Union[int, str]) -> None: + # Add an edge between 2 nodes in the graph + self.add_node(node1) + self.add_node(node2) + self.connections[node1].add(node2) + + +class GraphUndirectedWeighted: + """ + Graph Undirected Weighted Class + + Functions: + add_node: function to add a node in the graph + add_edge: function to add an edge between 2 nodes in the graph + """ + + def __init__(self) -> None: + self.connections = {} + self.nodes = 0 + + def __repr__(self) -> str: + return str(self.connections) + + def __len__(self) -> int: + return self.nodes + + def add_node(self, node: Union[int, str]) -> None: + # Add a node in the graph if it is not in the graph + if node not in self.connections: + self.connections[node] = {} + self.nodes += 1 + + def add_edge( + self, node1: Union[int, str], node2: Union[int, str], weight: int + ) -> None: + # Add an edge between 2 nodes in the graph + self.add_node(node1) + self.add_node(node2) + self.connections[node1][node2] = weight + self.connections[node2][node1] = weight + + +class GraphDirectedWeighted: + """ + Graph Directed Weighted Class + + Functions: + add_node: function to add a node in the graph + add_edge: function to add an edge between 2 nodes in the graph + """ + + def __init__(self) -> None: + self.connections = {} + self.nodes = 0 + + def __repr__(self) -> str: + return str(self.connections) + + def __len__(self) -> int: + return self.nodes + + def add_node(self, node: Union[int, str]) -> None: + # Add a node in the graph if it is not in the graph + if node not in self.connections: + self.connections[node] = {} + self.nodes += 1 + + def add_edge( + self, node1: Union[int, str], node2: Union[int, str], weight: int + ) -> None: + # Add an edge between 2 nodes in the graph + self.add_node(node1) + self.add_node(node2) + self.connections[node1][node2] = weight diff --git a/Solutions/DataStructures/Heap.py b/Solutions/DataStructures/Heap.py new file mode 100644 index 0000000..477a689 --- /dev/null +++ b/Solutions/DataStructures/Heap.py @@ -0,0 +1,202 @@ +from typing import Union + + +def get_parent_position(position: int) -> int: + # helper function get the position of the parent of the current node + return (position - 1) // 2 + + +def get_left_child_position(position: int) -> int: + # helper function get the position of the left child of the current node + return (2 * position) + 1 + + +def get_right_child_position(position: int) -> int: + # helper function get the position of the right child of the current node + return (2 * position) + 2 + + +class MinHeap: + """ + Min Heap class + + Functions: + extract_min: Remove and return the minimum element from the heap + insert: Insert a node into the heap + peek: Get the minimum element from the heap + _bubble_up: helper function to place a node at the proper position (upward + movement) + _bubble_down: helper function to place a node at the proper position (downward + movement) + _swap_nodes: helper function to swap the nodes at the given positions + """ + + def __init__(self) -> None: + self.heap = [] + self.elements = 0 + + def __len__(self) -> int: + return self.elements + + def __repr__(self) -> str: + return str(self.heap) + + def extract_min(self) -> Union[int, str]: + # function to remove and return the minimum element from the heap + if self.elements == 0: + raise RuntimeError("Heap Underflow. Cannot extract min from a empty heap") + + if self.elements > 1: + self._swap_nodes(0, self.elements - 1) + elem = self.heap.pop() + self.elements -= 1 + if self.elements > 0: + self._bubble_down(0) + return elem + + def insert(self, elem: Union[int, str]) -> None: + # function to insert a node into the heap + self.heap.append(elem) + self._bubble_up(self.elements) + self.elements += 1 + + def peek_min(self) -> Union[int, str]: + # function to get the minimum element from the heap + if self.elements == 0: + raise RuntimeError("Heap is empty") + return self.heap[0] + + def _bubble_up(self, curr_pos: int) -> None: + # Place a node at the proper position (upward movement) [to be used internally + # only] + if curr_pos == 0: + return + parent_position = get_parent_position(curr_pos) + elem = self.heap[curr_pos] + parent = self.heap[parent_position] + if parent > elem: + self._swap_nodes(parent_position, curr_pos) + self._bubble_up(parent_position) + + def _bubble_down(self, curr_pos: int) -> None: + # Place a node at the proper position (downward movement) [to be used + # internally only] + elem = self.heap[curr_pos] + child_left_position = get_left_child_position(curr_pos) + child_right_position = get_right_child_position(curr_pos) + if child_left_position < self.elements and child_right_position < self.elements: + child_left = self.heap[child_left_position] + child_right = self.heap[child_right_position] + if child_right < child_left: + if child_right < elem: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(child_right_position) + if child_left_position < self.elements: + child_left = self.heap[child_left_position] + if child_left < elem: + self._swap_nodes(child_left_position, curr_pos) + return self._bubble_down(child_left_position) + else: + return + if child_right_position < self.elements: + child_right = self.heap[child_right_position] + if child_right < elem: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(child_right_position) + + def _swap_nodes(self, pos1: int, pos2: int) -> None: + # function to swap two nodes in the heap [to be used internally only] + self.heap[pos1], self.heap[pos2] = self.heap[pos2], self.heap[pos1] + + +class MaxHeap: + """ + Max Heap class + + Functions: + extract_max: Remove and return the maximum element from the heap + insert: Insert a node into the heap + peek: Get the maximum element from the heap + _bubble_up: helper function to place a node at the proper position (upward + movement) + _bubble_down: helper function to place a node at the proper position (downward + movement) + _swap_nodes: helper function to swap the nodes at the given positions + """ + + def __init__(self) -> None: + self.heap = [] + self.elements = 0 + + def __len__(self) -> int: + return self.elements + + def __repr__(self) -> str: + return str(self.heap) + + def extract_max(self) -> Union[int, str]: + # function to remove and return the minimum element from the heap + if self.elements == 0: + raise RuntimeError("Heap Underflow. Cannot extract max from a empty heap") + + if self.elements > 1: + self._swap_nodes(0, self.elements - 1) + elem = self.heap.pop() + self.elements -= 1 + if self.elements > 0: + self._bubble_down(0) + return elem + + def insert(self, elem: Union[int, str]) -> None: + # function to insert a node into the heap + self.heap.append(elem) + self._bubble_up(self.elements) + self.elements += 1 + + def peek_max(self) -> Union[int, str]: + # function to get the minimum element from the heap + if self.elements == 0: + raise RuntimeError("Heap is empty") + return self.heap[0] + + def _bubble_up(self, curr_pos: int) -> None: + # Place a node at the proper position (upward movement) [to be used internally + # only] + if curr_pos == 0: + return + parent_position = get_parent_position(curr_pos) + elem = self.heap[curr_pos] + parent = self.heap[parent_position] + if parent < elem: + self._swap_nodes(parent_position, curr_pos) + self._bubble_up(parent_position) + + def _bubble_down(self, curr_pos: int) -> None: + # Place a node at the proper position (downward movement) [to be used + # internally only] + elem = self.heap[curr_pos] + child_left_position = get_left_child_position(curr_pos) + child_right_position = get_right_child_position(curr_pos) + if child_left_position < self.elements and child_right_position < self.elements: + child_left = self.heap[child_left_position] + child_right = self.heap[child_right_position] + if child_right > child_left: + if child_right > elem: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(child_right_position) + if child_left_position < self.elements: + child_left = self.heap[child_left_position] + if child_left > elem: + self._swap_nodes(child_left_position, curr_pos) + return self._bubble_down(child_left_position) + else: + return + if child_right_position < self.elements: + child_right = self.heap[child_right_position] + if child_right > elem: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(child_right_position) + + def _swap_nodes(self, pos1: int, pos2: int) -> None: + # function to swap two nodes in the heap [to be used internally only] + self.heap[pos1], self.heap[pos2] = self.heap[pos2], self.heap[pos1] diff --git a/Solutions/DataStructures/LinkedList.py b/Solutions/DataStructures/LinkedList.py new file mode 100644 index 0000000..21a9fca --- /dev/null +++ b/Solutions/DataStructures/LinkedList.py @@ -0,0 +1,60 @@ +from typing import Iterable + + +class Node: + """ + Node Class for the nodes of a Linked List + """ + + def __init__(self, val: int = None) -> None: + self.val = val + self.next = None + + def __repr__(self) -> str: + if self.next: + return f"{str(self.val)} => {str(self.next)}" + return str(self.val) + + +class LinkedList: + """ + Linked List Class + + Functions: + add: function to add a node at the end of the linked list + """ + + def __init__(self) -> None: + self.head = None + self.rear = None + self.length = 0 + + def __repr__(self) -> str: + return str(self.head) + + def add(self, val: int = 0): + # Add a new node with the provided value and adds it at the rear of the list + self.length += 1 + if self.head is None: + self.head = Node(val) + self.rear = self.head + else: + self.rear.next = Node(val) + self.rear = self.rear.next + + def __len__(self) -> int: + return self.length + + # iteration initialization + def __iter__(self) -> Iterable: + self.curr = self.head + return self + + # next function to iterate through the linked list iterator + def __next__(self) -> int: + if self.curr: + value = self.curr.val + self.curr = self.curr.next + return value + else: + raise StopIteration diff --git a/Solutions/DataStructures/PriorityQueue.py b/Solutions/DataStructures/PriorityQueue.py new file mode 100644 index 0000000..e98a213 --- /dev/null +++ b/Solutions/DataStructures/PriorityQueue.py @@ -0,0 +1,289 @@ +def get_parent_position(position: int) -> int: + # helper function get the position of the parent of the current node + return (position - 1) // 2 + + +def get_child_left_position(position: int) -> int: + # helper function get the position of the left child of the current node + return (2 * position) + 1 + + +def get_child_right_position(position: int) -> int: + # helper function get the position of the right child of the current node + return (2 * position) + 2 + + +class MinPriorityQueue: + """ + Minimum Priority Queue Class + + Functions: + is_empty: function to check if the priority queue is empty + push: function to add an element with given priority to the queue + peek_min: function to get the element with lowest weight (highest priority) without + removing it from the queue + extract_min: function to remove and return the element with lowest weight (highest + priority) + get_priority: function to get the priority of the given key + update_key: function to update the weight of the given key + _bubble_up: helper function to place a node at the proper position (upward + movement) + _bubble_down: helper function to place a node at the proper position (downward + movement) + _swap_nodes: helper function to swap the nodes at the given positions + """ + + def __init__(self) -> None: + self.heap = [] + self.position_map = {} + self.elements = 0 + + def __len__(self) -> int: + return self.elements + + def __repr__(self) -> str: + return str(self.heap) + + def __contains__(self, key: int) -> bool: + return key in self.position_map + + def is_empty(self) -> bool: + # Check if the priority queue is empty + return self.elements == 0 + + def push(self, elem: int, weight: int) -> None: + # Add an element with given priority to the queue + self.heap.append((elem, weight)) + self.position_map[elem] = self.elements + self.elements += 1 + self._bubble_up(elem) + + def peek_min(self): + if self.elements == 0: + raise RuntimeError("Queue is empty") + elem, _ = self.heap[0] + return elem + + def extract_min(self) -> int: + # Remove and return the element with lowest weight (highest priority) + if self.elements > 1: + self._swap_nodes(0, self.elements - 1) + elem, _ = self.heap.pop() + del self.position_map[elem] + self.elements -= 1 + if self.elements > 0: + bubble_down_elem, _ = self.heap[0] + self._bubble_down(bubble_down_elem) + return elem + + def get_priority(self, key: int) -> int: + if key not in self: + raise ValueError(f"{key} not found") + _, weight = self.heap[self.position_map[key]] + return weight + + def update_key(self, elem: int, weight: int) -> None: + # Update the weight of the given key + position = self.position_map[elem] + self.heap[position] = (elem, weight) + if position > 0: + parent_position = get_parent_position(position) + _, parent_weight = self.heap[parent_position] + if parent_weight > weight: + self._bubble_up(elem) + else: + self._bubble_down(elem) + else: + self._bubble_down(elem) + + def _bubble_up(self, elem: int) -> None: + # Place a node at the proper position (upward movement) [to be used internally + # only] + curr_pos = self.position_map[elem] + if curr_pos == 0: + return + parent_position = get_parent_position(curr_pos) + _, weight = self.heap[curr_pos] + _, parent_weight = self.heap[parent_position] + if parent_weight > weight: + self._swap_nodes(parent_position, curr_pos) + return self._bubble_up(elem) + return + + def _bubble_down(self, elem: int) -> None: + # Place a node at the proper position (downward movement) [to be used + # internally only] + curr_pos = self.position_map[elem] + _, weight = self.heap[curr_pos] + child_left_position = get_child_left_position(curr_pos) + child_right_position = get_child_right_position(curr_pos) + if child_left_position < self.elements and child_right_position < self.elements: + _, child_left_weight = self.heap[child_left_position] + _, child_right_weight = self.heap[child_right_position] + if child_right_weight < child_left_weight: + if child_right_weight < weight: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(elem) + if child_left_position < self.elements: + _, child_left_weight = self.heap[child_left_position] + if child_left_weight < weight: + self._swap_nodes(child_left_position, curr_pos) + return self._bubble_down(elem) + else: + return + if child_right_position < self.elements: + _, child_right_weight = self.heap[child_right_position] + if child_right_weight < weight: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(elem) + else: + return + + def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None: + # Swap the nodes at the given positions + node1_elem = self.heap[node1_pos][0] + node2_elem = self.heap[node2_pos][0] + self.heap[node1_pos], self.heap[node2_pos] = ( + self.heap[node2_pos], + self.heap[node1_pos], + ) + self.position_map[node1_elem] = node2_pos + self.position_map[node2_elem] = node1_pos + + +class MaxPriorityQueue: + """ + Maximum Priority Queue Class + + Functions: + is_empty: function to check if the priority queue is empty + push: function to add an element with given priority to the queue + peek_max: function to get the element with highest weight (highest priority) + without removing it from the queue + extract_max: function to remove and return the element with highest weight (highest + priority) + get_priority: function to get the priority of the given key + update_key: function to update the weight of the given key + _bubble_up: helper function to place a node at the proper position (upward + movement) + _bubble_down: helper function to place a node at the proper position (downward + movement) + _swap_nodes: helper function to swap the nodes at the given positions + """ + + def __init__(self) -> None: + self.heap = [] + self.position_map = {} + self.elements = 0 + + def __len__(self) -> int: + return self.elements + + def __repr__(self) -> str: + return str(self.heap) + + def __contains__(self, key: int) -> bool: + return key in self.position_map + + def is_empty(self) -> bool: + # Check if the priority queue is empty + return self.elements == 0 + + def push(self, elem: int, weight: int) -> None: + # Add an element with given priority to the queue + self.heap.append((elem, weight)) + self.position_map[elem] = self.elements + self.elements += 1 + self._bubble_up(elem) + + def peek_max(self): + if self.elements == 0: + raise RuntimeError("Queue is empty") + elem, _ = self.heap[0] + return elem + + def extract_max(self) -> int: + # Remove and return the element with highest weight (highest priority) + if self.elements > 1: + self._swap_nodes(0, self.elements - 1) + elem, _ = self.heap.pop() + del self.position_map[elem] + self.elements -= 1 + if self.elements > 0: + bubble_down_elem, _ = self.heap[0] + self._bubble_down(bubble_down_elem) + return elem + + def get_priority(self, key: int) -> int: + if key not in self: + raise ValueError(f"{key} not found") + _, weight = self.heap[self.position_map[key]] + return weight + + def update_key(self, elem: int, weight: int) -> None: + # Update the weight of the given key + position = self.position_map[elem] + self.heap[position] = (elem, weight) + if position > 0: + parent_position = get_parent_position(position) + _, parent_weight = self.heap[parent_position] + if parent_weight < weight: + self._bubble_up(elem) + else: + self._bubble_down(elem) + else: + self._bubble_down(elem) + + def _bubble_up(self, elem: int) -> None: + # Place a node at the proper position (upward movement) [to be used internally + # only] + curr_pos = self.position_map[elem] + if curr_pos == 0: + return + parent_position = get_parent_position(curr_pos) + _, weight = self.heap[curr_pos] + _, parent_weight = self.heap[parent_position] + if parent_weight < weight: + self._swap_nodes(parent_position, curr_pos) + return self._bubble_up(elem) + return + + def _bubble_down(self, elem: int) -> None: + # Place a node at the proper position (downward movement) [to be used + # internally only] + curr_pos = self.position_map[elem] + _, weight = self.heap[curr_pos] + child_left_position = get_child_left_position(curr_pos) + child_right_position = get_child_right_position(curr_pos) + if child_left_position < self.elements and child_right_position < self.elements: + _, child_left_weight = self.heap[child_left_position] + _, child_right_weight = self.heap[child_right_position] + if child_right_weight > child_left_weight: + if child_right_weight > weight: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(elem) + if child_left_position < self.elements: + _, child_left_weight = self.heap[child_left_position] + if child_left_weight > weight: + self._swap_nodes(child_left_position, curr_pos) + return self._bubble_down(elem) + else: + return + if child_right_position < self.elements: + _, child_right_weight = self.heap[child_right_position] + if child_right_weight > weight: + self._swap_nodes(child_right_position, curr_pos) + return self._bubble_down(elem) + else: + return + + def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None: + # Swap the nodes at the given positions + node1_elem = self.heap[node1_pos][0] + node2_elem = self.heap[node2_pos][0] + self.heap[node1_pos], self.heap[node2_pos] = ( + self.heap[node2_pos], + self.heap[node1_pos], + ) + self.position_map[node1_elem] = node2_pos + self.position_map[node2_elem] = node1_pos diff --git a/Solutions/DataStructures/Queue.py b/Solutions/DataStructures/Queue.py new file mode 100644 index 0000000..ebbf422 --- /dev/null +++ b/Solutions/DataStructures/Queue.py @@ -0,0 +1,57 @@ +from typing import Union + + +class Queue: + """ + Queue Class for FIFO Structure + + Functions: + dequeue: Remove and return the object at the head of the queue + Raises error if the queue is empty + enqueue: Add an object to the end of the queue + is_empty: Check if the queue is empty + peek: Get the value at the queue head without removing it + """ + + def __init__(self) -> None: + self.queue = [] + self.elements = 0 + + def __repr__(self) -> str: + return str(self.queue) + + def __len__(self) -> int: + return self.elements + + def __delitem__(self, position: int) -> None: + del self.queue[position] + self.elements -= 1 + + def __getitem__(self, position: int) -> Union[int, str]: + return self.queue[position] + + def __setitem__(self, position: int, value: Union[int, str]) -> None: + self.queue[position] = value + + def dequeue(self) -> Union[int, str]: + # Remove and return the object at the head of the queue + # Raises error if the queue is empty + if self.elements == 0: + raise Exception("Queue Underflow. Cannot de-queue from an empty queue") + self.elements -= 1 + return self.queue.pop(0) + + def enqueue(self, val: Union[int, str]) -> None: + # Add an object to the end of the queue + self.elements += 1 + self.queue.append(val) + + def is_empty(self) -> bool: + # Check if the queue is empty + return not bool(self.queue) + + def peek(self) -> Union[int, str]: + # Get the value at the queue head without removing it + if self.is_empty(): + raise Exception("Queue Underflow. Cannot peek at an empty queue") + return self.queue[0] diff --git a/Solutions/DataStructures/Stack.py b/Solutions/DataStructures/Stack.py new file mode 100644 index 0000000..e038ba5 --- /dev/null +++ b/Solutions/DataStructures/Stack.py @@ -0,0 +1,66 @@ +from typing import Union + + +class Stack: + """ + Stack Class for LIFO Structure + + Functions: + is_empty: Check if the stack is empty + peek: Get the value at the stack top without removing it + pop: Pop the object at the top of the stack + Raises erorr if the stack is empty + push: Push an object to the top of the stack + """ + + def __init__(self) -> None: + self.stack = [] + self.rear = -1 + self.top = -1 + + def __repr__(self) -> str: + return str(self.stack) + + def __len__(self) -> int: + return len(self.stack) + + def __delitem__(self, position: int) -> None: + del self.stack[position] + self.rear -= 1 + + def __getitem__(self, position: int) -> Union[int, str]: + return self.stack[position] + + def __setitem__(self, position: int, value: Union[int, str]) -> None: + self.stack[position] = value + + def is_empty(self) -> bool: + # Check if the stack is empty + return not bool(self.stack) + + def peek(self) -> Union[int, str]: + # Get the value at the stack top without removing it + if self.is_empty(): + raise Exception("Stack Underflow. Cannot peek at an empty stack") + return self.stack[-1] + + def pop(self) -> Union[int, str]: + # Pop the value at the stack top + if self.rear == -1: + raise Exception("Stack Underflow. Cannot pop from an empty stack") + elif self.top == 0: + self.rear = -1 + self.top = -1 + else: + self.top -= 1 + return self.stack.pop() + + def push(self, val: Union[int, str]) -> None: + # Push a new value to the stack top + if self.rear == -1: + self.stack.append(val) + self.rear = 0 + self.top = 0 + else: + self.stack.append(val) + self.top += 1 diff --git a/Solutions/DataStructures/Tree.py b/Solutions/DataStructures/Tree.py new file mode 100644 index 0000000..e7b28fc --- /dev/null +++ b/Solutions/DataStructures/Tree.py @@ -0,0 +1,130 @@ +from __future__ import annotations +from typing import Any, Optional, Union + + +class Node: + """ + Node Class for the nodes of a Binary Tree + + Functions: + insert_helper: Helper function to add node in a Binary Search Tree + height_helper: Helper function to calculate the height of a Binary Tree + num_nodes_helper: Helper function to calculate the number of Nodes in a Binary Tree + to_str: Helper function for __repr__ + """ + + def __init__( + self, val: int, left: Optional[Node] = None, right: Optional[Node] = None + ) -> None: + self.val = val + self.left = left + self.right = right + + def __eq__(self, other: Any) -> bool: + if type(other) == Node and self.val == other.val: + return self.left == other.left and self.right == other.right + return False + + def __repr__(self) -> str: + return self.to_str() + + def height_helper(self) -> int: + # Helper function to calculate the height of a Binary Tree + # Uses: height = max(left_height, right_height) + left_height, right_height = 0, 0 + if self.left is not None: + left_height = self.left.height_helper() + if self.right is not None: + right_height = self.right.height_helper() + return max(left_height, right_height) + 1 + + def insert_helper(self, val: int) -> None: + # Helper function to add node in a Binary Search Tree + # Uses: BST property + # NOTE: Duplicate nodes are not added + if self.val > val: + if self.left is None: + self.left = Node(val) + else: + self.left.insert_helper(val) + elif self.val < val: + if self.right is None: + self.right = Node(val) + else: + self.right.insert_helper(val) + + def num_nodes_helper(self) -> int: + # Helper function to calculate the number of Nodes in a Binary Tree + left, right = 0, 0 + if self.left: + left = self.left.num_nodes_helper() + if self.right: + right = self.right.num_nodes_helper() + return left + right + 1 + + def to_str(self) -> str: + # Helper function for __repr__ + # Returns all the childen in case 1 of them is not None, else returns only the + # value + if self.right is None and self.left is None: + return f"('{self.val}')" + elif self.left is not None and self.right is None: + return f"({self.left.to_str()}, '{self.val}', null)" + elif self.left is None and self.right is not None: + return f"(null, '{self.val}', {self.right.to_str()})" + elif self.left is not None and self.right is not None: + return f"({self.left.to_str()}, '{self.val}', {self.right.to_str()})" + + +class BinaryTree: + """ + Binary Tree Class + + Functions: + find_height: Calculate the height of a Binary Tree (uses height_helper in the Node + Class) + + NOTE: This class does not have the add node function and nodes have to be added + manually + """ + + def __init__(self) -> None: + self.root = None + + def __eq__(self, other: Any) -> bool: + if type(other) == BinaryTree: + return self.root == other.root + return False + + def __len__(self) -> int: + if self.root: + return self.root.num_nodes_helper() + return 0 + + def __repr__(self) -> str: + return str(self.root) + + def find_height(self) -> int: + # Calculate the height of a Binary Tree + if self.root: + return self.root.height_helper() + return 0 + + +class BinarySearchTree(BinaryTree): + """ + Binary Tree Class (INHERITS FROM THE BinaryTree CLASS) + + Functions: + add: Add nodes to a Binary Search Tree (uses insert_helper in the Node Class) + """ + + def __init__(self) -> None: + BinaryTree.__init__(self) + + def add(self, val: Union[int, str]) -> None: + # Add nodes to a Binary Search Tree + if self.root is None: + self.root = Node(val) + else: + self.root.insert_helper(val) diff --git a/Solutions/DataStructures/Trie.py b/Solutions/DataStructures/Trie.py new file mode 100644 index 0000000..17556d4 --- /dev/null +++ b/Solutions/DataStructures/Trie.py @@ -0,0 +1,60 @@ +from typing import List, Optional + + +class TrieNode: + """ + TrieNode Class for the nodes of a Pre-processing Trie + """ + + def __init__(self) -> None: + self.children = {} + self.is_end = False + + +class Trie: + """ + Pre-processing Trie Class + + Functions: + add: Add a string to the Trie + add_words: Add a list of strings to the Trie + get_suggestions: Get all possible words from the given prefix + _traverse: Helper function for get_suggestions (generates the words from prefix) + """ + + def __init__(self) -> None: + self.root = TrieNode() + + def add(self, word: str) -> None: + # Add a string to the Trie + pos = self.root + for char in word: + if char not in pos.children: + pos.children[char] = TrieNode() + pos = pos.children[char] + pos.is_end = True + + def add_words(self, word_list: List[str]) -> None: + # Add a list of strings to the Trie + for word in word_list: + self.add(word) + + def get_suggestions(self, prefix: str) -> Optional[List[str]]: + # Get all possible words from the given prefix + pos = self.root + for char in prefix: + if char not in pos.children: + # returns None if no word is possible from the given prefix + return None + pos = pos.children[char] + result = set() + self._traverse(pos, prefix, result) + return result + + def _traverse(self, pos: TrieNode, curr: str, result: set) -> None: + # Helper function for get_suggestions + # Generates the words from prefix (using result as the accumulator) + if pos.is_end: + result.add(curr) + for child in pos.children: + self._traverse(pos.children[child], curr + child, result) diff --git a/Solutions/DataStructures/__init__.py b/Solutions/DataStructures/__init__.py new file mode 100644 index 0000000..e69de29