<?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 Daniel (Heedong) Jang on Medium]]></title>
        <description><![CDATA[Stories by Daniel (Heedong) Jang on Medium]]></description>
        <link>https://medium.com/@deardanny?source=rss-ad723feb0ea0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lQDsnNipjelA-O8cIOizPg.jpeg</url>
            <title>Stories by Daniel (Heedong) Jang on Medium</title>
            <link>https://medium.com/@deardanny?source=rss-ad723feb0ea0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:16:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deardanny/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 Harris Finds Corners [Computer Vision]]]></title>
            <link>https://medium.com/@deardanny/how-harris-finds-corners-computer-vision-ca977c895fdd?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca977c895fdd</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 07:40:00 GMT</pubDate>
            <atom:updated>2026-09-27T07:40:00.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItXucl5GOsTBAUt-PSl3Gg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ttepavac?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tanja Tepavac</a> on <a href="https://unsplash.com/photos/a-piece-of-a-puzzle-with-a-missing-piece-cWMhxNmQVq0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Every jigsaw puzzle has three kinds of pieces.</p><p>The sky pieces could go almost anywhere. They are the same flat blue on every side, and you can hold one over a dozen spots without being sure. The border pieces are better. The straight side tells you the piece belongs on the edge of the puzzle, but not where along it. And then there are the pieces with a sharp turn in the picture, the corner of a window or the tip of a roof. Those fit in exactly one place.</p><p>Computer vision has the same problem whenever it matches two photos of one scene: stitching a panorama, rebuilding a scene in 3D, following an object from one video frame to the next. It needs points it can find again in the second photo. It needs the third kind of piece.</p><p>A corner detector is a program that finds the third kind. The Harris corner detector (Harris and Stephens, 1988) is the classic one, and it still shows up in the first few weeks of a computer vision course. This post builds it from one question: what happens when you nudge a piece?</p><h3>Sky pieces, border pieces, one-place pieces</h3><p>Put a small window over part of an image, say 5×5 pixels. That window is your puzzle piece. Now nudge it one pixel in some direction and compare what it shows before and after.</p><ul><li><strong>Flat region, the sky piece:</strong> nothing changes, whichever way you nudge. Nothing pins it down.</li><li><strong>Edge, the border piece:</strong> nudge it along the edge and nothing changes. Nudge it across and everything changes. It is pinned in one direction only. (Edges were the subject of the last post in this series.)</li><li><strong>Corner, the one-place piece:</strong> nudge it any direction and something changes. It is pinned in every direction.</li></ul><p>That is the whole detector in words, an idea that goes back to Moravec in 1980. A corner is a spot where every nudge makes the window look different. The rest of this post turns that sentence into numbers.</p><h3>Nudge the piece, measure the change</h3><p>To measure “looks different,” subtract the original window from the nudged one, square each pixel’s difference so negatives do not cancel, and add them up:</p><pre>E(u, v) = Σ over the window [ I(x+u, y+v) - I(x, y) ]²</pre><p>I is the image, (u, v) is the nudge (u to the right, v down), and E is the total change. Big E means the piece looks very different after the nudge, so it does not slide there.</p><p>Here is a toy image: a black background (0) with a white square (10) in the bottom-right. Three 5×5 windows sit on it, one of each kind of piece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Wo7F7Fc67y_CHtfHsWS-g.png" /></figure><p>Nudge each one and compute E:</p><pre>right (1,0)   down (0,1)   diagonal (1,1)<br>flat                    0            0              0<br>edge (vertical)       500            0            500<br>corner                300          300            700</pre><p>The numbers match the puzzle. The sky piece scores zero everywhere: it slides anywhere without complaint. The border piece scores zero in exactly one direction, along the edge. The one-place piece scores in every direction.</p><p>The catch is cost. Testing this way means trying many nudges at every pixel, and each try is a full pass over the window. It is like checking every puzzle piece against every spot on the table, one at a time. Harris and Stephens found a way to skip all of that.</p><h3>Read the piece instead of trying every spot</h3><p>For small nudges, you can approximate the shifted image with the gradient, the same derivatives from the edge post:</p><pre>I(x+u, y+v) ≈ I(x, y) + Ix*u + Iy*v</pre><p>Ix is how much brightness changes per pixel moving right, and Iy is the same moving down. Plug that into E and the I(x, y) terms cancel:</p><pre>E(u, v) ≈ Σ (Ix*u + Iy*v)²<br>        = [u v] M [u v]ᵀ</pre><pre>M = | Σ Ix*Ix   Σ Ix*Iy |<br>    | Σ Ix*Iy   Σ Iy*Iy |</pre><p>M is a 2×2 matrix built only from the gradients inside the window. It goes by a few names: second moment matrix, structure tensor, or, in my course slides, the covariance matrix of the gradients. Once you have it, you can predict E for any nudge without nudging anything. It is the difference between trying a piece in every spot and looking at its shape to know where it can go. Nine nudges or nine hundred, it is the same four numbers.</p><p>For the three spots in the toy image, with gradients from the central difference [-1, 0, 1] / 2:</p><pre>flat:     |   0    0 |<br>          |   0    0 |</pre><pre>edge:     | 250    0 |<br>          |   0    0 |</pre><pre>corner:   | 150   25 |<br>          |  25  150 |</pre><p>The edge one is easy to check by hand. Ix is 5 at 10 pixels of the window and 0 everywhere else, so Σ Ix*Ix = 10 × ⁵² = 250. Iy is 0 everywhere, so the rest of the matrix is 0.</p><p>The approximation is rough on a hard step like this one. Every E that M predicts comes out exactly half the real value, because the central difference spreads the jump over two pixels at half height. What survives is the pattern: M predicts zero exactly where E was zero, and something large everywhere else.</p><h3>Two numbers sort the pile</h3><p>M is symmetric, so it has two eigenvalues, λ1 and λ2 (lambda), each paired with a direction called its eigenvector. Each eigenvalue says how fast E grows when you nudge along its direction. A big eigenvalue means the piece is pinned that way. A small one means it slides freely that way.</p><pre>λ1     λ2<br>flat        0      0     slides every way<br>edge      250      0     pinned one way, slides the other<br>corner    175    125     pinned every way</pre><p>That is how you sort the pile:</p><ul><li>both small → sky piece (flat)</li><li>one large, one small → border piece (edge)</li><li>both large → one-place piece (corner)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMM-vRzsS41Xt76QE86OlA.png" /></figure><p>The border piece’s zero is worth staring at. λ2 = 0 belongs to the direction along the edge, where the piece slides without resistance. That zero is the math version of “I know it goes on the border, but not where.”</p><p>For the corner, the eigenvalues are not just the diagonal entries 150 and 150. The off-diagonal 25 says the gradients in the window are not cleanly split between x and y, and the eigenvalues absorb that: 150 + 25 = 175 and 150–25 = 125. Turning the piece in your hand would rotate the eigenvectors but leave the eigenvalues alone, which comes back later.</p><h3>One score for how one-place a piece is</h3><p>You could compute both eigenvalues at every pixel and threshold them. Harris and Stephens used a shortcut that never computes them at all. Two facts hold for any 2×2 matrix with entries a, b, c, d:</p><pre>det(M)   = λ1 * λ2  = a*d - b*c<br>trace(M) = λ1 + λ2  = a + d</pre><p>Both come straight from the four entries, no eigenvalue solver needed. The cornerness score is built from them:</p><pre>R = det(M) - k * trace(M)²        (k is usually 0.04 to 0.06)</pre><p>The product λ1 * λ2 is only big when both eigenvalues are big. The trace term subtracts a penalty when one of them dominates. In puzzle terms, a piece only scores high if it is pinned both ways, and a border piece, pinned hard one way and loose the other, gets marked down. Here it is on the three spots, with k = 0.04:</p><pre>flat:    R =     0 - 0.04 * 0²    =      0<br>edge:    R =     0 - 0.04 * 250²  =  -2500<br>corner:  R = 21875 - 0.04 * 300²  =  18275</pre><p>That gives the reading rule:</p><ul><li>R near 0 → flat</li><li>R negative → edge</li><li>R large and positive → corner</li></ul><p>One alternative is worth knowing. The Shi-Tomasi detector (1994) skips the formula and uses R = min(λ1, λ2) directly: a point is only as corner-like as its weaker direction. OpenCV’s goodFeaturesToTrack uses that version by default.</p><h3>One point per corner</h3><p>Compute R at every pixel and you get a heat map, not a list of corners. Around each real corner there is a small cluster of high values, because several neighboring windows overlap the same turn and all of them look like one-place pieces. You want one point per corner, not a handful.</p><p>Two steps turn the heat map into points:</p><ol><li><strong>Threshold.</strong> Keep pixels where R is above a cutoff, for example 1% of the largest R in the image. This throws out the sky and border pieces.</li><li><strong>Non-maximum suppression (NMS).</strong> Compare each remaining pixel’s R with its neighbors. Keep it only if it is the largest in its neighborhood.</li></ol><p>In one dimension it looks like this:</p><pre>R along a row:   2   5   9   6   3   1   4   8   7<br>NMS keeps:               ^                   ^</pre><p>Two peaks, two corners, instead of a whole cluster of candidates. In code, a common trick is to compare the response map with a max filter of itself: a pixel survives when it equals the maximum of its own neighborhood.</p><p>Here is the whole thing on a 100×100 white square, using the code at the end of this post:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swPGRL_31TeAzcd-aHjgKg.png" /></figure><p>The left panel is R: blue along the four sides (border pieces, negative R) and red only at the four corners. After thresholding and NMS, exactly four points survive.</p><h3>Turn the piece: fine. Zoom in: trouble.</h3><p>Turn a puzzle piece in your hand and it is still the same piece. Harris agrees. Rotation turns the eigenvectors, but the eigenvalues, and so R, stay the same. The right panel above shows it: the square rotated 30 degrees still gives exactly four corners.</p><p>Brightness changes are partly handled, like doing the puzzle under a warmer lamp. Adding a constant to every pixel (I → I + b) changes nothing, because R only uses derivatives. Multiplying every pixel (I → a * I) scales R by a⁴, so a fixed threshold can let corners slip in or out. A threshold relative to the largest R, like the 1% rule above, absorbs that.</p><p>Scale is where Harris breaks. The window has a fixed size. Zoom far into the tip of a rounded roof and the part inside the window is a gentle, nearly straight curve: a border piece. Zoom out and the whole turn fits inside the window: a one-place piece. Same roof, different kind of piece, depending only on how big it appears in the image.</p><p>The fix is to run the detector at several zoom levels, for example on each level of a Gaussian pyramid, and keep the points that respond most strongly across scales. That is the idea behind the detector in SIFT (Scale-Invariant Feature Transform), and probably a post of its own.</p><h3>Try it</h3><p>The whole piece-sorting machine fits in about twenty lines.</p><pre>import numpy as np<br>from scipy.ndimage import gaussian_filter, maximum_filter, rotate</pre><pre>def harris(img, sigma_d=1, sigma_w=2, k=0.04):<br>    Ix = gaussian_filter(img, sigma_d, order=(0, 1))   # derivative of Gaussian in x<br>    Iy = gaussian_filter(img, sigma_d, order=(1, 0))   # derivative of Gaussian in y<br>    Sxx = gaussian_filter(Ix * Ix, sigma_w)            # weighted sums over the window<br>    Syy = gaussian_filter(Iy * Iy, sigma_w)<br>    Sxy = gaussian_filter(Ix * Iy, sigma_w)<br>    det = Sxx * Syy - Sxy ** 2<br>    trace = Sxx + Syy<br>    return det - k * trace ** 2</pre><pre>def corners(R, size=7):<br>    keep = (R == maximum_filter(R, size=size)) &amp; (R &gt; 0.01 * R.max())<br>    return np.argwhere(keep)</pre><pre>img = np.zeros((100, 100))<br>img[30:70, 30:70] = 1.0          # a white square</pre><pre>R = harris(img)<br>print(corners(R).tolist())<br>for name, (y, x) in {&quot;flat&quot;: (50, 50), &quot;edge&quot;: (50, 30), &quot;corner&quot;: (31, 31)}.items():<br>    print(f&quot;{name:7} R = {R[y, x]:+.1e}&quot;)</pre><pre>tilted = rotate(img, 30, reshape=False, order=1)<br>print(&quot;rotated 30 deg:&quot;, len(corners(harris(tilted))), &quot;corners&quot;)</pre><pre>[[31, 31], [31, 68], [68, 31], [68, 68]]<br>flat    R = +0.0e+00<br>edge    R = -1.2e-04<br>corner  R = +6.6e-04<br>rotated 30 deg: 4 corners</pre><p>Four corners, one per corner of the square. The sky piece scores zero, the border piece is negative, the one-place piece is positive, exactly the reading rule from above.</p><p>The two sigmas are the two Gaussians in the method. sigma_d is the blur inside the derivative, the same derivative of Gaussian from the last post. sigma_w is the window. Instead of a hard 5×5 box, a Gaussian weights pixels near the center more, so the window has no corners of its own and treats every direction the same.</p><p>Then swap the square for a circle, a puzzle made entirely of border pieces:</p><pre>yy, xx = np.mgrid[:100, :100]<br>circle = (((yy - 50) ** 2 + (xx - 50) ** 2) &lt; 20 ** 2).astype(float)<br>print(f&quot;circle max R = {harris(circle).max():.1e}&quot;)   # 2.5e-08</pre><p>The strongest response on the circle is tens of thousands of times weaker than the square’s corners. A circle’s outline turns everywhere but never sharply, so at this window size every piece of it is a border piece. If you run corners() on it, the 1% threshold still lets a few pixel-staircase bumps through, because 1% of almost nothing is still almost nothing. A relative threshold assumes there is something worth finding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca977c895fdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cosine Similarity [ML Math]]]></title>
            <link>https://medium.com/@deardanny/cosine-similarity-ml-math-7db7ddaa8864?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db7ddaa8864</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 06:13:50 GMT</pubDate>
            <atom:updated>2026-09-27T06:13:50.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IwuK_CyWU5qQ_3CoTbrjw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rdehamer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryan De Hamer</a> on <a href="https://unsplash.com/photos/silhouette-of-people-walking-on-road-during-sunset-GfixHDntRvY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The last post started with this line:</p><pre>score = cosine_similarity(query_embedding, doc_embedding)</pre><p>That post was about the two objects going in. Arrows, each with a length and a direction. This one is about what happens inside the call.</p><p>The short version is in the name. Cosine similarity measures the angle between two arrows and ignores how long they are. The longer version is why you would want to ignore length at all, and how a formula that starts by multiplying numbers together ends up being about an angle.</p><h3>Two documents, two arrows</h3><p>Start with something small enough to draw. Pretend every document is described by just two numbers: how many times it says <em>game</em>, and how many times it says <em>recipe</em>.</p><pre>game   recipe   vector<br>query             3       4     [3, 4]<br>short doc         3       4     [3, 4]<br>long doc         30      40     [30, 40]<br>off-topic doc    40       5     [40, 5]</pre><p>The short doc matches the query exactly. The long doc says the same thing ten times over: same mix of topics, just longer. The off-topic doc is mostly about games and barely mentions recipes.</p><p>If you ranked these by “which one is about the same thing as the query,” you would put the short doc and the long doc tied at the top, and the off-topic doc last. Keep that ranking in mind. Two of the three common ways to compare vectors get it wrong.</p><h3>Multiply, then add</h3><p>The dot product takes two vectors of the same size, multiplies them position by position, and adds up the results.</p><pre>a · b = a1*b1 + a2*b2 + ... + an*bn</pre><p>For the query against each document:</p><pre>query · short     = 3*3  + 4*4  =   9 +  16 =  25<br>query · long      = 3*30 + 4*40 =  90 + 160 = 250<br>query · off-topic = 3*40 + 4*5  = 120 +  20 = 140</pre><p>Higher is supposed to mean more similar. So the dot product says the long doc is ten times more similar to the query than an exact copy of the query. It also says the off-topic doc beats the exact copy by a wide margin.</p><p>Both are wrong, and for the same reason. The dot product grows when the arrows get longer, and the long doc and the off-topic doc are simply longer arrows.</p><h3>What the dot product is actually measuring</h3><p>There is a second way to write the dot product, and it explains everything:</p><pre>a · b = ||a|| * ||b|| * cos(θ)</pre><p>||a|| and ||b|| are the lengths from the last post. θ (theta) is the angle between the two arrows. So the dot product is three things multiplied together: how long the first arrow is, how long the second arrow is, and how well they line up.</p><p>Only the last one is about direction. The first two are about size. That is the whole problem from the previous section, sitting right there in the formula.</p><p>You can check that the two versions agree on vectors small enough to picture. [1, 0] points right. [1, 1] points up and to the right, at 45 degrees.</p><pre>multiply and add:  1*1 + 0*1          = 1<br>lengths:           ||[1, 0]|| = 1,  ||[1, 1]|| = sqrt(2) ≈ 1.414<br>solve for cos(θ):  1 / (1 * 1.414)    ≈ 0.707<br>cos(45 degrees)                       ≈ 0.707</pre><p>Same number from both sides.</p><p>cos(θ) always lands between -1 and 1, and the three landmarks are worth memorizing:</p><ul><li><strong>1</strong>: same direction (θ = 0 degrees)</li><li><strong>0</strong>: perpendicular, nothing in common (θ = 90 degrees)</li><li><strong>-1</strong>: opposite directions (θ = 180 degrees)</li></ul><p>Word counts can never be negative, so for them the score stays between 0 and 1. Embeddings do have negative entries, so the full range is possible there.</p><h3>Dividing by the lengths is the entire trick</h3><p>If the lengths are the problem, divide them out. Rearrange the formula:</p><pre>cos(θ) = (a · b) / (||a|| * ||b||)</pre><p>That is cosine similarity. Nothing more. Run it on the three documents:</p><pre>query vs short:      25 / (5 * 5)      = 1.00<br>query vs long:      250 / (5 * 50)     = 1.00<br>query vs off-topic: 140 / (5 * 40.31)  ≈ 0.69</pre><p>The short doc and the long doc tie at 1.00, because they point in exactly the same direction. The off-topic doc drops to 0.69, about 46 degrees away. That is the ranking we wanted at the start.</p><p>This is the same move the last post ended on. Dividing [3, 4] and [30, 40] by their own lengths sent both of them to [0.6, 0.8]. Take the dot product of those two unit vectors and you get 0.36 + 0.64 = 1.00, the same answer. Cosine similarity just does that division inside the formula, so you never have to look at the unit vectors.</p><h3>Why not just use distance?</h3><p>The other obvious way to compare two vectors is the straight-line distance between their tips, Euclidean distance. Lower means closer:</p><pre>query vs short:      0.0<br>query vs long:      45.0<br>query vs off-topic: 37.0</pre><p>Euclidean distance says the off-topic doc is closer to the query than the long doc that says the same thing. Same mistake as the dot product, from the other side. A long arrow’s tip is far away from everything, so length leaks into the answer again.</p><p>That does not make Euclidean distance wrong. It is the right tool when length carries meaning: positions on a map, sensor readings, a customer who spent $30 versus $3,000. Cosine is the right tool when length is an artifact, like document length or raw word counts. Text embeddings are usually the second case.</p><p>There is one situation where the two agree completely. If every vector already has length 1, then</p><pre>||a - b||² = 2 - 2 * cos(θ)</pre><p>Smallest distance and largest cosine become the same thing, so they rank results in exactly the same order.</p><h3>Pitfalls</h3><p><strong>Cosine similarity is not a distance.</strong> Higher means more similar. The matching distance is 1 - cosine, and some libraries hand you that instead without making it obvious. scipy.spatial.distance.cosine(a, b) returns the distance. On the query and the off-topic doc it gives 0.31, not 0.69. It is very easy to read that as &quot;31% similar.&quot;</p><p><strong>sklearn wants 2D input.</strong> sklearn.metrics.pairwise.cosine_similarity compares every row of one matrix against every row of another, so two plain 1D arrays raise a ValueError. Wrap them, cosine_similarity([a], [b]), and you get back a 1×1 matrix, not a number.</p><p><strong>A zero vector has no direction.</strong> A document with none of the vocabulary words is [0, 0]. Its length is 0, so the formula divides by zero. NumPy gives you nan with a warning. sklearn quietly returns 0. Neither one stops your pipeline, so filter out empty inputs before they get there.</p><p><strong>If your embeddings are already normalized, cosine is just the dot product.</strong> When ||a|| = ||b|| = 1, the denominator is 1. Many embedding models return unit-length vectors, which is why vector databases offer “dot product” as a metric and it gives the same ranking as cosine. Check whether yours does before paying for the extra division.</p><h3>Try it</h3><pre>import numpy as np</pre><pre>def cosine(a, b):<br>    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))</pre><pre>query = np.array([3, 4])<br>docs = {<br>    &quot;short&quot;: np.array([3, 4]),<br>    &quot;long&quot;: np.array([30, 40]),<br>    &quot;off-topic&quot;: np.array([40, 5]),<br>}</pre><pre>for name, d in docs.items():<br>    print(f&quot;{name:10} dot={query @ d:&lt;5} cos={cosine(query, d):.2f}  dist={np.linalg.norm(query - d):.1f}&quot;)</pre><pre>short      dot=25    cos=1.00  dist=0.0<br>long       dot=250   cos=1.00  dist=45.0<br>off-topic  dot=140   cos=0.69  dist=37.0</pre><p>Three columns, three rankings. Only the middle one agrees with what you would say after reading the documents.</p><p>Then add &quot;huge&quot;: np.array([300, 400]) and run it again. The dot product jumps to 2500 and the distance to 495. Cosine does not move from 1.00. That is what ignoring length looks like.</p><p><em>Next in the series: Matrices [ML Math]. A matrix multiplication is a grid of dot products, which is also what attention is doing when it compares every word to every other word.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db7ddaa8864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Derivative Filters Break on Noisy Images [Computer Vision]]]></title>
            <link>https://medium.com/@deardanny/why-derivative-filters-break-on-noisy-images-computer-vision-4a5bb6e66fa1?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5bb6e66fa1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 21:07:56 GMT</pubDate>
            <atom:updated>2026-09-03T21:07:56.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFtJlmZU-iHSTX42XSFDWA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ionfet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ion Fet</a> on <a href="https://unsplash.com/photos/blue-eye-photo-QRawWgV6gmo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Edge detection starts with a derivative. The textbook version fails on the first real image you feed it. Here is what goes wrong and what fixes it.</em></p><p>An edge in an image is a place where brightness changes fast. That sentence is doing more work than it looks like, because “changes fast” is exactly what a derivative measures.</p><p>So the plan writes itself. Treat the image as a function, take its derivative, and look for large values.</p><p>The plan is correct. The naive implementation of it is not.</p><h3>The derivative of something that has no in between</h3><p>The calculus definition needs a limit:</p><pre>f&#39;(x) = lim (h -&gt; 0) [ f(x+h) - f(x) ] / h</pre><p>An image will not cooperate with that. There is a value at pixel 3 and a value at pixel 4 and nothing at all in between, so h cannot shrink past 1. The smallest step available is one pixel.</p><p>So we stop shrinking and use what we have. Take the neighbor on each side and divide by the distance between them:</p><pre>f&#39;(x) = [ f(x+1) - f(x-1) ] / 2</pre><p>Written as weights on three pixels, that is:</p><pre>[ -1, 0, 1 ] / 2</pre><p>The center is zero because the pixel’s own value is never used. Only the two neighbors matter.</p><p>On a clean signal this behaves exactly as advertised.</p><pre>signal:      10   20   10   200   210   250   250<br>derivative:   .    0    90   100   25    20    .</pre><p>The largest value lands at the point where the signal jumps from the low range to the high range. That index is the edge.</p><h3>Then you try it on a real signal</h3><p>Take a step edge and add a small amount of noise. Not dramatic noise. The kind any sensor produces.</p><pre>import numpy as np<br><br>x = np.arange(2000)<br>step = np.where(x &lt; 1000, 0.0, 1.0)<br>signal = step + np.random.normal(0, 0.05, 2000)<br>kernel = np.array([-0.5, 0.0, 0.5])<br>derivative = np.convolve(signal, kernel, mode=&quot;same&quot;)</pre><p>Plot signal and the step is obvious. You can point at where it happens.</p><p>Plot derivative and the step is gone. The whole plot is noise. There is a slightly taller spike near index 1000, but it is buried in a forest of spikes that are almost as tall.</p><p>The filter is correct. The math is correct. The result is useless.</p><h3>Why it happens</h3><p>The derivative asks one question at every position: how different are my two neighbors?</p><p>Noise is, by definition, a value that differs randomly from its neighbors. So on flat stretches where the answer should be zero, the filter keeps finding differences.</p><pre>true signal is flat:     100   100   100   100<br>what the sensor gives:   103    97   101    99<br>neighbor differences:      -3     2    -1</pre><p>Those small differences appear at every single position. The real edge produces one large difference. The noise produces two thousand small ones. When you plot all of them together, the two thousand win by volume.</p><p>There is a sharper way to say this. A derivative amplifies change. Noise is change. The filter is not malfunctioning, it is doing its job on a signal where most of the change is not the change you wanted.</p><h3>The fix is to average first</h3><p>Noise is random per sample, which means neighboring noise values tend to cancel when you average them. Real structure does not cancel, because it is consistent across neighbors.</p><p>So smooth before differentiating.</p><pre>from scipy.ndimage import gaussian_filter1d<br><br>smoothed = gaussian_filter1d(signal, sigma=20)<br>derivative = np.convolve(smoothed, kernel, mode=&quot;same&quot;)</pre><p>Now the plot has one clean bump centered on the edge and almost nothing elsewhere.</p><p>The Gaussian is doing the averaging, and sigma controls how much. Small sigma keeps fine detail and some noise. Large sigma removes more noise and blurs the edge wider. That single number is the whole trade, and choosing it is most of the tuning work in classical edge detection.</p><h3>The fix can be folded into one filter</h3><p>Convolution is associative, which gives a small but useful result:</p><pre>d/dx (image * gaussian) = image * (d/dx gaussian)</pre><p>Read that from right to left. Instead of blurring the image and then differentiating it, you can differentiate the Gaussian once, ahead of time, and convolve the image with that single kernel.</p><p>The result is called the derivative of a Gaussian. It looks like one bump above the axis and one below.</p><pre>derivative = gaussian_filter1d(signal, sigma=20, order=1)</pre><p>That order=1 is the entire two step pipeline in one pass. The kernel is precomputed, the image is touched once instead of twice, and the output is identical.</p><p>The shape is worth staring at for a second. One half of the kernel is positive and the other half is negative, so the filter is computing a weighted average on the right minus a weighted average on the left. The subtraction is the derivative. The averaging is the noise suppression. They are not two steps that happen to be adjacent. They are the same operation.</p><h3>Where you have already seen this</h3><p>The 3x3 Sobel kernel is this idea compressed into nine integers:</p><pre>[ -1  0  1 ]<br>[ -2  0  2 ]<br>[ -1  0  1 ]</pre><p>Split it apart and it is [1, 2, 1] stacked against [-1, 0, 1]. Averaging in one direction, differencing in the other. The [1, 2, 1] is a three sample Gaussian and the [-1, 0, 1] is the derivative from the top of this post.</p><p>Sobel is not a different technique. It is the same fix, hard coded at a fixed blur radius, small enough to be fast.</p><h3>Try it</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.ndimage import gaussian_filter1d<br><br>x = np.arange(2000)<br>signal = np.where(x &lt; 1000, 0.0, 1.0) + np.random.normal(0, 0.05, 2000)<br>kernel = np.array([-0.5, 0.0, 0.5])<br>fig, ax = plt.subplots(3, 1, figsize=(9, 6), sharex=True)<br>ax[0].plot(signal);                                       ax[0].set_ylabel(&quot;signal&quot;)<br>ax[1].plot(np.convolve(signal, kernel, mode=&quot;same&quot;));     ax[1].set_ylabel(&quot;naive&quot;)<br>ax[2].plot(gaussian_filter1d(signal, 20, order=1));       ax[2].set_ylabel(&quot;DoG&quot;)<br>plt.tight_layout(); plt.show()<br>plt.tight_layout(); plt.show()</pre><p>Three panels. The middle one is why nobody uses the naive filter. The bottom one is why every edge detector begins with a blur.</p><p>Then set sigma to 2, and to 100, and watch the bump go from noisy to comically wide. That parameter is the whole game.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5bb6e66fa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vectors [ML Math]]]></title>
            <link>https://medium.com/@deardanny/vector-ml-math-11b117737d2d?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/11b117737d2d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vector]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 19:34:23 GMT</pubDate>
            <atom:updated>2026-09-03T21:23:11.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGvmn2pRRohfpstlxImeog.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@silverkblack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vitaly Gariev</a> on <a href="https://unsplash.com/photos/young-boy-writing-complex-formulas-on-a-chalkboard-BpCrX9nwyC0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Every embedding you use is a vector. Here is what that actually means, and why its length matters less than you think.</em></p><p>You have probably written this line, or something close to it:</p><pre>score = cosine_similarity(query_embedding, doc_embedding)</pre><p>It works. You get a number back, you sort by it, you return the top results. The pipeline ships.</p><p>There are two objects being compared in that call. Not “768-dimensional embeddings,” which is just restating the shape, but what kind of thing they actually are, and what it means for two of them to point the same way.</p><p>This post is about that object. Not the similarity part yet, just the object.</p><h3>A vector is an arrow</h3><p>That is the whole definition. An arrow carries exactly two pieces of information: which way it points (direction), and how long it is (length, or magnitude).</p><p>When you write v = [3, 4], you are describing an arrow that starts at the origin and goes 3 steps right and 4 steps up.</p><pre>^ y<br>    4 |      * (3, 4)<br>      |     /|<br>      |    / |<br>      |   /  |<br>      |  /   |<br>      | /    |<br>      +------+---&gt; x<br>      0      3</pre><p>The numbers 3 and 4 are called the components. They are instructions for how to get to the tip: go this far horizontally, then this far vertically.</p><p>An embedding is the same thing with 768 instructions instead of 2. You cannot draw it, but nothing about the definition changes. It is still an arrow. It still has a direction and a length.</p><h3>Length: it is just Pythagoras</h3><p>Here is the question that made this click for me.</p><p>You walk 3 blocks east, then 4 blocks north. How far are you from where you started?</p><p>Not 7. That is how far you walked. The distance from your starting point, in a straight line, is 5.</p><pre>        end *<br>            |<br>            | 4 blocks north<br>            |<br>  start *---+<br>     3 blocks east</pre><p>That number comes from the Pythagorean theorem. In a right triangle, the two short sides and the long side (the hypotenuse) are related by:</p><pre>a² + b² = c²</pre><p>So:</p><pre>c = sqrt(3² + 4²) = sqrt(9 + 16) = sqrt(25) = 5</pre><p>Now look back at the arrow. The arrow is the hypotenuse. The components are the two short sides.</p><p>That means the length of a vector is:</p><pre>||v|| = sqrt(3² + 4²) = 5</pre><p>And that is exactly what np.linalg.norm(v) returns.</p><h3>The formula does not care how many dimensions you have</h3><p>Two dimensions:</p><pre>||v|| = sqrt(v1² + v2²)</pre><p>Three dimensions:</p><pre>||v|| = sqrt(v1² + v2² + v3²)</pre><p>768 dimensions:</p><pre>||v|| = sqrt(v1² + v2² + ... + v768²)</pre><p>Square everything, add it up, take the square root. The pattern never changes.</p><p>This is worth sitting with for a second. You cannot picture 768 dimensions, and you never will. But you do not have to. The geometry you can picture in 2D gives you the formula, and the formula keeps working when the picture runs out. That is most of what “high-dimensional space” means in practice.</p><h3>What tripped me up</h3><p>I assumed “norm” meant something like an average, or some kind of normalization step. The word sounds administrative. It sounds like preprocessing.</p><p>It is not. The norm is the length of the arrow. That is the entire meaning.</p><p>Once I stopped reading np.linalg.norm(v) as “normalize v somehow” and started reading it as “how long is this arrow,” a lot of code I had written became legible in a way it had not been before. The line v / np.linalg.norm(v) stopped being a formula I had copied and became an obvious operation: divide an arrow by its own length and you get an arrow of length 1 pointing the same way.</p><h3>Length and direction come apart</h3><p>Here is the idea that everything in the next post depends on.</p><p>Take two vectors:</p><pre>a = [3, 4]<br>b = [30, 40]</pre><p>These point in exactly the same direction. b is just ten times longer. Same heading, different magnitude.</p><p>That separation is not a technicality. It is the reason cosine similarity exists at all.</p><p>Think about two documents. One is a short blog post about dogs. The other is a 400-page book about dogs. Represent both as word counts and the book’s vector will be enormous compared to the post’s. Measure the straight-line distance between them and they look completely unrelated.</p><p>But they point the same way. Same topic, different volume.</p><p>Most of the time in ML, the direction is the signal and the length is an artifact of something you do not care about: document length, token count, how loud the input happened to be. So we built a similarity measure that throws the length away and keeps only the direction.</p><p>That measure is cosine similarity, and it is the next post.</p><h3>Try it</h3><pre>import numpy as np<br><br>a = np.array([3, 4])<br>b = np.array([30, 40])<br>print(np.linalg.norm(a))          # 5.0<br>print(np.linalg.norm(b))          # 50.0<br>print(a / np.linalg.norm(a))      # [0.6 0.8]<br>print(b / np.linalg.norm(b))      # [0.6 0.8]</pre><p>Two arrows with very different lengths. Divide each by its own length and they land on the same pair of numbers, because they were always pointing the same way.</p><p>That last line is the whole point of the next post, arriving early.</p><p><em>Next in the series: Cosine Similarity [ML Math]. What the dot product is measuring, and why dividing by the lengths is the entire trick.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b117737d2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Valid Palindrome [Python Algorithm]]]></title>
            <link>https://medium.com/@deardanny/valid-palindrome-python-algorithm-c2f040bb6f1e?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2f040bb6f1e</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 04:41:56 GMT</pubDate>
            <atom:updated>2026-08-28T04:41:56.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ard8pDZEBsB2ib-uFm8SMg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bamin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pierre Bamin</a> on <a href="https://unsplash.com/photos/gray-cross-with-blue-background-dULbsLNbHWk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Third post in the series. This one is less about choosing a data structure and more about a distinction I’d been getting wrong all evening: which string methods change the original, and which ones hand you a new one.</p><h3>Problem</h3><p>Given a string, return true if it reads the same forward and backward. Comparison is case-insensitive and ignores anything that isn&#39;t a letter or a digit.</p><pre>&quot;Was it a car or a cat I saw?&quot;  -&gt;  true<br>&quot;tab a cat&quot;                     -&gt;  false</pre><p>The first example becomes &quot;wasitacaroracatisaw&quot; once you strip the spaces, the question mark, and the capitals. That reads the same in both directions.</p><p>The second becomes &quot;tabacat&quot;, which does not. Reversed it&#39;s &quot;tacabat&quot;.</p><h3>The Two Halves</h3><p>The problem looks fiddly until you notice it’s two independent steps that happen to sit in the same function.</p><ol><li><strong>Clean the string.</strong> Keep letters and digits, drop everything else, lowercase what’s left.</li><li><strong>Compare it to its reverse.</strong></li></ol><p>Step 2 is one line once step 1 is done. Almost all of the work, and all of my mistakes, were in step 1.</p><h3>Solution</h3><pre>def is_palindrome(s):<br>    cleaned = &quot;&quot;<br>    for char in s:<br>        if char.isalnum():<br>            cleaned += char.lower()<br>    return cleaned == cleaned[::-1]</pre><p>Three pieces of syntax carry this.</p><p>char.isalnum() asks whether a character is alphanumeric, which is exactly the filter the problem describes. Letters and digits return True; spaces, punctuation, and symbols return False.</p><p>char.lower() returns the lowercase version, which is what makes the comparison case-insensitive.</p><p>cleaned[::-1] reverses the string. It&#39;s slice syntax with a step of -1, meaning &quot;walk through this from the end to the start.&quot;</p><p>Tracing &quot;Wa?&quot;:</p><pre>char=&quot;W&quot;   isalnum -&gt; True    cleaned = &quot;w&quot;<br>char=&quot;a&quot;   isalnum -&gt; True    cleaned = &quot;wa&quot;<br>char=&quot;?&quot;   isalnum -&gt; False   skipped, cleaned = &quot;wa&quot;</pre><p>Then &quot;wa&quot; == &quot;aw&quot; is False.</p><h3>Complexity</h3><p><strong>Time: O(n).</strong> One pass to build the cleaned string, one to reverse it, one to compare.</p><p><strong>Space: O(n).</strong> The cleaned string is a second copy of the input.</p><h3>Doing It Without Extra Space</h3><p>The version above is the one to write first, but interviewers often follow up with “can you do it in O(1) space?” You can, by walking two pointers inward from both ends instead of building a new string.</p><pre>def is_palindrome(s):<br>    left, right = 0, len(s) - 1<br>    while left &lt; right:<br>        while left &lt; right and not s[left].isalnum():<br>            left += 1<br>        while left &lt; right and not s[right].isalnum():<br>            right -= 1<br>        if s[left].lower() != s[right].lower():<br>            return False<br>        left += 1<br>        right -= 1<br>    return True</pre><p>The inner while loops skip over anything that isn&#39;t alphanumeric, so the pointers only ever compare real characters. Still O(n) time, but no second string, so <strong>O(1) space</strong>.</p><p>It’s harder to write correctly under pressure, and the left &lt; right guard inside the skip loops is easy to forget. Without it, a string of only punctuation runs one pointer past the other. I&#39;d lead with the first solution and mention this one as the follow-up.</p><h3>Pitfalls</h3><p><strong>Using the whole string where I meant one character.</strong> My first attempt:</p><pre>for char in s:<br>    if s.isalnum():          # checking the entire string<br>        cleaned += char.lower()</pre><p>s is the full input; char is the single character this iteration is looking at. &quot;Was it a car or a cat I saw?&quot;.isalnum() is False, because the string contains spaces. So the condition never passed, the body never ran, and cleaned stayed empty on every input.</p><p>What makes this one worth writing down is that it produced no error. The code ran, returned True for everything (an empty string equals its own reverse), and looked plausible. I made this exact mistake three times in a row before it stuck.</p><p><strong>Calling </strong><strong>.lower() and throwing the result away.</strong> This line does nothing:</p><pre>char.lower()</pre><p>.lower() returns a new lowercase string. It does not modify char. If nothing catches the return value, the new string is discarded and the original is untouched.</p><pre>char = &quot;W&quot;<br>char.lower()<br>print(char)          # &quot;W&quot;, unchanged<br>char = char.lower()<br>print(char)          # &quot;w&quot;</pre><p>This is the distinction I actually took away from the problem. Some methods return a new value and leave the original alone; others modify in place and return nothing.</p><pre>&quot;ABC&quot;.lower()        # returns &quot;abc&quot;<br>sorted([3, 1, 2])    # returns [1, 2, 3]<br>&quot; hi &quot;.strip()       # returns &quot;hi&quot;<br>nums.append(4)       # modifies nums, returns None<br>nums.sort()          # modifies nums, returns None</pre><p>Strings are immutable in Python, so every string method falls in the first group. There is no such thing as a string method that edits in place. Lists give you both kinds, which is where the confusion starts: sorted(nums) and nums.sort() do the same job with opposite mechanics.</p><p>The rule of thumb: if a method returns something, you have to use it. If it returns None, it already did the work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2f040bb6f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Group Anagrams [Python Algorithm]]]></title>
            <link>https://medium.com/@deardanny/group-anagrams-python-algorithm-863f0e90bb84?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/863f0e90bb84</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 05:36:41 GMT</pubDate>
            <atom:updated>2026-08-27T05:36:41.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8q0JsR9cIgqk0YaKtpbRJA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/photos/red-yellow-and-blue-lego-blocks-qodjMu0byZ8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Second post in the series. Two Sum was about remembering <em>where</em> you saw something. This one is about deciding <em>what counts as the same thing</em>.</p><h3>Problem</h3><p>Given a list of strings, group the anagrams together. Return the groups in any order.</p><pre>strs = [&quot;eat&quot;, &quot;tea&quot;, &quot;tan&quot;, &quot;ate&quot;, &quot;nat&quot;, &quot;bat&quot;]<br><br>[[&quot;eat&quot;, &quot;tea&quot;, &quot;ate&quot;], [&quot;tan&quot;, &quot;nat&quot;], [&quot;bat&quot;]]</pre><p>Anagrams are words made of the same letters in the same quantities. eat, tea, and ate all use one a, one e, one t.</p><p>“Any order” means the grader doesn’t care about the order of the groups or the order inside them. [[&quot;bat&quot;], [&quot;tan&quot;,&quot;nat&quot;], [&quot;eat&quot;,&quot;tea&quot;,&quot;ate&quot;]] is equally correct.</p><h3>Brute Force</h3><p>Compare every word against every other word:</p><pre>def group_anagrams(strs):<br>    groups = []<br>    used = [False] * len(strs)<br>    for i in range(len(strs)):<br>            if used[i]:<br>                continue<br>            group = [strs[i]]<br>            used[i] = True<br>            for j in range(i + 1, len(strs)):<br>                if not used[j] and sorted(strs[i]) == sorted(strs[j]):<br>                    group.append(strs[j])<br>                    used[j] = True<br>            groups.append(group)<br>        return groups</pre><p>It works, but look at the bookkeeping. You need a used array so words don&#39;t land in two groups, and you&#39;re re-sorting the same word over and over inside the inner loop.</p><p><strong>Time: O(n² · k log k)</strong> where n is the number of words and k is the average word length.</p><h3>Key Insight</h3><p>The brute force asks “is word A an anagram of word B?” for every pair. That’s the wrong question, because it’s still pairwise.</p><p>Better question: <strong>what is this word’s group name?</strong></p><p>Sorting gives you one, for free:</p><pre>sorted(&quot;eat&quot;)  -&gt;  [&#39;a&#39;, &#39;e&#39;, &#39;t&#39;]<br>sorted(&quot;tea&quot;)  -&gt;  [&#39;a&#39;, &#39;e&#39;, &#39;t&#39;]<br>sorted(&quot;ate&quot;)  -&gt;  [&#39;a&#39;, &#39;e&#39;, &#39;t&#39;]</pre><p>Every anagram of a word sorts to the same sequence. So sorting turns a comparison problem into a labeling problem. Instead of checking words against each other, you compute one label per word and let words with matching labels fall into the same bucket.</p><p>That’s a dictionary. The label is the key, the group is the value.</p><h3>Solution</h3><pre>def group_anagrams(strs):<br>    groups = {}<br>    for word in strs:<br>        key = &quot;&quot;.join(sorted(word))<br>        if key not in groups:<br>            groups[key] = []<br>        groups[key].append(word)<br>    return list(groups.values())</pre><p>Watching groups fill up:</p><pre>&quot;eat&quot;  key=&quot;aet&quot;   new key    -&gt;  {&quot;aet&quot;: [&quot;eat&quot;]}<br>&quot;tea&quot;  key=&quot;aet&quot;   exists     -&gt;  {&quot;aet&quot;: [&quot;eat&quot;, &quot;tea&quot;]}<br>&quot;tan&quot;  key=&quot;ant&quot;   new key    -&gt;  {&quot;aet&quot;: [...], &quot;ant&quot;: [&quot;tan&quot;]}<br>&quot;ate&quot;  key=&quot;aet&quot;   exists     -&gt;  {&quot;aet&quot;: [&quot;eat&quot;, &quot;tea&quot;, &quot;ate&quot;], ...}<br>&quot;nat&quot;  key=&quot;ant&quot;   exists     -&gt;  {..., &quot;ant&quot;: [&quot;tan&quot;, &quot;nat&quot;]}<br>&quot;bat&quot;  key=&quot;abt&quot;   new key    -&gt;  {..., &quot;abt&quot;: [&quot;bat&quot;]}</pre><p>At the end, the keys have done their job and you only want the buckets, so .values() pulls them out. It returns a view object rather than a list, which is why it&#39;s wrapped in list().</p><h3>Complexity</h3><p><strong>Time: O(n · k log k).</strong> One pass over n words, and sorting each k-length word costs k log k.</p><p><strong>Space: O(n · k).</strong> Every word ends up stored in the dictionary.</p><p>Compared to the brute force, the pairwise comparison collapses into a single pass. The sorting cost per word doesn’t change; what changes is that you do it once per word instead of once per pair.</p><h3>Pitfalls</h3><p><strong>Dictionaries don’t have </strong><strong>.append().</strong> This was my first attempt:</p><pre>groups = {}<br>for word in strs:<br>    groups.append(word)      # AttributeError</pre><p>append is a list method. A dictionary has no &quot;end&quot; to append to, because entries are stored under labels rather than in sequence. You add to a dictionary by naming the slot: groups[key] = value.</p><p><strong>groups.append(word) and </strong><strong>groups[key].append(word) are different calls.</strong> Once the pitfall above clicked, this one still took a moment. In the working solution, append is being called on groups[key], which is a list, not on groups, which is a dictionary. The dictionary holds lists; the append happens one level down.</p><p><strong>You can’t append to a bucket that doesn’t exist yet.</strong> The first time you see &quot;aet&quot; there&#39;s nothing there to append to, so the empty list has to be created first:</p><pre>if key not in groups:<br>    groups[key] = []<br>groups[key].append(word)</pre><p><strong>Forgetting </strong><strong>sorted and keeping </strong><strong>join.</strong> My submission had this:</p><pre>key = &quot;&quot;.join(word)          # returns &quot;eat&quot; unchanged</pre><p>&quot;&quot;.join() glues a sequence of characters back into a string. On its own it&#39;s a no-op, so every word became its own key and nothing grouped. The sorting is what makes anagrams collide; the join is only there because sorted() hands back a list, and lists can&#39;t be dictionary keys.</p><p>That last part is worth stating plainly, because it explains why the line looks convoluted:</p><pre>sorted(&quot;eat&quot;)             # [&#39;a&#39;, &#39;e&#39;, &#39;t&#39;]   a list, unusable as a key<br>&quot;&quot;.join(sorted(&quot;eat&quot;))    # &quot;aet&quot;             a string, usable as a key</pre><h3>Worth Knowing</h3><p>Two refinements you’ll see in other people’s solutions.</p><p>collections.defaultdict removes the existence check:</p><pre>from collections import defaultdict<br><br>def group_anagrams(strs):<br>    groups = defaultdict(list)<br>    for word in strs:<br>        groups[&quot;&quot;.join(sorted(word))].append(word)<br>    return list(groups.values())</pre><p>A defaultdict(list) creates an empty list automatically the first time a key is touched, so the if key not in groups block disappears. Cleaner, though I&#39;d write the explicit version in an interview unless asked, since it makes the logic visible.</p><p>You can also drop the sort entirely by using letter counts as the key:</p><pre>key = tuple(sorted(Counter(word).items()))</pre><p>or, for lowercase-only input, a 26-length tuple of counts. That brings the per-word cost from k log k down to k, giving <strong>O(n · k)</strong> overall. It&#39;s the theoretically better answer, but sorting is easier to write correctly under pressure and k is usually small.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=863f0e90bb84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Sum [Python Algorithm]]]></title>
            <link>https://medium.com/@deardanny/two-sum-python-algorithm-318ba682595b?source=rss-ad723feb0ea0------2</link>
            <guid isPermaLink="false">https://medium.com/p/318ba682595b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Daniel (Heedong) Jang]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 04:22:10 GMT</pubDate>
            <atom:updated>2026-08-26T04:22:10.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAMstA3di11L9MnFmZN7Kg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the first post in a series where I work through algorithm problems in Python and write down what actually tripped me up. I’m keeping these notes for myself as much as for anyone else, so I’m including the wrong turns, not just the final answer.</p><p>Starting with Two Sum, because everyone does.</p><h3>Problem</h3><p>Given a list of integers and a target value, return the indices of the two numbers that add up to the target.</p><pre>nums = [2, 7, 11, 15], target = 9   -&gt;   [0, 1]<br>nums = [3, 2, 4],      target = 6   -&gt;   [1, 2]</pre><p>Two details that matter more than they look:</p><ol><li>You return <strong>indices</strong>, not the values. In the first example the answer is [0, 1], not [2, 7].</li><li>You can’t use the same element twice. In the second example, 3 + 3 would hit the target, but there&#39;s only one 3 in the list.</li></ol><h3>Brute Force</h3><p>The obvious approach is to try every pair.</p><pre>def two_sum(nums, target):<br>    for i in range(len(nums)):<br>        for j in range(i + 1, len(nums)):<br>            if nums[i] + nums[j] == target:<br>                return [i, j]<br>    return []</pre><p>This works. j starts at i + 1 so you never pair an element with itself and never check the same pair twice.</p><p>The problem is the nested loop. For a list of n elements you check roughly n²/2 pairs. At n = 10,000 that&#39;s about 50 million comparisons, which is where LeetCode starts handing out Time Limit Exceeded.</p><p><strong>Time: O(n²). Space: O(1).</strong></p><h3>Key Insight</h3><p>The brute force wastes work by asking a symmetric question: “do these two numbers add up to the target?” You ask it once for every pair.</p><p>Flip it into a one-sided question instead. For any number n, there is exactly one value that completes it:</p><pre>partner = target - n</pre><p>If target is 9 and the current number is 2, the partner has to be 7. Nothing else works. So instead of scanning the rest of the list for a match, you can ask a single question per number: <strong>have I already seen my partner?</strong></p><p>That turns the inner loop into a lookup. And a lookup in a dictionary is O(1), because a hash table jumps straight to the slot instead of scanning from the front.</p><p>One more requirement: the problem wants indices, so remembering <em>which</em> numbers you’ve seen isn’t enough. You need to remember <em>where</em> you saw them. That’s why this is a dictionary and not a set. The number is the key, the index is the value.</p><h3>Solution</h3><pre>def two_sum(nums, target):<br>    seen = {}<br><br>    for i, n in enumerate(nums):<br>        partner = target - n<br>        if partner in seen:<br>            return [seen[partner], i]<br>        seen[n] = i<br>    return []</pre><p>enumerate gives you the index and the value together on each iteration, which you need because the answer is made of indices.</p><p>Tracing nums = [2, 7, 11, 15], target = 9:</p><pre>i=0   n=2   partner=7   not in seen   -&gt;  store 2:0<br>i=1   n=7   partner=2   found at 0    -&gt;  return [0, 1]</pre><p>Two iterations and it’s done. The 11 and 15 are never touched.</p><h3>Complexity</h3><p><strong>Time: O(n).</strong> One pass through the list, and each dictionary lookup and insert is O(1) on average.</p><p><strong>Space: O(n).</strong> In the worst case, no pair matches and every element ends up in the dictionary.</p><p>This is the classic trade: the brute force uses no extra memory but O(n²) time, and the hash map buys O(n) time by spending O(n) space. For most interview settings that’s the trade you want, but it’s worth being able to say out loud that you’re making it.</p><h3>Pitfalls</h3><p>These are the ones I got wrong, in the order I got them wrong.</p><p><strong>Declaring the dictionary after the loop, or not at all.</strong> seen is first referenced inside the loop body, so if you write the loop first (which is what I did) it&#39;s easy to run it and get a NameError for something you were sure you&#39;d written. The initialization is the first line of the function, before anything else.</p><p><strong>Returning too early, and the reason it’s correct here.</strong> A return inside a loop ends the entire function immediately, not just the current iteration. I&#39;d been burned by this an hour earlier: I wrote a search function that returned on its very first pass and never examined the rest of the list. Here, the early return is right, because once you&#39;ve found the pair there is nothing left to look for. Same syntax, opposite outcome. The question to ask is always &quot;does finding one answer mean I&#39;m done?&quot;</p><p><strong>Storing before checking.</strong> This one is subtle and it silently produces wrong answers instead of errors.</p><pre>seen[n] = i           # WRONG ORDER<br>if partner in seen:<br>    return [seen[partner], i]</pre><p>With nums = [2, 5] and target = 4, storing first means 2 is already in seen when you ask whether its partner 2 is there. It is, because you just put it there. You return [0, 0] and claim a number paired with itself.</p><p>Check first, then store. The invariant is that seen should only ever contain elements that come <strong>before</strong> the current one.</p><p><strong>Confusing </strong><strong>print with </strong><strong>return.</strong> Not specific to this problem, but it cost me a submission. print writes to the screen; return hands a value back to the caller. LeetCode&#39;s grader calls your function and inspects what comes back, so a function that prints the right answer and returns nothing fails with Your output was None.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=318ba682595b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>