<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by mohycs on Medium]]></title>
        <description><![CDATA[Stories by mohycs on Medium]]></description>
        <link>https://medium.com/@mohycs?source=rss-af35271d6b48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qjnHfc3O9bN_UfjxfsMTsw.jpeg</url>
            <title>Stories by mohycs on Medium</title>
            <link>https://medium.com/@mohycs?source=rss-af35271d6b48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:16:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohycs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Crack the Coding Interview: The 7 Phases of Interview Prep]]></title>
            <link>https://mohycs.medium.com/how-to-crack-the-coding-interview-the-7-phases-of-interview-prep-975569fbc410?source=rss-af35271d6b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/975569fbc410</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[faang-interview-prep]]></category>
            <category><![CDATA[cracking-coding-interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[coding-interview-problems]]></category>
            <dc:creator><![CDATA[mohycs]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 23:28:36 GMT</pubDate>
            <atom:updated>2023-07-30T00:04:05.897Z</atom:updated>
            <content:encoded><![CDATA[<p>Preparing for Coding Interviews can seem long and complicated when there is no clear path for studying or measuring your progress. This article attempts to build a clear roadmap such that anyone can interview prep thoughtfully and carefully over a period of 2–3 months or less. When I was interview prepping, it started off as doing random problems and slowly learning different concepts. I used to always give the age-old advice of “practice more problems” for anyone that needed help. In hindsight, these were the actual steps I took to get 3 offers from FAANGMULA, and avoid the hassle of random “leetcode grinding”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btkY7oMTNv40Jv2-2yO_jg.png" /><figcaption>The 7 Phases of Coding Interview Prep by MohyCS</figcaption></figure><blockquote>Here is a TikTok summarizing this article, but read on for more value + detail.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.tiktok.com%2Fembed%2Fv2%2F7258200304720743726&amp;display_name=tiktok&amp;url=https%3A%2F%2Fwww.tiktok.com%2F%40mohycs%2Fvideo%2F7258200304720743726&amp;image=https%3A%2F%2Fp16-sign.tiktokcdn-us.com%2Ftos-useast5-p-0068-tx%2FosBapnoIuuekDfabEgS0hSkbnlRPuAYLDQTBC5%7Etplv-dmt-logom%3Atos-useast5-i-0068-tx%2F77cad5ae8dd545e1984ad32435571c76.image%3Fx-expires%3D1690466400%26x-signature%3DMtGOBfWaOKnnp0uyAFlMTE%252BgovA%253D&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tiktok" width="340" height="700" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbb6508f4d8a3792caa4f6145aa14ad3/href">https://medium.com/media/dbb6508f4d8a3792caa4f6145aa14ad3/href</a></iframe><h3>🧑‍💻 ↔️ 👩‍💻 Phase 1) Understand the Interview Process: From Both Perspectives</h3><p>I like to view these interviews as a bit of a game. Before you succeed in any game, we have to understand the rules and criteria to win. This step is simple, and starts with the following questions:</p><blockquote>“How does the interviewer judge my performance to make a Hire VS No-Hire Decision?”</blockquote><blockquote>“What skills should be displayed in the interview to satisfy the Interviewer?”</blockquote><blockquote>“How do I effectively practice those skills before the game starts?”</blockquote><p>Most candidates cannot answer the above questions. This lack of understanding leads to the general frustration behind Coding Interviews being seen as “broken”.</p><p>This also leads to another assumption: “To pass the interview, you need the absolute optimal answer and flawless code”. This is simply not true.</p><p>These assumptions and frustrations are put on full display when a candidate is rejected, and they immediately think it’s purely based on optimality of their solution. This can be a factor but it is not the single deciding factor.</p><p>Lack of understanding also leads to endless “leetcode grinding”. Solving a lot of algorithm questions is beneficial but not satisfactory. I have spoken with candidates that have practiced 200+ questions, yet still fail interviews consistently. Why is this the case? There is a disconnect between an online platform like LeetCode saying your solution “passed”, and an interviewer’s methodology of assessing a Hire VS No-Hire decision.</p><p>If a candidate does extremely well in multiple interviews with multiple job offers, that does not imply the same candidate would be highly ranked in an online platform. How is that possible? Because successful candidates understand the interview process far better than how to win a Competitive Programming contest.</p><p>The goal is to understand the interview process as BOTH a Candidate &amp; Interviewer. Let’s forget everything we know about solving loads of problems online, and understand what skills interviewers are measuring. Take a look at this <em>simplified general</em> <em>rubric</em> used by the interviewer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdQvsKh3gPYhSS5wfh5qNA.jpeg" /><figcaption>Source: Tech Interview Handbook</figcaption></figure><p>Notice how every candidate’s aim of getting the optimal answer is only captured by the Problem Solving section. Which means this alone is not sufficient for passing with a “Hire” decision. There is still weight on Communication, Technical Competency, and Testing. With knowledge on the criteria is for a Strong Hire Decision, let’s dive into how to prep for all 4 factors. You can read about this rubric in more detail at <a href="https://www.techinterviewhandbook.org/">The Tech Interview Handbook</a>.</p><p>For more info on interview expectations by company, check out <em>Cracking the Coding Interview by Gayle Lock McDowell</em> and <em>Elements of Programming Interviews</em>.</p><h3>📖 Phase 2) Review Data Structures</h3><p>The key at this phase is to understand the Pros VS Cons per data structure. Let’s start with which data structures are relevant:</p><ul><li><strong><em>Arrays, Lists, Strings</em></strong></li><li><strong><em>Linked Lists, Stacks, Queues</em></strong></li><li><strong><em>Hash Maps, Hash Sets</em></strong></li><li><strong><em>Heaps, Sorted Maps/Sets</em></strong></li><li><strong><em>Trees, Graphs</em></strong></li></ul><p>The Pros VS Cons for each can be determined by the following:</p><ul><li><strong><em>Time Complexity for Operations: Search, Add, Update, Delete.</em></strong></li><li><strong><em>Space Complexity for Storing Elements and Relevant Ordering.</em></strong></li></ul><p>You can then contextualize when to use one data structure over another, which improves Problem Solving. For example, HashMaps are great for operations with O(1) Time Complexity and pairing unique keys to values. There is no particular ordering or sorted-ness to these key/value pairs. Heaps are great at maintaining elements in sorted order, but adding and removing the next element takes O(log(n)) Time.</p><p>Therefore, any problem that requires values to be sorted should remind us of Heaps. If instead we need quick lookups, consider using HashMaps. <em>You instantly have an intuition for which data structures may be relevant to the problem being solved.</em></p><blockquote><strong>How do I fully understand and remember this for EVERY Data Structure? <em>😑</em></strong></blockquote><p>Most would suggest reading about how they work under the hood, and that is a necessary step. I prefer to aim for long-term retention instead of a quick “memorize and forget” approach. Most likely you will interview multiple times throughout your career and re-use this material.</p><p><strong>What’s more practical is implementing them from scratch in the language of your choice.</strong> <em>For example, create a Linked List Class that allows for searching, adding, and deleting elements. Re-use your code to build your own version of a Stack. Do it again to implement a Queue. Now implement a Doubly Linked List. </em>Tada! You have implemented 4 data structures without any existing implementations.</p><p><strong>This provides a clear understanding of the Time and Space Complexities for all 4 operations: <em>search, add, update, delete</em></strong>. As a bonus, some interviewers will flat out ask, “How do HashMaps search in O(1) Time”. I call this, <em>Data Structure Trivia</em>, since you either know it or you don’t. These are trivial questions once this phase is complete.</p><h3>🧠 Phase 3) Practice Algorithmic Thinking</h3><p>Now you are equipped to start practicing some coding questions, and the data structures will serve as your toolkit. Here’s a list of Online Coding Platforms I used along the way.</p><ul><li>LeetCode</li><li>CodeSignal</li><li>Codility</li><li>HackerRank</li></ul><p>In total you have <strong><em>thousands</em></strong> of questions to choose from but who has time for that? Fortunately, interviewers across many companies stick to a dozen or so topics. Which site you use is nowhere near as important as the problems practiced themselves. Here’s a list of topics sorted from Easiest to Hardest (in my opinion).</p><ul><li>Two Pointers</li><li>Binary Search</li><li>Sliding Window</li><li>Fast + Slow Pointers</li><li>Sorting</li><li>Merging Intervals</li><li>Linked List Reversal</li><li>BFS</li><li>Recursion</li><li>DFS</li><li>Topological Sort</li><li>Memoization</li><li>DP</li></ul><p>To be fair, the list is actually longer because some topics have nested sub-topics. <strong><em>Sorting </em></strong>consists of different algorithms like: <strong><em>Bubble Sort, Merge Sort, Quick Sort, Heap Sort, Bucket Sort, etc. </em></strong>By filtering questions on these high level topics we can learn each of the sub-topics along the way. Memoization and DP are at the absolute bottom since they are so rarely asked and the most challenging for most candidates.</p><p>For each category, target attempting 10 questions composed of 3 Easy and 7 Medium. There’s no need to worry about Hard problems initially until Mediums seem fairly easy.</p><p><em>You can also rely on different lists online like Blind 75, Grind 75, LeetCode 100, and NeetCode 150. These lists are fairly similar and based on the same topics, so don’t think too hard on which list to do. Just get started.</em></p><h3>⚡️ Phase 4) Grasping Patterns &amp; Concepts</h3><blockquote>Pattern Recognition can make Coding Interviews twice as easy.</blockquote><p>The goal of this phase is to improve [Problem Solving + Coding] <strong><em>Speed</em></strong>. It’s great that over time your skills are improving, but speed is crucial. This is necessary since interviews often last 40 minutes or less.</p><p>First, we can <strong>pattern match the type of question</strong> to instantly categorize it against one of many data structures or algorithms from the prior phases. Then after choosing the appropriate algorithm, we can pattern match the implementation to code it out <strong><em>quickly</em></strong>.</p><p>When I see the need to traverse a grid-like maze, I can recall this fits the category of Graph problems. Boom, data structure identified. A more obvious case is when I have to traverse a Graph or Tree. Then I wonder which algorithms are appropriate, and recall that BFS and DFS are viable for searching Graphs. Finally, I compare how each algorithm performs in Time and Space Complexity to finally choose one. Writing the code does not take very long since BFS + DFS do not have very many ways to implement them.</p><blockquote>How do I improve Pattern Recognition for Problem Solving and Coding?</blockquote><p><strong>Problem Solving:</strong> Take note of the inputs and the wording for each problem. Over time you will realize similar problems rely on similar answers.</p><p><strong>Here are some examples:</strong></p><ol><li>If it mentions finding some connection/path between 2 locations, we can pattern match to a Graph question. Graphs can be solved with BFS or DFS. If it focuses on finding any path, you can go with either BFS or DFS. I would prefer DFS since it is recursive, which implies less lines of code to be written. If there is an emphasis on finding the <em>shortest path</em>, then pick BFS for optimal performance since DFS will be sub-optimal. Ideally we want to visit each node only once to achieve a Time &amp; Space Complexity of O(N). If the graph contains cycles, we must avoid re-visiting nodes by using a Visited Set. If the graph has weighted edges, Dijkstra is needed for finding the Shortest Paths.</li><li>If we need to find the longest/shortest sub-string/array that fulfills a criteria, then Sliding Window may be the answer. To keep track of the start and end of your window, you will need two pointers or indices. Keeping track of the exact values within your window can be done with a Hash Map/Set. There must be a condition to either extend the window on the right side, or decrease the side from the left side. This leads to an algorithm with O(N) Time &amp; Space Complexity.</li></ol><p><strong>Coding: </strong>Since similar problems rely on the same set of algorithms, you often <strong><em>re-write the same code</em></strong>. <strong>To improve your coding speed, implement each algorithm in your language of choice.</strong> Then when you attempt to solve a problem and run into errors, quickly reference these templates and course-correct. After multiple repetitions, implementation speed will increase and you will not reference these templates as often. Coding the same algorithms will become a habit requiring very little thought.</p><h4><strong>High-Level Study Habits to maintain during this phase:</strong></h4><ul><li>Set a timer for <strong>30 minutes</strong> while <strong>solving</strong>, and spend another <strong>30+ minutes understanding the solution.</strong></li><li>Aim for <strong>1–3 Easy problems a day, and aim for Mediums after Week 1–2.</strong></li><li><strong>Track problems in a spreadsheet</strong> and categorize them by Data Structure &amp; Algorithm.</li><li><strong>Re-visit 1 Week old questions </strong>assuming you do not recall the solutions.</li><li><strong>Produce your own 3 Test Cases</strong> to work on the <strong>Testing Criteria of the Coding Interview rubric.</strong></li><li>Focus on <strong>comprehending solutions, not memorization.</strong></li></ul><h3>🥋 Phase 5) Simulate via Mock Interviews</h3><p>The interview can be <strong><em>super nerve-racking</em></strong>. It’s a completely different setting from solving problems alone in silence. You have no idea how the interviewer is going to introduce themselves, what questions they’ll ask, or how they will react as you try to solve their technical questions. I used to overthink and wonder, “What do they think about my answer so far” and “Am I typing too slowly? They must think I’m unqualified”. <strong><em>This is what I like to call, Interview Anxiety.</em></strong></p><blockquote>How do I get rid of Interview Anxiety?</blockquote><p>Put yourself in an interview setting 1–2X a week via Mock Interviews. You can do this thru platforms like Pramp &amp; InterviewingIO. Many candidates, from self-taught, to new grads, and even gainfully employed engineers will leverage these platforms to practice interviewing as a skill. Some of the mock interviewers can be very helpful in guiding you, while others are more quiet and leave you to think for yourself. This is great experience for meeting different types of interviewer personalities.</p><p>It’s also great for networking with folks that are also on the job hunt. But I never found it useful for learning new algorithms and data structures, since it can take 1+ hrs. to grasp a new concept. Over time, you will not be concerned about the interviewer’s opinion as you struggle to solve questions. You will be mentally focused on attacking the problem presented and overthink less. You will learn how to communicate your thought process to multiple interviewers.</p><blockquote>Consider how you present yourself to the interviewer by sitting in their seat.</blockquote><p>There is arguably more value added when you act the interviewer, because you can observe any flaws in the candidate. <strong>This goes hand in hand with “Phase 1) Understand the Interview Process from Both Perspectives”</strong>.</p><p>For example, I noticed many candidates do not ask clarifying questions about the problem. This observation led me to consider whether I make the same mistake in my actual interviews. You are effectively learning from other people’s mistakes, and making sure to avoid them yourself. <strong>The main skills you will observe go back to the Coding Interview Rubric mentioned at the start: Communication, Problem Solving, Technical Competency, and Testing.</strong></p><h3>👂 Phase 6) Feedback &amp; Self-Reflect</h3><p>With every Mock Interview, analyze the rating you receive for the 4 Criteria on the rubric. Most candidates do a reasonable job at Communication, but struggle with the rest. Problem Solving has to be the most difficult criteria to meet, since it helps find and compare multiple solutions. With a reasonable solution, we can proceed to start Coding and Testing. Otherwise, poor Problem Solving puts the candidate’s progress to a halt and it’s difficult to starting Coding without any approach..</p><p>Analyze the following to properly self-reflect:</p><ol><li>Do I <strong>fully clarify the problem</strong> from the start of the interview?</li><li>Did I <strong>fail any unexpected test cases</strong> and could I have thought of them beforhand?</li><li>How much <strong><em>time</em></strong> do I spend trying to Problem Solve? How much is spent on Coding? Which step took the longest?</li><li>Which<strong> categories of problems</strong> are the most difficult to Problem Solve? Maybe it’s time to revisit them.</li><li>Which <strong>algorithms</strong> do I struggle to Code? Perhaps I do not fully understand them and need to review.</li><li>Did I <strong><em>provide multiple solutions</em></strong> from brute force to optimal?</li><li>Can I <strong>explain the Time &amp; Space Complexity</strong> of any solutions?</li><li>Out of the 4 criteria from the Coding Interview Rubric, <strong><em>where was most of my time spent</em></strong> during the mock interview?</li><li>What is the <strong><em>consistent negative &amp; positive feedback</em></strong> received over multiple interviews?</li><li>How can I <strong><em>think about this new problem differently</em></strong> to come to the same solution <strong><em>faster</em></strong>?</li></ol><p>These questions will help you focus on your weaknesses and what problems to re-visit for review. With each and every mock interview, you’ll notice less mistakes being made because you are cognizant of the initial mistakes and took action to improve them. This is also why mock interviews should not be done daily, because time is needed to improve on mistakes.</p><p>Without proper self-reflection and analysis, you may find little to no improvement in mock interviews over the long term. This will lead to frustration and a sense of unfairness. Which is why this is critical to the final phase.</p><h3>🥊 Phase 7) Interview for Technical Roles</h3><p>This phase is essentially a combination of the 5th + 6th phases, but this time real offers are at stake. The goal is not to necessarily pass the interview process, but to see how far we can get given the amount of time spent prepping. This means passing the Online Assessment, Technical Phone Screen, and finally a panel of interviewers during the On-Site (which may be virtual).</p><p>Irrespective of how good or bad these rounds go, take note of the questions being asked, the answers you provide, and all follow up questions. After the interview, review and see if there was a better answer you could have provided. If you receive a rejection, most definitely the only factor you can improve on is the quality of your answers. This is fully in your control to improve on. Ignore the interviewer’s demeanor if they were having a bad day, because that is always outside of your control.</p><p>Compare your performance against the Coding Interview Rubric. This should be a fairly easy task since you’ve been self-reflecting for weeks over many mock interviews and making adjustments. Simply repeat this process and make new adjustments in between each round of the interview. Implement these new adjustments in Mock Interviews to prepare for the next technical role.</p><p>Last thing to note, pay attention to any nuance in the way each company conducts their interviews. Culture has an impact on the way interviewers interact with candidates and the types of questions being tested.</p><blockquote>For example, Meta asks 2 Medium level questions per round which leads to very little small talk and a greater focus on problem solving and coding speed. Some of their questions may not have super intuitive answers like, Next Permutation. But they do not shy away from asking interview questions that have been exposed online.</blockquote><blockquote>Meanwhile, Microsoft asks less challenging questions that are more popular/known. From my experience, Microsoft Engineers are more sociable in treating candidates like teammates and stick to easier concepts like HashMaps and Linked Lists.</blockquote><blockquote>Amazon has a a greater focus on Behavioral questions (a.k.a. Leadership Principles) and so technical skills alone are insufficient. Amazon Engineers are more willing to disagree and challenge candidates on answers provided.</blockquote><blockquote>Over time you will recognize slight differences in the way companies perform interviews. Of course, these comparisons are anecdotal based on my experience. Be sure to draw these comparisons yourself.</blockquote><p>If the recruiter sends you a rejection, ask for feedback. Most likely, none will be provided since you can sue over discriminatory hiring practices. However, every now and then one recruiter is willing to help you out.</p><p>Sometimes it can just be a numbers game. You can be a terrible candidate with 1/10 chance of receiving an offer, but if 20 companies reach out then that offer is bound to come soon. On the other hand, if you hardly get contacted for roles, you have to be more analytical about where you are performing well and what needs improvement to get a high success rate over few opportunities.</p><h3>🏆 Celebrate the Offers 💰</h3><p>All of these phases may seem over the top, time consuming, and difficult. I believe it is all worth it when you can receive not just 1 or 2 but 3+ offers. At this stage, companies have to appeal to the candidate for a signature on the dotted line, which means you can negotiate compensation.</p><p>The only thing to to keep in mind is this will not be the last time you go through these 7 phases. The company you join may not have a rigorous engineering culture, or maybe the project work is uninteresting. You can always leave for any number of reasons, and the company can perform mass lay-offs.</p><p>Every now and then, you will find a post on Reddit or Blind from a Senior Software Engineer that wants to leave their workplace without sacrificing their compensation. But they have no motivation to go through the interview process as they’ve forgotten many of the concepts learned. They are essentially stuck at their employer. The point is you do not want to be that person. View this interview process as a game that hardly changes over time. What I mean is, a Binary Search question today will probably repeat itself again in a few years with some slight re-wording. The same Data Structures and Algorithms are static.</p><p><strong><em>The 7 Phases are inescapable.</em></strong> <em>Over time, technical interviews will include Object Oriented Design, System Design, and Behavioral/Leadership especially when you interview for higher levels.</em></p><blockquote>Ultimately the interview prep process is the same: Learn the Game, Practice the Problems, Interview &amp; Reflect, Repeat.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=975569fbc410" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hashing Basics]]></title>
            <link>https://mohycs.medium.com/hashing-basics-964670a2a956?source=rss-af35271d6b48------2</link>
            <guid isPermaLink="false">https://medium.com/p/964670a2a956</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[mohycs]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 21:25:17 GMT</pubDate>
            <atom:updated>2023-07-30T00:34:22.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Hashing?</h3><p>Hashing is an important Data Structure, which is designed to use a hash function that maps a given element to a particular key for faster access. Imagine having a set of elements/values you would like to not only store, but also access quickly. We could store such elements in a list, and access them later via a linear search. However, a linear search take O(n) time, where n = number of elements. Also, storing more elements results in a longer linear search. Rather than simply appending each element to our list, we can intelligently choose an index for each element, which can be later accessed immediately in O(1) time.</p><h3>Basic Hashing Exercise</h3><p>Take the simple example of storing integers from 1 to 10 in an array of length 10. We could simply store these integers in any order we would like, but it is smarter to write a hash function to determine the index for each integer. Ideally, we would like the integer 1 to be stored at index 0, and integer 2 to be stored at index 1, and so on . . . until integer 10 is stored at index 9.</p><h3>Choosing Hashing Functions</h3><p>We might be tempted to think that our hash function for any integer x is simply: <em>H(x) = x-1</em>. Now when x = 1, we place it at index 0 and when X = 10, we place it at index 9. But what happens when unexpected integers are added such as 11, 0, and -1? Our primitive hash function is going to calculate a key/index that is out of bounds, because our array is only of size 10. Increasing the size of the array can help mitigate larger X values but now our array is growing in size. We need a more intelligent hash function that does not depend on a lower and upper bound of input so that:</p><p>A) Hash function considers future input scale.</p><p>B) The Array size does not increase beyond necessity.</p><p>So why not use the following hash function: <strong>H(x) = x % 10. </strong>Notice that we are now using the modulo operator by the size of our array. In this case, when x = 0, our key/index is now 0. For x = 1 our resulting key/index is now also 1. For x = 2, the resulting key/index is also 2. For x = 10, our resulting key/index is not 10, but it is 0 since there is no remainder. Even if our input x is larger than 10, say x = 11, then the resulting key/index goes back to 1. Throw an even larger input such as x = 100, and it is clear that the resulting key is still within bounds. For negative integers, the result is always positive but we can make the function more clear by stating:</p><p><strong>H(x) = | x | % 10</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZMZVle0_OYnjeiEipsW8A.png" /><figcaption>Image credited to GeeksForGeeks</figcaption></figure><h3>Handling Collisions</h3><p>Given that the array is of size 10 &amp; the improved hash function, what happens when two integers map to the same key? Both 0 and 10 map to index 0, and each index can only hold one element. The dilemma of having 2 elements map to the same key is known as a <strong>collision. </strong>We want to store both 0 and 10 safely via chaining.</p><p><strong>Chaining</strong> is having each cell of the hash table point to a linked list of elements that have the same hash function key. In this case, both 0 and 10 can reside in the same cell as a linked list. However, this solution can compromise our fast search time. What if the integers we have to store all happen to map to index 0? We now end up with one linked list of many values. When all N elements map to the same index, we can re-calculate the index of any element in O(1) time, but finding the chosen element in a linked list takes O(N) time. It is the same as performing a linear search on an array, so this hashtable is not as efficient as intended.</p><p><strong>Advantages:</strong><br>1) Simple to implement.<br>2) Hash table never fills up, we can always add more elements to the chain/list.<br>3) Less sensitive to the hash function or load factors.<br>4) It is mostly used when it is unknown how many and how frequently keys may be inserted or deleted.</p><p><strong>Disadvantages:</strong><br>1) Cache performance of chaining is not good as keys are stored using a linked list. Open addressing provides better cache performance as everything is stored in the same table.<br>2) Waste of Space (Some cells of hash table are never used)<br>3) If the chain becomes long, then search time can become O(N) in the worst case.<br>4) Uses extra space for Linked List objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*ex-8Y-kg5O2KOgVBapmpPg.png" /></figure><h4>Hashing Performance</h4><p>We can evaluate the performance of our hashing function and data structure by the following:</p><pre>m = Size of hash table<br> n = Number of keys to be inserted in hash table<br> <br> Load factor α = n/m <br>  <br> Expected time to search = O(1 + α)<br> <br> Expected time to insert/delete = O(1 + α)</pre><pre> Time complexity of search, insertion and deletion is <br> O(1) if α is O(1)</pre><p>The load factor represents the average number of keys placed in each index/cell.</p><h3>Where is Hashing used?</h3><h3>Microsoft Azure</h3><p>Hashing does have a very practical use case, specifically for storing and accessing repeatedly used values. In fact, <strong>Azure Cache </strong>for <strong>Redis</strong> utilizes hashing to accomplish this. As a result, Azure Cache improves the performance and scalability of systems that rely heavily on backend data-stores. The cache temporarily copies frequently accessed data to a hash table. This fast storage is located in-memory with Azure Cache for Redis instead of being re-loaded from disk by a database. Application performance is improved by taking advantage of the low-latency, high-throughput performance of the Redis engine.</p><p><strong>Loading Web Pages Faster</strong></p><p>Most web pages are generated from templates with headers, footers, toolbars, menus, etc. They don’t actually change often and should not be generated dynamically. Using an in-memory cache, like Azure Cache for Redis, will give your web servers quick access to this type of static content compared to backend datastores. This pattern reduces processing time and server load that would be required to generate content dynamically, saving cloud users cost and execution time. This allows web servers to be more responsive, and can allow you to reduce the number of servers needed to handle loads.</p><p><strong>Storing User Session</strong></p><p>Storing too much in a cookie can have a negative impact on performance as the cookie size grows and is passed and validated with every request. A typical solution is to use the cookie as a key to query the data in a backend database. How can we reduce the number of queries made to a database? Using an in-memory cache, like Azure Cache for Redis, to associate information with a user is much faster than interacting with a full relational database.</p><p>Another more common case, is choosing to store an API response and other essential objects related to the user’s session. These can be stored in a persisting HashMap, that is inserted into other classes via dependency injection. Developers can pre-determine which Strings can act as the key for each expected object, then get them from the HashMap, instead of re-executing API calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*fOChqICZ22uYqLOzK5iZcg.png" /><figcaption>Image credited to Microsoft</figcaption></figure><h3>Database Management Systems</h3><p>When we are forced to interact with a backend data store, in most cases the DBMS is also implementing hashing! Hashing is used to directly search the location of desired data on the disk without using an index structure. Data is stored in the form of data blocks whose address is generated by applying a hash function in the memory location where these records are stored, known as a data block or data bucket.</p><p>Here, are the situations in the DBMS where you need to apply the Hashing method:</p><ul><li>For a huge database structure, it’s tough to search all the index values through all its level and then you need to reach the destination data block to get the desired data. This is a case where linear search results in poor performance.</li><li>Hashing method is used to index and retrieve items in a database as it is faster to search that specific item using the shorter hashed key instead of using its original value.</li><li>Hashing is an ideal method to calculate the direct location of a data record on the disk without using index structure.</li><li>It is also a helpful technique for implementing dictionaries.</li></ul><h3>Hashing for Justice: Microsoft’s PhotoDNA</h3><p>In 2009, Microsoft partnered with Dartmouth College to develop PhotoDNA, a technology that aids in finding and removing known images of child exploitation. Today, PhotoDNA is used by organizations around the world and has assisted in the detection, disruption, and reporting of millions of child exploitation images.</p><p><strong>How does PhotoDNA accomplish this complicated task?</strong></p><p>PhotoDNA creates a unique digital signature (known as a “hash”) of an image which is then compared against signatures (hashes) of other photos to find copies of the same image. When matched with a database containing hashes of previously identified illegal images, PhotoDNA is an incredible tool to help detect, disrupt and report the distribution of child exploitation material. PhotoDNA is not facial recognition software and cannot be used to identify a person or object in an image. A PhotoDNA hash is not reversible, and therefore cannot be used to recreate an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHf8-DdBrmdKO05fl1mo7A.png" /><figcaption>Image credited to Microsoft</figcaption></figure><p>Prior to PhotoDNA’s inception, law enforcement had to manually compare new images found online to pre-existing images and determine whether they were new or duplicates. Even if an existing image is cropped or discolored, PhotoDNA is capable of detecting whether it is new or not.</p><h3>Types of Hashing Data Structures</h3><p>Now that we understand the use cases for hashing, we can consider different data structures that already do the heavy lifting of hashing for us.</p><h3>HashMaps</h3><p>The HashMap will map a given key to a given value, and allow for fast lookup later on. This allows the user to choose any key for their values, while keeping in mind that there is a 1:1 mapping relationship. It also takes care of constructing a hash function. We have the following basic operations:</p><p><strong>get(key) -&gt; returns the value associated with the given key (returns null if key was never added with a value)</strong></p><p><strong>add(key, value) -&gt; stores the given key and value as a pair</strong></p><p>However, one issue with the HashMap is iterating over each (key, value) pair will not guarantee any particular order.</p><p>For example, say we have a HashMap containing Character to Integer pairs. We can insert (‘b’, 5), (‘a’, 3), and (‘c’, 6) in that order. However, if we iterate thru this map and print each pair, there is no guarantee that all 3 pairs would print in the same order they were added. The HashMap gives no control on ordering every pair, only quick insertion and search.</p><p>The HashMap may internally end up looking like this:</p><p><strong>HashMap {</strong></p><p><strong>‘a’ : 3</strong></p><p><strong>‘b’ : 5</strong></p><p><strong>‘c’ : 6</strong></p><p><strong>}</strong></p><h3>Linked HashMaps</h3><p>Linked HashMaps take care of this ordering issue. When we iterate over the map and print each pair, the order is maintained relative to our insertions. This Map implementation is more favorable when ordering matters and iteration will be used later on. We can think of a Linked HashMap as being a combination of a Linked List, since it maintains ordering by insertion, and a HashMap, due to the quick insertion and search time.</p><p>Internally, our Linked HashMap will look like this:</p><p><strong>Linked HashMap {</strong></p><p><strong>‘b’ : 5</strong></p><p><strong>‘a’ : 3</strong></p><p><strong>‘c’ : 6</strong></p><p><strong>}</strong></p><h3>TreeMap</h3><p>What if we are more picky about the ordering of pairs? We may decide that the pairs should be sorted by their keys in ascending order. In this case, a TreeMap is appropriate. We can decide how pairs are ordered (ascending/descending), and print each pair based on that criteria. However, we pay a cost of time needed to sort each pair. Internally, the TreeMap uses a Red Black Tree to maintain sorted order. Trees &amp; Sorting can be covered in another article. The main point is that<strong> inserting &amp; searching one pair</strong> into the TreeMap takes <strong>log(N)</strong> time. After adding <strong>N elements/pairs</strong>, this takes up <strong>N*log(N)</strong> time.</p><p>The two previous Map implementations take up <strong>O(1) time per insertion &amp; search</strong>, and thus <strong>O(N) time to insert N elements</strong> (making them faster). Because of this time difference, TreeMaps should only be used when sorting is absolutely necessary.</p><p>If we decided that our TreeMap will store pairs by keys in descending order, then it will look like this:</p><p><strong>TreeMap {</strong></p><p><strong>‘c’ : 6</strong></p><p><strong>‘b’ : 5</strong></p><p><strong>‘a’ : 3</strong></p><p><strong>}</strong></p><h3>Concurrent HashMaps</h3><p>Concurrent HashMaps behave similarly to regular HashMaps, while including support for concurrency. If multiple threads tried to read and write to a regular hashmap, they may end up accessing the same index and this can eventually lead to a deadlock. More specifically, if Thread A tries to put data in index K, and at same time Thread B tries to read data from index K, we will go into an infinite loop. The Concurrent HashMap allows multiple threads to access it at the same time, just like the HashMap. However, now each thread locks the exact bucket/index being operated on. In this case, no two threads can access the same key at the same time which solves the infinite loop issue.</p><p>Now that we have a fundamental understanding of hashing data structures, let’s solve some commonly asked problems! Consider the Map &amp; Set Implementations available in your language of choice and which types of Maps are most useful for each scenario. Sometimes a map may not be needed, but the concept of hashing is useful for gaining the optimal solution.</p><h3>Exercises:</h3><p>1) <strong>Duplicate Image Problem</strong>: You have thousands of images in your Pictures folder., some of which may be duplicates. After reading each image, write an algorithm that identifies which files are in fact duplicates.</p><p>2) <strong>Employee Ranking Search Problem</strong>: Given a list of Employees, each containing a name and rank, sort them by rank in ascending order for your company and provide a feature that lets users quickly look up an employee by rank.</p><p>3) <strong>Letter Frequency Problem</strong>: Given a string of lowercase characters, print each unique character followed by its frequency. The order of these characters must be in the same order they occur in the given string</p><pre>Input: str = “avanade”<br>Output: a3 v1 n1 d1 e1</pre><p>4) <strong>Check Permutation Problem</strong>: Given two strings (containing only lowercase characters), determine whether they are valid permutations. A permutation is a way in which a set of things can be arranged. Both strings should have the exact same set of characters and the same frequency per character.</p><pre>Example: &quot;happy&quot; and &quot;paphy&quot; are permutations of each other<br>since both contain the exact same set of characters in common...<br>1 h<br>1 a<br>1 y<br>2 p</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964670a2a956" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>