├── .vscode └── settings.json ├── DataStructures └── LinkedList │ └── detect_list_middle.py ├── DesignQuestions ├── MergePurge.md └── README.md ├── DynamicProgramming ├── README.md └── longest_increasing_subsequence.py ├── GraphTheory ├── BFS.py ├── DFS(iterative).py ├── DFS(rec).py ├── README.md ├── check_binary_search_tree.py ├── mirror_tree.png ├── not_bst.png ├── tree.png ├── tree_diameter.py └── tree_traversals.py ├── InterviewProcess └── README.md ├── LICENSE ├── MathRelatedProblems └── KRootAprroximation.py ├── README.md ├── StringProblems ├── README.md ├── pattern_anagram.py ├── string_compression.py └── string_duplicates.py └── cool.py /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": false 3 | } -------------------------------------------------------------------------------- /DataStructures/LinkedList/detect_list_middle.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = None 5 | 6 | 7 | class LinkedList: 8 | def __init__(self, start): 9 | self.start = start 10 | 11 | def detect_middle(self): 12 | if self.start.next is None: 13 | return self.start 14 | 15 | i = self.start 16 | j = self.start 17 | 18 | while j.next is not None: 19 | j = j.next.next 20 | if j is not None: 21 | i = i.next 22 | else: 23 | break 24 | if j is not None: 25 | return i.value 26 | return i.value, i.next.value 27 | 28 | 29 | def main(): 30 | n1 = Node(1) 31 | n2 = Node(2) 32 | n3 = Node(3) 33 | n4 = Node(4) 34 | n5 = Node(5) 35 | 36 | n1.next = n2 37 | n2.next = n3 38 | n3.next = n4 39 | n4.next = n5 40 | 41 | l = LinkedList(n1) 42 | 43 | assert (l.detect_middle() == 3) 44 | 45 | main() 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /DesignQuestions/MergePurge.md: -------------------------------------------------------------------------------- 1 | # Merge-Purge related problems 2 | 3 | Suppose that you are the CEO of a large company like Amazon and 4 | you just aquired another company that provides similar services 5 | like Emag. It's blackfriday and you have to send mails to all your 6 | users with their favourite items that are on sale but you don't want to send multiple mails to the same person. What is your approach? 7 | 8 | Now from the start there are a few problems that you should point out to the interviewer: 9 | 10 | * Most likely there are users that are customors of the both entities. 11 | * We can have the same customer that used different emails for registration in these two companies 12 | 13 | * There are typos in our databases. 14 | 15 | * The ammount of data. 16 | 17 | The solution for this problem was designed in the mid 90's and is called Merge-Purge. 18 | Merge-Purge is a process of merging records from one or multiple data sources and eliminating 19 | duplicate records. The core issue of the merge purge process is identifying equivalent attributes. 20 | 21 | So your answer should highlight the scenarios that merge-purge resolves: 22 | 23 | * Combine multiple lists to create a "master" list. 24 | * Combine multiple fields of data to create a "complete" record. 25 | * Exclude certain records from your mailing. 26 | * Find common records acrosss lists. 27 | 28 | The classic Merge-Purge algorithm is the Sorted Neighborhood method. 29 | 30 | This method has 3 phases: 31 | 1. Create Keys: should create the most discriminationg key O(N) 32 | 2. Sort data: partition can also be applied to use concurrency O(N log N) 33 | 3. Merge O(w*N). Use sliding window technique, where the length of the window is w. 34 | 35 | Advantages of Merge-Purge for multiple data sets: 36 | * Increases efficiency, accuracy 37 | * Decreases the impact of typos and other human erros. 38 | * Saves time and resources. 39 | 40 | -------------------------------------------------------------------------------- /DesignQuestions/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /DynamicProgramming/README.md: -------------------------------------------------------------------------------- 1 | # Part 1. Classic Dynamic Programming Problems 2 | 3 | Classic Problem no. 1: Longest Increasing Subsequence 4 | ex: 1 0 3 4 2 10 4 6 -> length 4 (0 3 4 10) 5 | O(n^2) complexity longest_increasing_subsequence.py 6 | -------------------------------------------------------------------------------- /DynamicProgramming/longest_increasing_subsequence.py: -------------------------------------------------------------------------------- 1 | def longest_subsequence(arr): 2 | n = len(arr) 3 | 4 | lista_crescatoare = [1]*n 5 | 6 | for i in range (1 , n): 7 | for j in range(0 , i): 8 | if arr[i] > arr[j] and lista_crescatoare[i]< lista_crescatoare[j] + 1 : 9 | lista_crescatoare[i] = lista_crescatoare[j]+1 10 | 11 | maximum = 0 12 | 13 | for i in range(n): 14 | maximum = max(maximum , lista_crescatoare[i]) 15 | 16 | return maximum 17 | 18 | arr = [1, 0, 3, 4, 2, 10, 4] 19 | print "Length of lista_crescatoare is", longest_subsequence(arr) 20 | -------------------------------------------------------------------------------- /GraphTheory/BFS.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, n): 3 | self.graph = defaultdict(list) 4 | for i in range(n): 5 | self.graph[i] = [] 6 | 7 | def add_edge(self, u, v): 8 | self.graph[u].append(v) 9 | 10 | def bfs_iter(self, start): 11 | visited = [False] * len(self.graph) 12 | q = [] 13 | q.append(start) 14 | visited[start] = True 15 | while q: 16 | current = q.pop(0) 17 | print(current) 18 | for i in self.graph[current]: 19 | if visited[i] == False: 20 | q.append(i) 21 | visited[i] = True 22 | 23 | 24 | b = Graph(4) 25 | b.add_edge(0, 1) 26 | b.add_edge(0, 2) 27 | b.add_edge(1, 2) 28 | b.add_edge(2, 0) 29 | b.add_edge(2, 3) 30 | 31 | b.bfs_iter(2) -------------------------------------------------------------------------------- /GraphTheory/DFS(iterative).py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, n): 3 | self.graph = defaultdict(list) 4 | for i in range(n): 5 | self.graph[i] = [] 6 | 7 | def add_edge(self, u, v): 8 | self.graph[u].append(v) 9 | 10 | def dfs_iter(self, start): 11 | visited = [False] * len(self.graph) 12 | st = [] 13 | st.append(start) 14 | while st: 15 | current = st.pop() 16 | if not visited[current]: 17 | print(current) 18 | visited[current] = True 19 | for i in self.graph[current]: 20 | if not visited[i]: 21 | st.append(i) 22 | 23 | b = Graph(4) 24 | b.add_edge(0, 1) 25 | b.add_edge(0, 2) 26 | b.add_edge(1, 2) 27 | b.add_edge(2, 0) 28 | b.add_edge(2, 3) 29 | 30 | b.dfs_iter(2) -------------------------------------------------------------------------------- /GraphTheory/DFS(rec).py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, n): 3 | self.graph = defaultdict(list) 4 | for i in range(n): 5 | self.graph[i] = [] 6 | 7 | def add_edge(self, u, v): 8 | self.graph[u].append(v) 9 | 10 | def dfs_recursiv(self, start, visited): 11 | visited[start] = True 12 | print(start) 13 | 14 | for i in self.graph[start]: 15 | if not visited[i]: 16 | self.dfs_recursiv(i, visited) 17 | 18 | def dfs_main(self, start): 19 | visited = [False] * len(self.graph) 20 | self.dfs_recursiv(start, visited) 21 | 22 | 23 | b = Graph(4) 24 | b.add_edge(0, 1) 25 | b.add_edge(0, 2) 26 | b.add_edge(1, 2) 27 | b.add_edge(2, 0) 28 | b.add_edge(2, 3) 29 | 30 | b.bfs_iter(2) 31 | print() 32 | b.dfs_iter(2) -------------------------------------------------------------------------------- /GraphTheory/README.md: -------------------------------------------------------------------------------- 1 | # Part 1: BFS, DFS, Recursive DFS 2 | These are the basic graph algorithms. 3 | A lot of interview problems can be solved with these two algorithms. 4 | 5 | I will enumerate some problems or algorithms that use DFS: 6 | * Detecting cycle in a graph 7 | * Path finding 8 | * Topological sorting 9 | * Bipartite graph testing 10 | * Finding strongly connected components 11 | 12 | I will enumerate some problems or algorithms that use BFS: 13 | * Shortest Path 14 | * Minimum Spanning Tree (unweighted graph) 15 | * Bipartite graph 16 | * Finding all the nodes in a connected component. 17 | 18 | # Part 2. Basic tree algorithms. 19 | 20 | ![tree image](tree.png) 21 | 22 | In order traversal (Left Root Right) 4 2 5 1 3 23 | Pre order traversal (Root Left Right) 1 2 4 5 3 24 | Post order traversal (Left Right Root) 4 5 2 3 1 25 | 26 | An easy way of remebering these traversal is to keep in mind that 27 | you have to place the Root in Left Right as the first word indicates you. 28 | Example Pre order: the root is before Left Right 29 | The python code for the traversals can be found in tree_traversals.py 30 | 31 | Level order tree traversal. 1 | 2 3 | 4 5 | 32 | 33 | Mirror tree. (see the second tree figure) 34 | ![mirror image](mirror_tree.png) 35 | 36 | Test if a tree is a BST. (Binary search tree) 37 | 38 | For more details about binary search tree go to: http://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/ 39 | At first it looks easy to check this, you just have to check if the root is between the left and the right values. 40 | This solution would have problems with the tree from the next figure which is not a BST. 41 | 42 | ![not bst image](not_bst.png) 43 | 44 | 8 is bigger than 3 but is on the left side so to fix this, in the reccursive call 45 | we will also pass two parameters to know the minimum and the maximum value allowed 46 | in that part of the tree. (Python implementation can be found in check_binary_search_tree.py) 47 | 48 | 49 | Check if a tree is a subtree of another tree (subtree.py) 50 | 51 | If two trees have two of the pre,post,inorder traversals identical than they are equal. 52 | Similarly if we compute the pre order and in order traversal of two trees and 53 | (store them in array pre1, pre2, in1, in2). To check if tree2 is a subtree of tree 1 we just 54 | have to see if pre2 is a subarray of pre1 and in2 a subarray of in1. Computing traversals 55 | and both subarray checks are O(N) operations so the overall complexity is O(N). 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /GraphTheory/check_binary_search_tree.py: -------------------------------------------------------------------------------- 1 | def check_bst_util(root, min_value, max_value): 2 | if root is None: 3 | return True 4 | if not (min_value < root.value < max_value): 5 | return False 6 | return check_bst_util(root.left, min, root.value) and check_bst_util(root.right, root.value, max) 7 | 8 | 9 | def check_bst(root): 10 | return check_bst_util(root, - maxsize, maxsize) -------------------------------------------------------------------------------- /GraphTheory/mirror_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GeorgeLinut/CodingInterviewTipsAndTricks/79202748f5739b59313f3fa8b820b46117fb34eb/GraphTheory/mirror_tree.png -------------------------------------------------------------------------------- /GraphTheory/not_bst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GeorgeLinut/CodingInterviewTipsAndTricks/79202748f5739b59313f3fa8b820b46117fb34eb/GraphTheory/not_bst.png -------------------------------------------------------------------------------- /GraphTheory/tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GeorgeLinut/CodingInterviewTipsAndTricks/79202748f5739b59313f3fa8b820b46117fb34eb/GraphTheory/tree.png -------------------------------------------------------------------------------- /GraphTheory/tree_diameter.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GeorgeLinut/CodingInterviewTipsAndTricks/79202748f5739b59313f3fa8b820b46117fb34eb/GraphTheory/tree_diameter.py -------------------------------------------------------------------------------- /GraphTheory/tree_traversals.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,key): 3 | self.left = None 4 | self.right = None 5 | self.val = key 6 | 7 | 8 | def print_inorder(root): 9 | 10 | if root: 11 | 12 | print_inorder(root.left) 13 | 14 | print(root.val) 15 | 16 | print_inorder(root.right) 17 | 18 | 19 | def print_postorder(root): 20 | 21 | if root: 22 | 23 | print_postorder(root.left) 24 | 25 | print_postorder(root.right) 26 | 27 | print(root.val), 28 | 29 | 30 | def print_preorder(root): 31 | 32 | if root: 33 | 34 | print(root.val), 35 | 36 | print_preorder(root.left) 37 | 38 | print_preorder(root.right) -------------------------------------------------------------------------------- /InterviewProcess/README.md: -------------------------------------------------------------------------------- 1 | # Phone interview with Recruiter 2 | A lot of companies such Microsoft, Google, Toptal have a phone interview with a 3 | recruiter as their first part of the interview process. 4 | Most of the time this is a short interview (under 30 minutes) which tests you communication 5 | skills more than anything else. This way you don't waste too much time interviewing a person who 6 | can't speak Enghish. 7 | 8 | The first thing that a recruiter would ask you is to tell a few words about yourself, think about this 9 | before the interview so you won't stutter at the interview. 10 | Also keep it simple, the recruiter does not want to know your entire story, just tell them when and where you gratuated 11 | where do you work now and a thing that would reflect that you are a good match for that company (ex: work on freelance projects 12 | in my spare time, strong background in algorithms and data structures, acm awards etc) 13 | 14 | The next part of the interview will be focused on behavioral questions 15 | A few common questions: 16 | 1. Tell me about yourself? 17 | 2. What are your greatest professional strengths? 18 | 3. Why did you leave (or why are you leaving) your job? 19 | 4. What is your greatest professional achievement? 20 | 5. Where do you see yourself in five years? 21 | 6. Why should we hire you? 22 | 7. What do you know about the company? 23 | 8. Have you got any questions? 24 | Your answers should reflect past experience that showcases your skills and your interest in the company. 25 | Having a prepared answer for them definately helps. 26 | 27 | Sometimes a recruiter can also ask you brain teasers. 28 | Usually these riddles are known ones such as the island riddle(https://puzzling.stackexchange.com/questions/9979/brooklyn-99-riddle-weighing-islanders). 29 | Great Brooklyn 99 episode by the way. 30 | 31 | 32 | # Phone interview with Software Engineer 33 | For internship roles some companies have only phone interviews. (Google, Amazon, Facebook). 34 | Microsoft has only one phone interview and then you receive plane tickets for the office where you will work 35 | if you receive an offer after the on site interviews. 36 | The first phone interview is usually pretty easy, it is designed to test basic data structures and algo skills 37 | such as working with Hashmaps and strings, maybe a bfs/dfs. 38 | Another important thing for the first phone interview is to be proficient in the language you have chosen. You may 39 | want to show your python/java/go skills by using a language specific feature. For example do some python magic 40 | in one line that would require 10 in Java. (see example in cool.py) 41 | 42 | 43 | # On site interview 44 | Questions from GlassDoor interviews. 45 | * Behavioral 46 | 47 | 1. Why do you choose Microsoft? Which group would you like to work in? Introduce a group project that you like most. 48 | 2. Describe an experience where things were not going your way and how did you overcome that. 49 | 3. Why do you want to be a software engineer 50 | 4. What is the most challenging thing you have faced during your project? 51 | 5. Describe a project that you worked on 52 | 53 | 54 | 55 | 56 | * Technical 57 | 58 | 1. Find the length of the longest palindrome in a string 59 | 2. Giving an integer and return the maximum product of the numbers which sums up to the given number. 60 | 3. Write a program that raises x to the power of y 61 | 4. Knapsack problem 62 | 5. Recursively find the shortest valid path from one point to another in an array (basically solve a maze). 63 | 6. What is quick sort? 64 | 7. Insert "," to int 65 | 8. Create all unique strings using some alphabets 66 | 9. Use spaces as the delimiters, reverse each word given by the first step then reverse the whole sentence 67 | 10. Convert a string of digits into a float. 68 | 69 | 70 | * Design 71 | 72 | 1. Design an IDE 73 | 2. Design the touchButton function in iOS 74 | 3. How would you design an application for blind people? 75 | 4. Design Twitter 76 | 5. Design bit.ly 77 | 78 | 79 | 80 | 81 | TBC.. 82 | 83 | 84 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 George Linut 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MathRelatedProblems/KRootAprroximation.py: -------------------------------------------------------------------------------- 1 | function root(x, n, error): 2 | if (x == 0): 3 | return 0 4 | 5 | left = 0 6 | right = max(1, x) 7 | middle = (right + left) / 2 8 | 9 | while (middle - left >= error): 10 | if (power(middle, n) > x): 11 | right = middle 12 | else if (power(middle, n) < x): 13 | left = middle 14 | else 15 | break 16 | 17 | middle = (right + left) / 2 18 | 19 | return middle -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodingInterviewTipsAndTricks 2 | 3 | Resources, solved problems and references for interview practice. 4 | 5 | # Part 1: Classic problems 6 | 7 | These are the problems that you should solve before an interview. 8 | Knowing the best solution for these problem may give you idea for more complex prblems. 9 | 10 | In the following I will give a few examples of "classic" problems (you can also find the python implementation in this repository) 11 | Some of these problems appear difficult the first time you read them but if you understand the "suggested" solution for them 12 | you will be able to solve it very quickly in the next coding interview. 13 | 14 | The first problem that we will solve is usually asked as a warm up question in technical interviews 15 | 16 | Classic Problem no. 0: You are given a list of n-1 integers and these integers are in the range of 1 to n. 17 | There are no duplicates in list. One of the integers is missing in the list. 18 | 19 | How do you find the missing number as quickly as possible? 20 | Of course you can add all the numbers in the interval and substract the sum of the given numbers and you will find the missing one. 21 | But that is not very interesting so the proposed solution is using bit operations (a must read subject before an interview). 22 | The operation that we will use is Xor. 23 | 24 | Fact: If we xor a number with itself the result will be 0 as thew binary representation is identical. We also observ that 0 25 | is a neutral element for the Xor operation since 0 xor 0 = 0 and 1 xor 0 = 0 26 | 27 | Using those observations we can see that if we xor all the elements that are given with all the elements in the interval [1,n] 28 | we will have pairs, 1 xor 1 = 0, 2 xor 2 = 0... n xor n = 0 , the only element that will not have a pair is the missing one. 29 | So the result of this operation is the missing element xor a lot of 0's but since 0 is the neutral element we are left with the answer. 30 | 31 | Short version of the solution discussed above: 32 | Input: a, an array of lenght n-1 with numbers in [1,n] 33 | R1 = a[0] xor a[1] xor a[n-1] 34 | R2 = 1 xor 2... xor n 35 | R3 = R1 xor R2 = the missing number 36 | 37 | The set of "classic" problems that we will solve uses one of the most used data structures in interviews, the Linked List. 38 | Languages such as Java or C# have their own implementation for the linked list but is good practice to implement your own. 39 | 40 | Classic Problem no. 1: Find the "middle" of a linked list. 41 | Classic Problem no. 2: Detect a cycle in a linked list. 42 | 43 | The general approach for these two problems is very similar. 44 | Use 2 pointers instead of one and give them diffent speed! 45 | 46 | If you want to find the middle of the list you need move a pointer two noded every time you move the other one once. 47 | When the first pointer reaches the end of the list the second one is at the middle (for n = 2k+1 nodes, otherwise he is at k+1 and we can consider the previous node to as the middle) 48 | (detect_list_middle.py) 49 | 50 | If you want to detect a cycle use the same approach but in this case the first pointer will never reach the end if there is a cycle 51 | so the first time you have both pointers at the same node you detected the cycle.(detect_list_cycle).py) 52 | 53 | The complexity for both solutions is O(N) time and O(1) memory.(we can detect a cycle with only one pointer but it will require O(N) memory). 54 | 55 | To be continued... 56 | 57 | # Part 2: Classic solutions 58 | 59 | Classic Solution no. 1: Use a HashMap 60 | To quote Gayle Laakmann(the author of Cracking the Coding Interview) the Hashmap should be on top of your mind whenever you are solving an interview question. 61 | It's the magic weapon with "almost" O(1) get and O(1) update operations. 62 | 63 | Classic Solution no. 2: Binary search or smth like it 64 | 65 | Problems that demand a certain numeric value with rounding error are usually a hint that binary search is involved. 66 | For example find the K order root of a number N can be solved by starting with 0 and the number (or 1 if the number is less than 1). 67 | You just have to compare middle^K with N to see i which way you have to shift the interval and the problem is over. 68 | Another exit condition can be that your interval is less than the maximum error defined in the problem. 69 | Python implmentation can be find in MathRelatedProblems/KRootAprroximation.py. 70 | -------------------------------------------------------------------------------- /StringProblems/README.md: -------------------------------------------------------------------------------- 1 | # Strings. 2 | String related problems are very common at codind interviews. 3 | There are string problems that you can solve in one line and string problems that require 4 | knowledge about algorithms such as KMP to have the desired complexity. 5 | We will give examples of string problems within large range of difficulty. 6 | 7 | # Part 1. 8 | 9 | For the first round of interviews you won't get difficult problems, they are meant to test your speed 10 | and your proficiency in the language you selected (Java, Python). 11 | 12 | 1. String compression: transform "aaaabbc" -> "a4b2c1" (string_compression.py) 13 | 2. Remove duplicates: "interviewRepository" -> "intervwrRposy" (string_duplicates.py) 14 | 3. Detect the position of anagrams for a given string and pattern -> "abcbatttab" -> [0,3,8] (pattern_anagram.py) 15 | -------------------------------------------------------------------------------- /StringProblems/pattern_anagram.py: -------------------------------------------------------------------------------- 1 | def compare(d1, d2): 2 | for k in d1.keys(): 3 | if k not in d2: 4 | return False 5 | if d1[k] != d2[k]: 6 | return False 7 | return True 8 | 9 | 10 | def find_anagram_position(text, p): 11 | if len(p) > len(text) or len(text) == 0 or len(p) == 0: 12 | return ":P" 13 | 14 | dp = {} 15 | window_d = {} 16 | index = 0 17 | while index < len(p): 18 | if p[index] in dp.keys(): 19 | dp[p[index]] += 1 20 | else: 21 | dp[p[index]] = 1 22 | if text[index] in window_d.keys(): 23 | window_d[text[index]] += 1 24 | else: 25 | window_d[text[index]] = 1 26 | index += 1 27 | if compare(window_d, dp): 28 | print(index - len(p), end="") 29 | 30 | while index < len(text): 31 | if window_d[text[index - len(p)]] > 1: 32 | window_d[text[index - len(p)]] -= 1 33 | else: 34 | window_d.pop(text[index - len(p)]) 35 | if text[index] in window_d.keys(): 36 | window_d[text[index]] += 1 37 | else: 38 | window_d[text[index]] = 1 39 | 40 | if compare(window_d, dp): 41 | print(index - len(p) + 1, end="") 42 | index += 1 43 | 44 | 45 | find_anagram_position("AAABABAA", "AABA") 46 | print() 47 | print("***") 48 | find_anagram_position("BACDGABCDA", "ABCD") 49 | 50 | -------------------------------------------------------------------------------- /StringProblems/string_compression.py: -------------------------------------------------------------------------------- 1 | # Given an array of characters, compress the array in a way such that [aBBBAAaaa] becomes 2 | # [a1B3A2a3]. 3 | 4 | 5 | def str_compress(a): 6 | if len(a) == 0: 7 | return None 8 | s = "" 9 | ch = a[0] 10 | fr = 1 11 | for c in a[1:]: 12 | if c == ch: 13 | fr += 1 14 | else: 15 | s += ch 16 | s += str(fr) 17 | fr = 1 18 | ch = c 19 | 20 | return s + ch + str(fr) 21 | 22 | 23 | print(str_compress(['B', 'B', 'B', 'A', 'A', 'a', 'a', 'a'])) 24 | 25 | -------------------------------------------------------------------------------- /StringProblems/string_duplicates.py: -------------------------------------------------------------------------------- 1 | def rem_dup(text): 2 | d = {} 3 | res = "" 4 | for ch in text: 5 | if ch not in d.keys(): 6 | d[ch] = 1 7 | res += ch 8 | else: 9 | d[ch] += 1 10 | return res 11 | 12 | -------------------------------------------------------------------------------- /cool.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | """ 7 | 8 | def rotate(matrix): 9 | 10 | return [list(x[::-1]) for x in zip(*matrix)] 11 | 12 | 13 | print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) 14 | 15 | """ 16 | [1, 2, 3], [4, 5, 6], [7, 8, 9]] ----> [[7, 4, 1], [8, 5, 2], [9, 6, 3]] 17 | 18 | """ 19 | --------------------------------------------------------------------------------