<?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 Madhumitha Raghu on Medium]]></title>
        <description><![CDATA[Stories by Madhumitha Raghu on Medium]]></description>
        <link>https://medium.com/@madhumitha-raghu1106?source=rss-671814eb937f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Js9TJTzMHpKJL8CoJpzsJA.jpeg</url>
            <title>Stories by Madhumitha Raghu on Medium</title>
            <link>https://medium.com/@madhumitha-raghu1106?source=rss-671814eb937f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 19:59:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhumitha-raghu1106/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[Break an egg!]]></title>
            <link>https://medium.com/codex/break-an-egg-64f97e476712?source=rss-671814eb937f------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f97e476712</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[egg-drop]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Madhumitha Raghu]]></dc:creator>
            <pubDate>Mon, 24 May 2021 00:06:56 GMT</pubDate>
            <atom:updated>2021-05-24T20:18:30.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*lQAlKpst4T2u8Oe26IGx2Q.png" /><figcaption>k eggs and a building with n floors</figcaption></figure><h3>Problem statement</h3><p>This is a very popular math puzzle (<a href="https://leetcode.com/problems/super-egg-drop/">Leetcode</a>). You are given ‘k’ identical eggs and you have access to a building with ‘n’ floors. You can move up the floors of this building and drop an egg. If the egg breaks at the current floor ‘x’, then it will break at all floors above ‘x’. If the egg breaks, you must discard it. If the egg does not break at the current floor ‘x’, then it also won’t break at any floor below ‘x’. We call ‘x’ the critical floor. You need to determine ‘x’ <strong><em>with certainty, by taking the minimum number of moves</em></strong>.</p><p>There are many blog posts available online that describe the approach to solving this problem. In this post, I would like to do a deep dive to understand the mathematical intuition behind the solution to this problem. After that, I will delve into the programmatic approach to analyze what the recurrence relation is trying to accomplish. It is a little lengthy! But, after reading this, you will have more clarity on why this approach works and why it’s awesome. So, let’s get started!</p><h3>Mathematical intuition to the problem</h3><p>If we had just 1 egg, this problem is not that interesting. This is because the minimum number of moves will be ’n’ — We need to drop the egg at every floor from 1 to ‘n’ to determine the critical floor. This is because we need to be able to determine the critical floor <strong><em>with certainty</em></strong> and we can’t afford to lose the egg and speculate.</p><p>Suppose we have 2 eggs, we have an additional egg to spare! So, we don’t have to take the 1 to ’n’ approach. We need to figure two things out:</p><p>a) Which floor should we start with?</p><p>b) If the egg does not break, which floor should we proceed to?</p><p>To answer this, let us assume simple values for ’n’ and ‘k’. Consider a building with 10 floors (’n’) and we have 2 eggs (‘k’). Say, I randomly decide to start at floor 3 and move in increments of 3, i.e. floor3-&gt;floor6-&gt;floor9-&gt;floor10. The following diagram describes the different moves possible with this configuration. Each node represents a floor number. ‘t’ refers to the trial number (when we break an egg) and ‘tmax’ refers to the maximum number of moves for each configuration we can take. The picture on the arrow shows the number of eggs we have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGEwXbSjgv_NWrA3n3l3qA.png" /><figcaption>Fig 1. Consequence of throwing egg at floors 3,6,9 and 10</figcaption></figure><p>Fig 2. below highlights what happens when the egg breaks on floors 3 and 6. At each node, we have 2 possibilities — if the egg breaks, we explore the lower floors (shown to the right of the node) and if the egg does not break, we explore the higher floors (shown below the current node). The nodes highlighted in green correspond to the floors where our next moves should be, after the egg breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6Svv8XtFr3cs_ITGbAcvg.png" /><figcaption>Fig 2. Visualizing maximum number of trials when egg is thrown at floors 3 and 6 (Based on Fig 1)</figcaption></figure><p>Similarly, Fig 3. below highlights the sequence of events when the egg breaks at floors 9 and 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTdB15QonQNp0ak877ByKA.png" /><figcaption>Fig 3. Visualizing maximum number of trials when egg is thrown at floors 9 and 10 (Based on Fig 1)</figcaption></figure><p>What we get from Figures 1–3 is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*hPDtISsCoN21dKZ4WUoktA.png" /></figure><p>The number of moves we need to make varies depending on how many eggs we have. Of course, we can pick the configuration that gives us a minimum of 3. <strong><em>But this won’t help us determine with certainty if this is the critical floor</em></strong>. What we should go for is a setup where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*lSyJGNuFgKsGj_I7216UpA.png" /></figure><p><strong><em>This will help us determine the critical floor with certainty</em></strong>. To do this, what we need to account for is the fact that every time we drop an egg, we end up exhausting one additional trial. So, having equal intervals like what we had before won’t work.</p><p>Let’s start with floor 3 again. But, this time, the intervals for subsequent trials are not evenly spaced out, as shown in Fig 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4TGsJx6MQGxNfgd4mPung.png" /><figcaption>Fig 4. Consequence of throwing egg at floors 3, 5 and 6</figcaption></figure><p>This is definitely an improvement from before. If the egg drops at floors 3 or 5, the maximum number of trials we need to take is 3. But we have a problem here. Once we drop the egg at floor 6, we have exhausted the maximum of 3 trials and we at least need to make one more, to determine the critical floor. This approach violates what we want — equalize the maximum number of trials for all moves. So, starting at floor 3 is not the right move. How do we pick the first floor?</p><p>What we have done in Fig4. is, we have picked subsequent floors according to the following logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Xb5cTQYeKBawQ7j1DS21Bw.png" /></figure><p>If we start with floor ‘x’ and we have a total of ’n’ floors, then, we need to solve the following equation to determine the best floor to start with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3zqFsmpsXZQn7lxWVDJ5Bg.png" /></figure><p>And this is the sum of the first ‘x’ natural numbers and we know how to find this sum. If we solve this equation by plugging in the value of 10 for ’n’, we get that x = 4 — This will be our critical floor, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJiAYVOZr47Pu13aHQHXHg.png" /><figcaption>Fig 5. Consequence of throwing egg at floors 4, 7, 9 and 10</figcaption></figure><p>The critical floor is 4 and the maximum number of trials we need to take is also 4. Another cool aspect of this problem is, we can predict the maximum number of floors that can be explored with 4 trials and 2 eggs [2][3]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY6U19fnXCj6ZtkrvOQYnw.png" /></figure><p>This should be read as the number of ways of choosing 4 trials with 0 egg drops, 1 egg drop and 2 egg drops respectively.</p><h3>Coding up a generic solution</h3><p>Now would be a good time to put on your programmer’s hat! Let’s look at attempting to solve the 2 egg problem programmatically.</p><p>To begin with, we have 2 variables — the number of floors and the number of eggs. Conceptually we can think of a function ‘F’ that accepts these two pieces of inputs and returns the critical floor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*7YFdrixirvfTkxCpoGcSGw.png" /><figcaption>Fig 6. Signature of function accepting number of eggs and number of floors as input</figcaption></figure><p>The general idea is to iterate through all floors from 1-nfloors, and for each floor, we drop the egg and exhaust one trial. This leaves us with 2 possibilities — The egg breaks and we explore the lower floors or the egg does not break and we explore the higher floors. So, this gives rise to a recurrence relation [4]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhVjkHj2DA6rmmPAWdE2Lg.png" /><figcaption>Fig 7. Recurrence relation to solve the generic egg drop problem</figcaption></figure><p>Ok, so why do we have a min and a max term? This is for <strong><em>minimizing the maximum regret </em></strong>[1]. Let’s walk through an example to understand why we are doing this.</p><p>For simplicity and ease of visualization, let’s consider a situation where we have 2 eggs and 4 floors. Drawing the recursion tree for the recurrence relation above would give us something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOUNcrfs2WT3LlxqMN8HRw.png" /><figcaption>Fig 8. Recursion tree for 2 eggs and 4 floors</figcaption></figure><p>If we can find out the optimal solution for F(2,3) for instance, the result can be extrapolated to find the optimal solution for F(2,4). This indicates that this problem has an optimal substructure where optimal solutions to smaller subproblems can give rise to an optimal solution to the bigger problem [5].</p><p>We also see that we end up recomputing solutions to subproblems like F(2,1), F(1,1), etc., again and again. This means, there are overlapping subproblems and the function ‘F’ solves the same subproblems multiple times [6].</p><p>These two observations make this an ideal candidate for dynamic programming and we can memoize the results of the subproblems to deal with the exponential complexity of the recursion tree.</p><p>Ok, now going back to the tree, we actually know the solutions to many of the nodes in the tree, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNgqr8c128Iprj3enhiC3w.png" /><figcaption>Fig 9. Colored nodes (legend on bottom right) have quick solutions</figcaption></figure><p>So, we only need to continue recursing for the nodes in orange. Let’s evaluate the function for these values and visualize the tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXX4Erjc2qZkrw-9pP8FVA.png" /><figcaption>Fig 10. Function evaluated at all nodes</figcaption></figure><p>Traversing any one branch of the tree from the root to the leaf indicates one possible outcome of this experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGT0_r2HA4adePeoZ6UZMw.png" /><figcaption>Fig 11. Example outcome of having 2 eggs and 4 floors</figcaption></figure><p>What we see in Fig 11 is (path highlighted by blue nodes), we start with floor 1 and drop the egg. It does not break, so we move to floor 2 and drop the egg. It does not break. Now, we jump from the 2nd to the 4th floor and then drop the egg and it breaks. This is one of the different outcomes possible with 2 eggs and 4 floors.</p><p>The maximization term in Fig 7 is ensuring that we pick the worst possible case once we decide to throw the egg at a given floor. Having done this, we don’t have to stick with this floor if we can find the critical floor with fewer trials by jumping to a different floor from the current one. This is what the minimization term is helping us accomplish. This is also what is ensuring that we don’t attempt to throw at every floor starting from 1-n, but we skip floors based on the approach that minimizes the number of egg breaks.</p><p>Let’s look at one final example to understand the minimization of maximum regret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ba-m7KEw7G-4d9S_GPnTmg.png" /><figcaption>Fig 12. Minimization of maximum regret approach</figcaption></figure><p>Focusing on the green nodes and reading from top to bottom:</p><ul><li>We picked floor1 and the egg did not break, so we moved to floor 2</li><li>The egg did not break on floor 2. Now, we have a choice of either moving to floor 3 or 4.</li><li>The green tree on the bottom left corresponds to floor 3 and we have 2 outcomes here — if the egg breaks we have found our critical floor (3) and if it does not break, we need to explore one more floor above 3 (4). So, the worst-case number of additional throws is 1.</li><li>We use the same logic to understand the consequence of throwing the egg at floor 4 and the worst-case number of additional throws is also 1.</li><li>Finally, on floor 2, we can either pick the 3rd or 4th floor and we will choose the one that gives us the minimum (it’s the same in this case).</li></ul><p>You can find a top-down memoized solution to this problem at my GitHub repository:</p><p><a href="https://github.com/madhu90/CodeExamplesForBlogPosts/blob/main/EggDropProblem.cpp">madhu90/CodeExamplesForBlogPosts</a></p><p><strong>Reference</strong></p><p>[1] <a href="https://datagenetics.com/blog/july22012/index.html">https://datagenetics.com/blog/july22012/index.html</a></p><p>[2] <a href="https://code.oursky.com/famous-egg-dropping-puzzle-in-combinatorics/">https://code.oursky.com/famous-egg-dropping-puzzle-in-combinatorics/</a></p><p>[3] <a href="https://math.stackexchange.com/questions/2012591/eggs-and-floors-puzzle-extended-generalized#:~:text=2%20Answers&amp;text=For%20three%20eggs%20and%20100,suspicious%20floors%20at%20our%20disposal">https://math.stackexchange.com/questions/2012591/eggs-and-floors-puzzle-extended-generalized#:~:text=2%20Answers&amp;text=For%20three%20eggs%20and%20100,suspicious%20floors%20at%20our%20disposal</a>.</p><p>[4] <a href="https://medium.com/@parv51199/egg-drop-problem-using-dynamic-programming-e22f67a1a7c3">https://medium.com/@parv51199/egg-drop-problem-using-dynamic-programming-e22f67a1a7c3</a></p><p>[5] <a href="https://en.wikipedia.org/wiki/Optimal_substructure#:~:text=In%20computer%20science%2C%20a%20problem,greedy%20algorithms%20for%20a%20problem">https://en.wikipedia.org/wiki/Optimal_substructure#:~:text=In%20computer%20science%2C%20a%20problem,greedy%20algorithms%20for%20a%20problem</a>.</p><p>[6] <a href="https://en.wikipedia.org/wiki/Overlapping_subproblems">https://en.wikipedia.org/wiki/Overlapping_subproblems</a></p><p>[7] <a href="https://spencermortensen.com/articles/egg-problem/">https://spencermortensen.com/articles/egg-problem/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f97e476712" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/break-an-egg-64f97e476712">Break an egg!</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting text from images]]></title>
            <link>https://medium.com/codex/extracting-text-from-images-cb4d0f59a71b?source=rss-671814eb937f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb4d0f59a71b</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[cnn]]></category>
            <dc:creator><![CDATA[Madhumitha Raghu]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 20:46:51 GMT</pubDate>
            <atom:updated>2021-04-26T01:10:30.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7dEtpezgEEZohzve4W5UA.png" /><figcaption>Wordcloud generated from the contents of this blog</figcaption></figure><p>Text recognition is a very powerful machine learning technique that has a lot of potential in text based searches and digitization. I chose this topic as my Capstone project for Udacity’s Machine Learning Engineer Nano degree program.</p><p>There are numerous blog posts on text recognition (you can easily tell by the number of references I have linked)! So, you might be wondering what’s different here. My aim is to provide an overview of some of the most important steps in a typical machine learning workflow — data exploration, model selection and evaluation. This blog is a small compilation of many posts out there. I have tried to justify my observations about the dataset and the chosen model, to understand what it might take to build a system that is capable of recognizing any text.</p><p>Optical character recognition is the broader subject that deals with the ability of a machine to identify hand-written or machine written text [1]. It has numerous applications like reading postal addresses, bank cheques, application forms [2], digitizing heritage materials as images [3], automatic number plate recognition [4] and so on. It is one of the earliest areas of AI research and is quite a mature technology today [5]. In fact, there are many commercial software applications today which help digitize texts — for e.g., Tesseract, Adobe Acrobat Pro DC, Microsoft OneNote etc. [6]. A type of OCR called Intelligent Word Recognition [7] enables interpretation of hand-written text of different styles and fonts and that is the main focus of this article.</p><p>The application of OCR that intrigues me the most is its use in assistive technology for visually challenged individuals and kids with dyslexia [8]. Digital text makes it possible to see and hear words at the same time and that can be tremendously useful to those with reading disabilities.</p><p>I have chosen to work with the Extended MNIST dataset [9]. This is a dataset of handwritten characters converted to a 28x28 pixel image. There are 6 different sets for this dataset provided in Binary and CSV formats. There are also 6 different types of splits provided and I will be using the Balanced split downloaded from Kaggle [10]. This has train and test data for 47 classes. The balanced split has a more uniform distribution of the classes (~2400 images for each class).</p><p>This a link to my github repository that contains a Jupyter notebook with code examples:</p><p><a href="https://github.com/madhu90/MachineLearningProjects/tree/main/Character%20recognition">madhu90/MachineLearningProjects</a></p><h3><strong><em>Data exploration</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*GiZGJyRguS2EsM8sp235vQ.png" /></figure><p>Let’s begin by printing out the shape of the training and test data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHKkBk8EBc-HrVVU8HZvMw.png" /><figcaption>Fig 1. Shape of train and test data</figcaption></figure><p>We have 112799 training examples and 18799 test points. The first column corresponds to the label and the remaining 784 columns correspond to actual pixel intensities of a 28x28 image. We need to reshape the columns to understand what the data looks like.</p><p>There are 47 different classes used in this dataset. It would be good to pick an example for each class and visualize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*F2aFjI2_5T7T7Rc8U63xUg.png" /><figcaption>Fig 2. Example training images in each category</figcaption></figure><p>We have a uniform distribution of training examples across all labels (~2400 each).</p><p>Normalization is an important step in machine learning. This ensures the pixel intensities in our images have a similar data distribution [11]. So, after this step, our pixel intensities will lie between 0 and 1.</p><p>If we were to plot a histogram of these pixel intensities for any image (let’s say character “A”), this is what it would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Eft8QQ-EYwSeZOI7_iHzNw.png" /><figcaption>Fig 3. Histogram of pixel intensities for a sample training image</figcaption></figure><p>What we see here is that most of the pixel intensities are 0 or black and this corresponds to the background. The intensities of the actual image is between 0 and 1 and this is also evident from Fig 3.</p><p>It would be good to look at what the average image of class “A”, or “1” would look like [12]. This can be computed by summing all images of a given class and dividing it by the total number of examples of that class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDEbuFgU7sGxqGxpxTB4ng.png" /><figcaption>Fig 4. Average image of all classes</figcaption></figure><p>There are certainly different ways of representing any number or alphabet — you can change the font, using a cursive style and so on. Fig 4 tells us what the average image looks like for our dataset and this seems to be pretty standard.</p><p>It would be interesting to find out how the images in each category deviate from the mean image (also called centroid)[12]. This tells us how much variance is there in each category. We can use euclidean distance to compute the distance between two images :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*_apPY5hnv-lGPQmf8PSM6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRnyVZmdX6kB7vkipANX_A.png" /><figcaption>Fig 5. Boxplot of distances of all training images from their respective means</figcaption></figure><p>The length of the box indicates the interquartile range and tells us how dispersed the data is [13]. The box length is quite high for classes like “L”, “I” and this indicates that there is less consistency in the images representing this class. For example, the following images are examples of those which fall into the box for “I”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tCwDt9xtcxvZhBc1RLs-Q.png" /><figcaption>Fig 6. Sample images of class “I” that are at various quartiles represented by the boxplot</figcaption></figure><p>In the image at the center in Fig 6, we see that there is a lot of variability, but it is not too far from the average image (bottom right).</p><p>The image on the left in Fig 6 shows examples of “I” that are closer to the mean (Q1) and the image on the right shows examples that are farther away from the mean (&gt; Q3) and this is quite evident from what they look like. There are indeed many different ways to write the alphabet “I”.</p><p>Let’s look at an example where the length of the box is much smaller — “Q”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UVdJcjMvUiTLqqwlPFvVA.png" /><figcaption>Fig 7. Sample images of class “Q” that are various quartiles represented by the boxplot</figcaption></figure><p>There is less variability within the examples of the class “Q”. However, most examples are far away from the mean. There aren’t too many different ways this alphabet can be represented.</p><p>Let’s look at a subset of images of 5 different classes that are very far away from their respective centroids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*YrvqwECRr2Hu5REbON6Bkw.png" /><figcaption>Fig 8. Outliers for a classes “H”, “X” and “7”</figcaption></figure><p>From Fig 8, it is quite evident why these images are at a distance from the respective centroids.</p><p>Another useful visualization is a pair-wise comparison of digits/alphabets [12]. This pictorially shows us how one class can be discerned from another. We can plot this by subtracting the centroid of a given class from the centroid of all other classes, as shown below. Consider the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*mXHuvejU8BbdmVCZZHynwA.png" /><figcaption>Fig 9. Pair-wise comparison of the centroids of “S” and “I”</figcaption></figure><p>Classes “I” and “S” are very different from each other and this is evident from the difference image. We can identify “S” as the black regions in the image quite easily.</p><h3>Model selection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*MYu83jNZVu-duD04tg3Lzg.png" /></figure><p>Moving onto the next step in a typical machine learning workflow. There are a number of machine learning models that can be used for image classification — SVM (support vector machines), Decision trees, CNN (convolutional neural network) etc [15]. When extracted manually, features like corners, edges, blobs, SURF and SIFT are used for image classification [16].</p><p>CNNs are the most commonly used model for image classification because of their high accuracy. CNNs are feed forward neural networks and they are effective in reducing the number of parameters to be learnt by employing filters. These filters help us exploit the spatial locality of images [17]. Nodes that are close together are helpful in identifying a feature and CNNs leverage this spatial correlation of pixels [18].</p><p>Convolution is a mathematical operation which is essentially an element-wise multiplication of two matrices (an image and a kernel) followed by a sum [19] and the end result is something like blurring, smoothing, edge detection and so on, as shown below [20].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2Sqlsu-Tnff8HqJCm6I_g.png" /><figcaption>Fig 10. Convolution of an image with different kernels</figcaption></figure><p>The kernel defines what operation is performed on the image. If you stack up different types of kernels, you will be able to extract different features from an image. In a nutshell, CNN automatically learns what kernels should be applied to an image to extract meaningful features.</p><p>There are a few different types of layers in a CNN [21]:</p><p>a) Convolution layer — This layer employs the concept of mathematical convolution. A filter or kernel is moved across the image from top to bottom, left to right and each point in the image is convolved with the filter to generate a feature/activation map. This feature map is a representation of features like edges, corners, lines etc.</p><p>2) Pooling layer — The main purpose of this layer is to reduce the size of the feature map. The feature map records the exact position of features in the image. What this means is that small changes in the position of the feature in the input image will impact the feature map [22]. We need to make sure the feature detection process is translation invariant. This is where the pooling layers kick in. It reduces the resolution and complexity of the feature map by only outputting the max/average value from a grid [23]. This way, information about the exact position of the maxima is discarded.</p><p>3) Fully connected layers — Neurons in this layer have full connections to all activations in the previous layers [24]. Inputs from the previous layers are flattened out and fed to this layer. This layer is usually placed before the output layer.</p><p>The output layer gives us the results of classification and the number of neurons in this layer depends on the number of classes in the dataset (47).</p><p>I will be using the Keras Sequential [25] model to implement a CNN and the architecture of the model is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*fviH0MXogV-is-zRBWuPnw.png" /><figcaption>Fig 11. CNN model used on the EMNIST dataset</figcaption></figure><p>There are 2 convolution layers which use 32 and 64 filters respectively. There is a fully connected layer with 128 units and utilizing rectified linear activation function. Filters close to the input image pick up small, fine-grained details and the ones close to the output captures more general features, as shown in the following figures [26]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PWJztXhI6oTeedbcCfWihw.png" /><figcaption>Fig 12. Activation map obtained applying the first convolution layer to a training image of class “8”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*OwfXrQAQ6otYDYnJ-8OuIA.png" /><figcaption>Fig 13. Activation map obtained by applying the second convolution layer to a training image of class “8”</figcaption></figure><p>We then fit this model on our training data. I have used 30% of the training examples for cross validation. I plotted the error and accuracy of the model on the training and validation sets. The accuracy is improving for each epoch and the loss is reducing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*pHjpth3PUCU1lGUn3iSPMA.png" /><figcaption>Fig 14. Plot of the error and accuracy for each training epoch</figcaption></figure><p>Our model has an accuracy of 89.7% on the training data.</p><h3><strong>Model evaluation</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*Bs_LHm2OdwbeOopC9f3fQw.png" /></figure><p>Now it is time to test our model. Applying our model to the test dataset yields an accuracy of 87%. In addition to accuracy, it would also be good to look at other metrics like precision, recall and F1 score [27].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*EYIHD1cfCPVr_tnHkwQopA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*igg1meT87j7ymijRdT6ZpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*hMBKMU6-r3mO9U9U5iJ6IA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*SsqliEUYn6Xqppo6i-IQtg.png" /><figcaption>Fig 15. Precision, recall and F1 scores of our model per class and entire test data</figcaption></figure><p>Since this is a multi-class classification problem, macro averaging is used to compute these metrics. It reduces the multi-class prediction problem into multiple sets of binary predictions, calculates the corresponding metric for each of the binary cases, and then averages the results together [28].</p><p>The weighted macro averages for precision, recall and F1 score is 0.88, 0.87 and 0.87 respectively. If you look at some classes like “L”, “f”, “q”, they have a very small recall. Clearly, our model is not doing well on these classes. Let’s look at the results of our model and try to understand why this might be happening.</p><p>Let’s first look at the misclassification rate for our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*bDr5iGrMf1ow5N602dvKRg.png" /></figure><p>We have a uniform distribution of test data (400 each) and hence this ratio should be comparable. When I plot this for all classes, this is what I get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*qeBjgF-ps_wz3ZtX71jIZw.png" /><figcaption>Fig 16. Misclassification rate for all classes in the test dataset</figcaption></figure><p>The classes L, F q, g, 0 and O seem to have the highest misclassifications, and this is quite evident from the low recall. Let us plot some test examples in this category to visualize what the test data looks like, and the predicted labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*F465ClxhOzhMRz2ABOkxIQ.png" /><figcaption>Fig 17. Sample images which get misclassified and their corresponding predicted label</figcaption></figure><p>The test images for which we get the prediction wrong are not typical examples and our model seems to be giving a reasonable prediction.</p><p>It would also be a good idea to look at what kind of training data is provided for classes that get confused very often (eg. L and 1 or L and I). The following figure shows a subset of training images of class “L” which are between Q1 and Q3 quartiles (with respect to distance from class centroid).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*eJKvXfVG013bl7ti0P0IQw.png" /><figcaption>Fig 18. Sample images of class “L” (left) and “I” (right) whose distance from their respective centroid is between Q1 and Q3</figcaption></figure><p>What we see is that the training images are not very helpful is differentiating these labels. It would be good to filter out such examples from the training data or replace it with more synthetic meaningful examples.</p><p>It is also a good idea to look at the labels associated with the test data. From Fig 19, the images labelled as “F” look very incorrect. If we look at more examples of “F” which the model classified incorrectly, this is what we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDDJ-FF8xPzOASF0Mm6QHA.png" /><figcaption>Fig 19. Test data labelled as “F” which were classified incorrectly. Predicted label is on top of each image</figcaption></figure><p>They look so much like the lowercase alphabet “f” and our model has correctly classified it as “f”! This could in turn be a consequence of bad training examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*MWGQjfSl46b9MEMKASePrg.png" /><figcaption>Fig 20. Training data labelled as “F” (left) and “f” (right)</figcaption></figure><p>To summarize, there are a number of techniques to improve the accuracy of a model — Data augmentation (when there are fewer training examples), dropout regularization (fix overfitting), Increase the training data size or number of training epochs (fix underfitting), batch normalization (minimize training time) and so on [29]. It is equally important to make sure the training data used on the model is good enough to differentiate one class form the other. The labels associated with the test data should also be valid. If a human cannot accurately determine the class of an image, it is a good indication that the image is not an ideal candidate for training.</p><h3><strong>Does our model generalize well?</strong></h3><p>Since our labels are characters and numbers, we can easily generate synthetic data and pass it to our model. We can get creative with different font styles, shapes, and translation effects, to test the model efficacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*t7QatZBRAsavRtzmyClmbg.png" /><figcaption>Fig 21. Synthetic data (different font style and size) to test our model</figcaption></figure><p>Once you run the new data against the model, what you observe is that parameters like font style, size, horizontal and vertical translation affect the accuracy of our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*-IV7MuBgb-jV8jyYBNVzCw.png" /><figcaption>Fig 22. Impact of font size and style on model accuracy</figcaption></figure><p>Now this is expected because we have not trained our model to work with these font styles and sizes. So, if we would like our model to recognize any font style and size, we must train it on additional data.</p><p>I also tried testing our model with augmented training data. I picked a class with very high misclassification rate (“F”) and a class with the lowest misclassification (“3”). The data was augmented by mean centering and performing different translations. I generated around 100 images for each of the classes and ran it through the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*NkcB2usym3MbyOA2v_Lp5g.png" /><figcaption>Fig 23. A random training image of class “F” that is augmented</figcaption></figure><p>For augmented “F”, the accuracy was 0.48 and for augmented “3”, it was 0.2. This is a good indication that model accuracy on the test and validation sets is not sufficient to ensure it generalizes well.</p><p>In a nutshell, in order to solve the more generic problem of character recognition, we will need to employ data augmentation to have more training examples, train the model on other languages, and also identify and correct labeling bias [30].</p><p><strong>References</strong></p><p>[1] <a href="https://www.sciencedirect.com/topics/computer-science/optical-character-recognition">https://www.sciencedirect.com/topics/computer-science/optical-character-recognition</a></p><p>[2] <a href="https://www.sciencedirect.com/topics/social-sciences/character-recognition">https://www.sciencedirect.com/topics/social-sciences/character-recognition</a></p><p>[3] <a href="https://www.digitalnc.org/blog/digital-collections-ocr-what-it-is-and-what-it-isnt/">https://www.digitalnc.org/blog/digital-collections-ocr-what-it-is-and-what-it-isnt/</a></p><p>[4] <a href="https://en.wikipedia.org/wiki/Optical_character_recognition">https://en.wikipedia.org/wiki/Optical_character_recognition</a></p><p>[5] <a href="https://research.aimultiple.com/ocr-technology/">https://research.aimultiple.com/ocr-technology/</a></p><p>[6] <a href="https://beebom.com/best-ocr-software/">https://beebom.com/best-ocr-software/</a></p><p>[7] <a href="https://en.wikipedia.org/wiki/Intelligent_character_recognition">https://en.wikipedia.org/wiki/Intelligent_character_recognition</a></p><p>[8]<a href="https://www.understood.org/en/school-learning/assistive-technology/assistive-technologies-basics/how-does-optical-character-recognition-help-kids-with-reading-issues">https://www.understood.org/en/school-learning/assistive-technology/assistive-technologies-basics/how-does-optical-character-recognition-help-kids-with-reading-issues</a></p><p>[9] <a href="https://www.nist.gov/itl/products-and-services/emnist-dataset">https://www.nist.gov/itl/products-and-services/emnist-dataset</a></p><p>[10] <a href="https://www.kaggle.com/crawford/emnist">https://www.kaggle.com/crawford/emnist</a></p><p>[11] <a href="https://becominghuman.ai/image-data-pre-processing-for-neural-networks-498289068258">https://becominghuman.ai/image-data-pre-processing-for-neural-networks-498289068258</a></p><p>[12] <a href="http://varianceexplained.org/r/digit-eda/">http://varianceexplained.org/r/digit-eda/</a></p><p>[13] <a href="https://www.thoughtco.com/what-is-the-interquartile-range-3126245">https://www.thoughtco.com/what-is-the-interquartile-range-3126245</a></p><p>[14] <a href="https://towardsdatascience.com/explaining-k-means-clustering-5298dc47bad6">https://towardsdatascience.com/explaining-k-means-clustering-5298dc47bad6</a></p><p>[15] <a href="https://iq.opengenus.org/basics-of-machine-learning-image-classification-techniques/">https://iq.opengenus.org/basics-of-machine-learning-image-classification-techniques/</a></p><p>[16] <a href="https://www.rsipvision.com/image-features-for-classification/#:~:text=Well%20known%20examples%20of%20image,features%20can%20be%20wisely%20selected">https://www.rsipvision.com/image-features-for-classification/#:~:text=Well%20known%20examples%20of%20image,features%20can%20be%20wisely%20selected</a></p><p>[17] <a href="https://www.analyticsvidhya.com/blog/2021/01/image-classification-using-convolutional-neural-networks-a-step-by-step-guide/">https://www.analyticsvidhya.com/blog/2021/01/image-classification-using-convolutional-neural-networks-a-step-by-step-guide/</a></p><p>[18] <a href="https://towardsdatascience.com/simple-introduction-to-convolutional-neural-networks-cdf8d3077bac#:~:text=There%20are%20three%20types%20of,Features%20of%20a%20convolutional%20layer">https://towardsdatascience.com/simple-introduction-to-convolutional-neural-networks-cdf8d3077bac#:~:text=There%20are%20three%20types%20of,Features%20of%20a%20convolutional%20layer</a></p><p>[19] <a href="https://www.pyimagesearch.com/2016/07/25/convolutions-with-opencv-and-python/">https://www.pyimagesearch.com/2016/07/25/convolutions-with-opencv-and-python/</a></p><p>[20] <a href="https://medium.com/analytics-vidhya/2d-convolution-using-python-numpy-43442ff5f381">https://medium.com/analytics-vidhya/2d-convolution-using-python-numpy-43442ff5f381</a></p><p>[21] <a href="https://www.upgrad.com/blog/basic-cnn-architecture/#:~:text=There%20are%20three%20types%20of,CNN%20architecture%20will%20be%20formed">https://www.upgrad.com/blog/basic-cnn-architecture/#:~:text=There%20are%20three%20types%20of,CNN%20architecture%20will%20be%20formed</a></p><p>[22] <a href="https://machinelearningmastery.com/pooling-layers-for-convolutional-neural-networks/">https://machinelearningmastery.com/pooling-layers-for-convolutional-neural-networks/</a></p><p>[23] <a href="https://divsoni2012.medium.com/translation-invariance-in-convolutional-neural-networks-61d9b6fa03df">https://divsoni2012.medium.com/translation-invariance-in-convolutional-neural-networks-61d9b6fa03df</a></p><p>[24] <a href="https://cs231n.github.io/convolutional-networks/#fc">https://cs231n.github.io/convolutional-networks/#fc</a></p><p>[25] <a href="https://keras.io/api/models/sequential/">https://keras.io/api/models/sequential/</a></p><p>[26] <a href="https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/">https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/</a></p><p>[27] <a href="https://towardsdatascience.com/accuracy-precision-recall-or-f1-331fb37c5cb9">https://towardsdatascience.com/accuracy-precision-recall-or-f1-331fb37c5cb9</a></p><p>[28] <a href="https://cran.r-project.org/web/packages/yardstick/vignettes/multiclass.html">https://cran.r-project.org/web/packages/yardstick/vignettes/multiclass.html</a></p><p>[29] <a href="https://www.analyticsvidhya.com/blog/2019/11/4-tricks-improve-deep-learning-model-performance/">https://www.analyticsvidhya.com/blog/2019/11/4-tricks-improve-deep-learning-model-performance/</a></p><p>[30] <a href="https://towardsdatascience.com/identifying-and-correcting-label-bias-in-machine-learning-ed177d30349e">https://towardsdatascience.com/identifying-and-correcting-label-bias-in-machine-learning-ed177d30349e</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb4d0f59a71b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/extracting-text-from-images-cb4d0f59a71b">Extracting text from images</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Median of two sorted arrays]]></title>
            <link>https://medium.com/codex/median-of-two-sorted-arrays-a84a4315e85?source=rss-671814eb937f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a84a4315e85</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Madhumitha Raghu]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 01:02:35 GMT</pubDate>
            <atom:updated>2021-03-29T01:39:11.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g3QXU5JCIcccqfbA" /><figcaption>Photo by <a href="https://unsplash.com/@dtopkin1?utm_source=medium&amp;utm_medium=referral">Dayne Topkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><a href="http://medium.com/codex">CODEX</a></h4><p>We are given two arrays which are sorted and our goal is to find the median of these arrays in <strong>logarithmic</strong> time and <strong>O(1)</strong> space complexity (<a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">LeetCode</a>). This is a very common question that has numerous solutions posted all over the internet. However, it took me some time to wrap my head around it. I would like to describe my thought process and solution here.</p><h4>Problem statement</h4><p>To begin with, this is how we compute the median for a single sorted array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*ZST_RRJdHop72wCbQbzIdw.png" /><figcaption>Fig 1. Finding the median of a single even length sorted array</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*ayc8lwJCNwNObtAY7HdeYg.png" /><figcaption>Fig 2. Finding the median of a single odd length sorted array</figcaption></figure><p>Let’s first visualize the problem statement. Consider two arrays as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*Zy7YXUY-jCn2_I3SPYptiQ.png" /><figcaption>Fig 3. Finding the median of two sorted arrays (problem statement)</figcaption></figure><p>Here, we have two sorted arrays A and B. In order to find the median of these arrays, we can need to combine these two arrays, sort it and compute the median of the combined array. This approach does not satisfy the requirements of the problem statement because:</p><p>a) Combining the two arrays into a single array and sorting it(using an algorithm like merge sort) is an <strong>O(n*log(n)) </strong>time operation</p><p>b) The space complexity is also <strong>O(n)</strong> because we need to create a new array to accommodate the two arrays</p><p>The combined array A+B cannot be obtained by simply appending one array to another. This is why the approach of trying to combine the arrays to determine the median won’t satisfy the logarithmic time constraint imposed by the problem— We know the relationship between elements within each array because they are sorted. So, the smallest is at the beginning and the largest is at the end. However, we do not know the relationship between elements across the arrays. Without iterating through both the arrays completely we can’t find the relationship between them and this violates the time constraint.</p><h4>Solution approach</h4><p>If you think about it, the constraints are really pushing us in the direction of not having to worry about the combined array. An O(log(n)) algorithm (like binary search) basically keeps discarding a section of the array at every iteration based on some criteria. So, we need to think of a way to incorporate that in our solution.</p><p>That is, if we know that A and B are sorted, we do not need to know what A+B will look like, to compute the median. We only need to know the<strong> first half</strong> of the combined array to find the median. Depending on the length of A+B, the position of the median will be slightly different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*K788oxnm_MrzulhbIJonkw.png" /><figcaption>Fig 4. Index of median element in A+B when it has an odd length</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*9RbebIVHV7f6gWTU_cw-4Q.png" /><figcaption>Fig 5. Index of median element in A+B when it has an even length</figcaption></figure><p>The bottom line is, once we know which elements in A and B contribute to the first half (left side) of the combined array A+B, we don’t really care about the remaining elements and that is what is going to help us solve this in logarithmic time.</p><p>Ok, so what about the O(1) space constraint? What this implies is that, we should not be allocating memory for any temporary arrays. We technically don’t need to. We will discuss this more once we get into the implementation of the solution.</p><p>In a nutshell, we are going to apply binary search across two arrays to draw a line that indicates how much of a given array will contribute to the left half or first half of the combined array. This can be visualized like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*Ip6pRMUzLFKLbZCog5mzrg.png" /><figcaption>Fig 6. Visualizing the binary search approach to determine which elements in each array contribute to the combined array (odd length)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*VA3tasV-K2l8FvRXdGbu9Q.png" /><figcaption>Fig 7. Visualizing the binary search approach to determine which elements in each array contribute to the combined array (even length)</figcaption></figure><h4>Implementation details</h4><p>Remember that our goal is to use binary search to figure out how much each array contributes to the combined array. What’s the structure of a binary search problem?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*C9DsWJtklqxW_yo8PYIiXA.png" /><figcaption>Fig 8. Binary search pseudocode</figcaption></figure><p>So, we need to map our problem statement into this format. We have 2 arrays to work with. We should focus on one array (the smaller one) and use it to determine contributions from both arrays. Let’s assume A is the smaller array.</p><p><strong>a) What should keep our loop going?</strong></p><p>We should keep looping till we have explored all possible ways to combine both the arrays to determine the left half of A+B. As an example, if the size of the left side of A+B is 4 and we have picked one element from A , this automatically implies we need three elements from B. We can either pick nothing from A, a few elements from A or everything from A. So, we keep looping till the contribution of A is equal to its length.</p><p><strong>b) What is our target and how should we be testing it?</strong></p><p>We want to find the left-side of A+B so that we can easily compute the median. So, we want to find a split that helps us get to the median.</p><p>Each split partitions both the arrays into 4 parts and we are combining the elements on the left halves of the splits to form the first half of A+B, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*Pm2qpa2dUSRssk2kWPeA8w.png" /><figcaption>Fig 9. Target visualization</figcaption></figure><p>If all elements on the left side are less than all elements on the right side, then, we know that the split has given us the first half of A+B.</p><p>That is:</p><p><strong>A[aL] &lt; B[bR] and B[bL] &lt; A[aR], </strong>where aL, bL, bR and aR correspond to the indices of the elements on either sides of the split.</p><p><strong>c) How do we compute median if we find the target split?</strong></p><p>Consider a situation where the length of A+B is odd (Fig 9) and also assume that we have found the target split. Now, we have a split where a1&lt; b4 and b3 &lt; a3. Since A+B has a length of 7, the median is the 4th element in A+B and this has to be either a1,b1,b2 or b3 (elements on the left half). We have 4 numbers and there are 4! ways of arranging them (assuming no repetition), as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*bDFvVoEA0HoFAhoRJVa_6w.png" /><figcaption>Fig 10. Different ways in which elements on the left side of the A+B array (odd length)can be arranged, depending on their values</figcaption></figure><p>But, do we really care about these arrangements? We are only interested in the fourth element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*tDI30h4pxraVXYlYdyGK0g.png" /><figcaption>Fig 11. Position of median in A+B (odd length) that we are interested in</figcaption></figure><p>The 4th element has to be the largest number on the left-hand side and we only need to compare the largest numbers from A and B to get this! So:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*os33pEG1SiTeE2m3zq7o9w.png" /></figure><p>Similarly, let’s look at a situation where A+B has an even length:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*APg-zKK-fqt6B5BWuY2FtA.png" /><figcaption>Fig 12. Finding median of A+B which has an even length</figcaption></figure><p>Now, we have a split where a2 &lt; b3 and b2 &lt; a3. Since A+B has a length of 8, the median is the average of the 4th and 5th elements in A+B.</p><p>There are 4! ways of arranging {a1,a2,b1,b2} and for each arrangement, there are 2 ways of picking the 5th element (a3 or b3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*C32K6ymXqee7RRmrgcMh2g.png" /><figcaption>Fig 13. Different ways in which elements on the left side of the A+B array (even length)can be arranged, depending on their values</figcaption></figure><p>Here again, do we really care about these arrangements? We are only interested in the 4th and 5th elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*1kcBM14bDmtuA0_85c9m4A.png" /><figcaption>Fig 14. Position of median in A+B (odd length) that we are interested in</figcaption></figure><p>The 4th element is the largest on the left side of A+B and it must be max(a2,b2), just like what we saw for the odd length case. The 5th element has to be either a3 or b3. But, it must be just next to the 4th element. So, we pick the minimum value, i.e. min(a3,b3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*r88YlzIe4oOUn841lFmklQ.png" /></figure><p><strong>d) How do we keep the loop going if we don’t find the target?</strong></p><p>In a nutshell, if we haven’t found the target split, we should either include more or less of A. Let’s walk through a couple of examples to understand this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*_k5Tun3zeQ8-NjGqqpjbaA.png" /><figcaption>Fig 15: First split of two arrays to compute median when length of A+B is odd</figcaption></figure><p>In this example, A+B has an odd length of 7 and the median is the 4th element. We first pick one element from A and 3 elements from B to compute the left-half of A+B.</p><p>1 &lt; 6. However, 5 &gt; 4. This indicates that there are smaller elements to the right of A.This means neither 5 cannot be the 4th smallest element. We need to include more of A to discover that element. So, we continue to the next iteration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*Xb4ds7MS7KhqIgNzPggyTg.png" /><figcaption>Fig 16: Second split of two arrays to compute median when length of A+B is odd</figcaption></figure><p>Let’s again compare the elements on both the sides — 4 &lt; 5 and 3 &lt; 7 and there are 4 elements on the left side. So, we have found the right split!</p><p>Since A+B has an odd length, we need to find the last element in this subarray. This has to be the max of the values on the right most extreme of both the arrays A and B, i.e. max(4,3) and that is 4.</p><p>Let’s look at another example where A+B has an even length:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*HKO9ttG8ezMV9pkwAbEVUQ.png" /><figcaption>Fig 17: First split of two arrays to compute median when length of A+B is even</figcaption></figure><p>A+B has an even length of 8 and the median is the average of the 4th and 5th elements (mean(4,5)). We pick 1 element from A and 3 of them from B.</p><p>1 &lt; 6. However, 5 &gt; 4. This means neither 5 cannot be the 4th smallest element. We need to include more of A to discover that element. So, we continue to the next iteration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*nnzgwXH7ZDFB1GHhxm7BXA.png" /><figcaption>Fig 18: Second split of two arrays to compute median when length of A+B is even</figcaption></figure><p>Here, 4 &lt; 6 and 5 &lt; 7. So, we have found the median split! So, the median is the average of max(4,3)and min(5,7).</p><p>One thing to remember is, we can be in a situation where the split results in one more more of the halves being empty. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*GhcxS5jGw8QyxyjGsUwUYA.png" /><figcaption>Fig 19: Special situation to consider in implementation</figcaption></figure><p>This is an interesting case where two of the splits to the right are empty! What do we compare 1 and 2 to? The smaller values are on the left and the larger ones are on the right. Since we have no valid number to compare to, we just assume that 1 and 2 satisfy the condition for a median split. This can be done by comparing them to very large values (+∞). Similarly, if there are empty values on the left, we compare it with -∞.</p><h4>Time complexity analysis</h4><p>Now that we know how to implement this algorithm, it is time to make sure it satisfies the constraints of the problem.</p><p>We have not used any temporary arrays and we just rely on the indices for our implementation. So, the space complexity is O(1).</p><p>We always pick the smaller array to iterate and and every step we either include more of it (less of the other array) or less of it (more of the other array). So, the time complexity is O(log(min(A,B))).</p><h4>Link to Github repository: <a href="https://github.com/madhu90/CodeExamplesForBlogPosts.git">https://github.com/madhu90/CodeExamplesForBlogPosts.git</a></h4><h4>References</h4><p>[1] <a href="https://www.geeksforgeeks.org/median-of-two-sorted-arrays/">https://www.geeksforgeeks.org/median-of-two-sorted-arrays/</a></p><p>[2] <a href="https://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/">https://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/</a></p><p>[3] <a href="https://www.youtube.com/watch?v=LPFhl65R7ww&amp;ab_channel=TusharRoy-CodingMadeSimple">https://www.youtube.com/watch?v=LPFhl65R7ww&amp;ab_channel=TusharRoy-CodingMadeSimple</a></p><p>[4] <a href="https://www.youtube.com/watch?v=MHNTl_NvOj0&amp;ab_channel=IDeserve">https://www.youtube.com/watch?v=MHNTl_NvOj0&amp;ab_channel=IDeserve</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a84a4315e85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/median-of-two-sorted-arrays-a84a4315e85">Median of two sorted arrays</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>