<?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 Ball on Medium]]></title>
        <description><![CDATA[Stories by Daniel Ball on Medium]]></description>
        <link>https://medium.com/@balleto333?source=rss-803803d8b6ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3G196SlLLfs5PPkZp6YfEA.jpeg</url>
            <title>Stories by Daniel Ball on Medium</title>
            <link>https://medium.com/@balleto333?source=rss-803803d8b6ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:19:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balleto333/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[Bit Manipulation Tutorial Using JavaScript]]></title>
            <link>https://medium.com/@balleto333/bit-manipulation-tutorial-using-javascript-b27267cf0f1d?source=rss-803803d8b6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/b27267cf0f1d</guid>
            <category><![CDATA[bit-manipulation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Daniel Ball]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 08:31:17 GMT</pubDate>
            <atom:updated>2022-11-13T20:23:08.309Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is intended to be a brief introduction to Bit Manipulation. It will discuss what it is, why it’s important, go over some important concepts to help start understanding it and we’ll walk through two examples to show how it can be applied.</p><h3><strong>Prerequisites</strong></h3><ul><li>Basic knowledge of at least one programming language, Big O notation, how to convert a positive number to binary and the Bitwise operators below.</li><li>Reference: <a href="https://www.w3schools.com/js/js_bitwise.asp">https://www.w3schools.com/js/js_bitwise.asp</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*rWEDIkRYcAupdiUJe-7qew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*taTOvm_MVXKA2g9kTjxAqA.png" /></figure><h3><strong>What is Bit Manipulation?</strong></h3><p>We’ll look at one of the most common ways algorithms use integers for problems. That’s a 32-bit signed integer. A 32-bit signed integer class is in the range of -2,147,483,648 and 2,147,483,647. You will see a lot of algorithms use this as the upper/lower bounds because otherwise the number starts getting too big, hard to represent, memory consumption can start being an issue and the range is so big it tends to cover most problems for the task at hand. In base 2(power of two) this range can also be represented as -2³¹ to 2³¹. In Computer Science every number in this range has 32 bits, which is the binary representation of the number. This is an example of what the following four numbers are below in binary:</p><p>One(1): 00000000000000000000000000000001</p><p>Two(2): 00000000000000000000000000000010</p><p>Four(4): 00000000000000000000000000000100</p><p>Eight(8): 00000000000000000000000000001000</p><p>This is where bit manipulation comes in. We can shift(&lt;&lt; or &gt;&gt;) the bits to manipulate the value of a number. We can also use the other operators to manipulate them and to specifically target a bit at a specific position.</p><p>It’s also important to know and get used to converting numbers to binary. There is surprisingly a pretty fast way to do this for smaller numbers and I’ll show you here because it can be helpful when attacking Bit Manipulation algorithms. You can convert numbers to binary very fast by using the powers of two. Let’s look at the first(looking right to left ) 16 bits of a 32-bit signed integer(<strong>only using the first</strong> <strong>16 bits so we can fit it properly in the table, this is also done in a similar fashion in other sections for readability</strong>):</p><ul><li>** 2 ^ 1 is: 2 to the power of 1 ***</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sn5t3KrtkJKUn1BcJ1CfvA.png" /></figure><p>Every bit position is a power of 2…so what is 48 in binary? To convert the number to binary look at the table above and start setting the bits starting on the left side of the table and going to the right.</p><p>110000 = 48</p><p>Notice how I said “setting the bits,” a bit is considered set if its value is 1 and Not set if its value is zero.</p><p>We set the first bit at position 6 (32 or 2⁵) because that’s the max value that fits into 48.</p><p>100000 = 32</p><p>We have 16(48–32) left over so we set the bit again at position 5</p><p>110000 = 48</p><p>We have nothing left(16–16) over after setting this bit so the rest of the bits are zero and we’re done converting 48 into binary.</p><p>Here are some more examples:</p><p>110001 = 49</p><p>110010 = 50</p><p>1011001 = 89</p><p>Many Computers will use a combination of Bit Manipulation techniques to achieve operations such as addition, subtraction, multiplication and division. Usually, bitwise operations are faster than the multiplication/division operators because you can shift bits to the left to multiply or shift bits to the right to divide a number. Keep in mind programming languages handle Bit Manipulation differently and some are faster than others. In Computer Science, bit manipulation can be an important topic because it helps explain what computers are doing behind the scenes. Aside from speed, there are many space-saving techniques that will help optimize algorithms, reduce memory usage and achieve constant(O(1)) Space Complexity which is where I think Bit Manipulation really shines.</p><h3><strong>How to Convert a number to binary in JavaScript</strong></h3><p>For positive numbers:</p><p>(2).toString(2) = 00000000000000000000000000000010</p><p>For negative numbers:</p><p>(-2 &gt;&gt;&gt; 0).toString(2) = 11111111111111111111111111111110</p><h3><strong>What is Bitmasking?</strong></h3><p>When manipulating bits and changing values a common technique is to create a temporary value(this is our mask or bit mask) and use some combination of Bitwise Operators to get the result. One common technique is to determine if an integer is odd or even. Is 49 odd or even?</p><p>Create a “mask,” this mask will be the number 1 and use the &amp; operator</p><p>49 = 00000000000000000000000000110001 = 49</p><p>Mask = 00000000000000000000000000000001 = 1</p><p>49 &amp; Mask = 00000000000000000000000000000001 = 1</p><p>If the result is 1 the number is odd…the “<strong><em>&amp;”</em></strong> operator only returns 1 if both bits are set at that specific position and zero otherwise. An odd number will always have a 1…so here we’re just checking to see what the first bit is set to. Even(such as odd/even) numbers won’t have a bit set at the very first bit.</p><p>So Bitmasking or masks are used many times in different ways in a single algorithm to help achieve the result we want. Loops can use a different mask during each iteration and the masks may target only some positions or all positions of the bits in the target number.</p><p>Sample Problems via <a href="http://www.leetcode.com/">www.leetcode.com</a> site.</p><p>It’s recommended that you read the problem on the site before proceeding.</p><p><a href="https://leetcode.com/problems/number-of-1-bits/"><strong>Number of 1 Bits</strong></a><strong> (https://leetcode.com/problems/number-of-1-bits/)</strong></p><p>7 in binary is 00000000000000000000000000000111</p><p>There are three 1 bits so 3 is the answer.</p><p><a href="https://leetcode.com/problems/number-of-1-bits/">https://leetcode.com/problems/number-of-1-bits/</a></p><p>We need to count the number of bits that are set(which is 1) at every bit position for our input which is either a positive or negative number. Normally we could just shift the bits to the right and check if the right-most bit is 1 but shifting doesn’t work with negative numbers. So we set a count of 0 and keep increasing the count for every iteration while N(our input) is not zero. We create a mask with n-1 which basically allows us to mark that bit being counted before moving on to the next bit. The AND(&amp;) operator helps us mark this bit being set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*czk7muNC7sUUaWDGPdfvPg.png" /></figure><p>7 = 111 in binary (only showing the first 3 bits, the other 29 bits are zero)</p><p>First Iteration:</p><p>Increase count to 1 since n = 111</p><p>N-1 = 6 = 110</p><p>111 &amp; 110 = 110</p><p>Second Iteration:</p><p>Increase the count to 2 since n = 110</p><p>N-1(6–1) = 5 = 101</p><p>110 &amp; 101 = 100</p><p>Third Iteration:</p><p>Increase the count to 3 since n = 100</p><p>N-1(2–1) = 3 = 011</p><p>100 &amp; 011 = 0</p><p>Return the result which is 3 since n = 0</p><h3><a href="https://leetcode.com/problems/majority-element/">Majority Element</a> (https://leetcode.com/problems/majority-element/)</h3><p>[2,4,9,2,2]…2 occurs the most, and there are 3 occurrences, so 2 is the answer.</p><p>The problem says we’re guaranteed to have an element that occurs more than any other element in the input array so if we have 5 elements in our input array this element will occur at least 3 times(it’s the majority element), however the order of the numbers could be random. The input array being guaranteed to have an element that occurs the majority amount of time is important because otherwise this approach would not work. Normally a good way and possibly more efficient way to solve this algorithm would be to create a hash map and store the number of times an element appears. However, this uses additional space because we use another data structure and that structure will have about O( n — (n/ 2)) space which will equate to a Space Complexity of O(n). We could sort the numbers but then the time complexity would be O(n * log(n)). We can do this another way.</p><p>We’ll build our answer one bit at a time…all 32 of them. We start out with a result of zero and for every iteration(32 of them) we iterate over our input array and check to see if that bit position is set(for every element in the array). After every iteration, we’ll know if we have to set that bit position to 1 in our result because our majority element will have that bit set and we’re counting them and they occur the majority amount of time. For example, [3,2,3,1,3] has three occurrences of the number 3 and thus the position(all 32 of them) of those bits being set will also have the most occurrences when compared to the other numbers that have those bits set. We can target those bits by counting them to build our answer one bit at a time and simply count the “Majority” element at every bit iteration…we’ll look at the first bit and then the second and so on. Our Space Complexity will be constant since we allocate space for only one integer that has a max constant amount of 32 bits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*2_AKu_xhkNekHH3QQJY0KA.png" /></figure><p>majority = 0</p><p>[3,2,3,1,3] = input array</p><p>[11,10,11,01,11] = input array in binary</p><p><strong>First Iteration</strong></p><p>Count = 0</p><p>Mask = 1 &lt;&lt; 0 = 1 ( looking at the very first bit)</p><p>(3)11 &amp; 01(mask) = 01</p><p>(2)10 &amp; 01(mask) = 00</p><p>(3)11 &amp; 01(mask) = 01</p><p>(1)01 &amp; 01(mask) = 01</p><p>(3)11 &amp; 01(mask) = 01</p><p>Count = 4 (because 4 of 5 of the results is &gt; 0)</p><p>4 (one’s) <strong>&gt;</strong> 1(zero’s), so we update the bit position of majority</p><p><strong>majority</strong> = (0 | 1) <strong>= 1</strong>, the OR operator only needs 1 of the bits to be set to update it.</p><p><strong>Second Iteration</strong></p><p>Mask = 1 &lt;&lt; 1 = 10 (looking at the second bit…checking to see if it is set)</p><p>(3)11 &amp; 10(mask) = 10</p><p>(2)10 &amp; 10(mask) = 10</p><p>(3)11 &amp; 10(mask) = 10</p><p>(1)01 &amp; 10(mask) = 00</p><p>(2)11 &amp; 10(mask) = 10</p><p>Count = 4 (we reset it every iteration, and if the result is more than zero we know a 1 bit is set at this position)</p><p>4 &gt; 1, so we update the bit position of the majority</p><p><strong>majority</strong> = (01 | 10) <strong>= 11</strong>, the OR operator only needs 1 of the bits to be set to update it.</p><p>The next 30 iterations will be 0 since every number in our input array has zeros at those positions. We’re done, our result is:</p><p>00000000000000000000000000000011 which equals 3 and that is our answer.</p><h3><strong>Conclusion</strong></h3><p>Bit manipulation is about moving bits in an input such as a number to produce a result, it tends to be faster, can usually save space, many times deals with a 32-bit Signed Integer and is used heavily by computers behind the scenes to accomplish all sorts of tasks.</p><p>If you like the content please follow me and like it and if there is enough traction I may create another article about Bit Manipulation that goes into how to do addition/multiplication/division using Bit Manipulation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b27267cf0f1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming Tutorial using JavaScript]]></title>
            <link>https://medium.com/@balleto333/dynamic-programming-tutorial-using-javascript-5c54c30f8938?source=rss-803803d8b6ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c54c30f8938</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[software-engineer]]></category>
            <dc:creator><![CDATA[Daniel Ball]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:19:44 GMT</pubDate>
            <atom:updated>2022-04-17T10:19:44.938Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial is intended to be a brief introduction to learning dynamic programming. It is broken down into sections that cover important topics to properly learn this algorithmic technique. Learning Dynamic Programming can be challenging and in this article, I hope to make it a little easier to understand when studying/practicing Algorithms and Data Structures.</p><p>I personally have been coding for many years and I currently work as a Software Engineer at a medium-sized company. I’ve always been intrigued by Algorithms and Data Structures and believe Computer Science will be even more important in the future.</p><p><strong>Prerequisites</strong></p><p>You should have at least basic knowledge of recursion, programming with any language of your choice, and big o notation.</p><p><strong>What is Dynamic Programming</strong></p><p>Dynamic Programming is a mathematical and computer programming technique to solve a complicated problem by breaking it down into smaller sub-problems. Many times these problems generally tend to ask the min/max value of some computation and/or all combinations of an array/string.</p><p>The naive approach when solving these problems will many times result in exponential time complexity. Dynamic Programming can be applied to solve these problems instead and lower the time complexity to polynomial(such as exponential) time. This is part of the reason why dynamic programming is a powerful technique to solve problems in computer science and why it should be learned when studying Algorithms and Data structures.</p><p><strong>Top-Down and Bottom-Up</strong></p><p>There are two ways to write an algorithm for DP. Top-Down uses a recursive approach and bottom-up uses an iterative approach to create the algorithm. Both approaches usually use a data structure such as a 2D Array to cache the sub-problem to make sure we never compute the same sub-problem again. For top-down, if we look up a cached result it&#39;s called memoization and for bottom-up it&#39;s called tabulation. It’s important to cache the results because if you don’t, most of the time your solution cannot be considered to be Dynamic Programming.</p><p>For this article, we’re going to focus on using top-down to learn DP. Although some problems are easier to write using top-down or bottom-up, in general top-down is easier to learn and we can always convert it to bottom-up by using the same principles we used for the top-down solution.</p><p><strong>Memoization and how to cache sub-problems</strong></p><p>Typically caching the results is done by two D or 3D arrays. You could use a hashmap and may have to sometimes, however, the array lookup is usually a little faster…after all a hashmap uses an array under the hood.</p><p>Get used to making these multi-level arrays:</p><blockquote><em>c</em><strong><em>onst twoDArray = […new Array(input.length+1)].map(a=&gt; […new Array(secondInput.length+1)].fill(-Infinity))</em></strong></blockquote><blockquote><strong><em>const threeDArray = […new Array(input1.length+1)].map(a =&gt; […new Array(input2.length+1)].map(a =&gt; […new Array(input3.length+1)].fill(Infinity)))</em></strong></blockquote><p>This is one way. Notice every element is unique and cannot be changed by other elements via reference. We always add +1 or more to our input length, we do this because the cost is minimal and it addresses many edge cases. We also set a default value which is usually -Infinity if we want the max value or Infinity if we want the min value.</p><p>In our method we would usually write the lookup in this way:</p><blockquote><strong><em>if (memo[i][j] !== -Infinity) return memo[i][j]</em></strong></blockquote><blockquote><strong><em>if (memo[i][j][k] !== Infinity) return memo[i][j][k]</em></strong></blockquote><p><strong>How to Approach a Dyanic Programming Problem</strong></p><p>We start out by writing down our state variables, our base cases, and the recurrence relation before attacking any DP problem. Let’s look at the problem <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/">Best Time To Buy and Sell Stock With Cooldown</a> from Leetcode.</p><p>The problem states we have an array of days and the value is the cost of that price on that day. We can either buy or sell or sell each day, we can do as many transactions as we want(buy &amp; sell multiple times) until we reach the end of the array. When we sell we must skip a day(cooldown) and we want the max value for all valid transactions added up for the entire array.</p><p>There could be many different combinations here(if our input is large) and they want the max value, these are two hints that this is a Dynamic Programming problem.</p><p><strong><em>State Variables:</em></strong></p><p>During our recursive method, we will usually do some type of computation. Typically we just look up one thing during each recursive call. Here we start at the beginning of the input array which is the first day. <em>What are we going to do each day? </em>We are either going to buy or sell and we need to know what day we’re on. So for the state variables let’s have <strong>i</strong> for the index of the day we’re on and <strong>t</strong> for the transaction we’re doing, 1 can represent buying and 0 can be selling. So for this problem, we will have a two D Array.</p><blockquote>const memo = […new Array(prices.length+1)].map(a=&gt; […new Array(2+1)].fill(-Infinity))</blockquote><p>We want the max value so the default value is -Infinity, we need to track all days so the first array is the input length + 1 and we only need to hold 2 values for buying or selling on each day(we add +1 to make it 3 to avoid edge cases). We should think about how we’re going to initiate the recursive method as well. We will initiate it like this: <strong><em>dp(0,1). </em></strong>The dp is the name of our recursive method, we have 0 for the first day of our input and 1 since we need to buy the stock first before we can sell it. We start at the beginning of our input although you could start at the end if written differently. Because of the nature of recursion, this should return the final result as well, so we could just return that as our answer(many times we can’t do this if we have a loop outside of the recursive method or some other type of computation must be made).</p><p><strong><em>Base Cases:</em></strong></p><p>Recursive methods always need some type of base case to avoid an infinite loop. We cannot let our state variable <strong><em>i</em></strong> for the day we’re on go past our input length because it would be out of bounds. We want the max value as the result, so we can return <strong><em>0</em></strong>. Our first base case is:</p><blockquote><strong><em>if (i &gt;= prices.length) return 0</em></strong></blockquote><p>We need valid transactions and we can consider a transaction is valid when we can buy and sell. Because of this, we cannot buy on the last day. Our other base case is:</p><blockquote><strong><em>if (t === 1 &amp;&amp; i &gt;= prices.length-1) return 0</em></strong></blockquote><p><strong><em>Recurrence Relation:</em></strong></p><p>This is typically the hardest part and it takes practice to find the recurrence relation. If found we can use this for a bottom-up solution as well. This is also where Mathematical Induction or at least the thinking or association to it can come into play. We’re essentially writing a formula or better yet a relation. Many times if the relation is written a certain way you don’t need to iterate over the input in a loop, but many times you do need to(inside or outside of the recursive method).</p><p>During each recursive call, we typically do one computation involving our state variables.</p><p>If we’re buying we will do this:</p><blockquote><strong><em>if (t ===1)</em></strong></blockquote><blockquote><strong><em>memo[i][t] = dp(i+1, 0) -prices[i]</em></strong></blockquote><p>Since we’re buying we decrement the value of the price on that day( <strong><em>-prices[i]</em></strong>). Now we need to capture the sale so we go to the next <strong><em>day(i+1)</em></strong> and since we need the sale <strong><em>t = 0</em></strong>.</p><blockquote>else if (t === 0)</blockquote><blockquote><strong><em>memo[i[[t] = dp(i+2, 1) + prices[i]</em></strong></blockquote><p>Since we’re selling we can add the price(<strong><em>+prices[i]</em></strong>). Because we need to get the next valid transaction we need to skip a day(cooldown) so that’s why we add 2 to the state variable <strong><em>i</em></strong>(<strong><em>i+2</em></strong>) since we’re now going to buy <strong><em>t = 1</em></strong>.</p><p>This is the final part of our recurrence relation:</p><blockquote>return memo[i][t] = Math.max(dp(i+1, t), memo[i][t])</blockquote><p>We’ve computed our value already but we need the best(max) value during each step/phase of our recursive method. It may be best to sell or buy on the next day for each transaction. So we include that by doing this <strong><em>dp(i+1, t)(t </em></strong>can either be<strong><em> 0 </em></strong>or<strong><em> 1). </em></strong>By adding this we’re now ensuring we take the max value between our current state of transition and a future state of transition during each recursive call. This is because by passing in the variable<strong> t</strong> as the second parameter we are essentially trying to compare the current state value towards a future state value…we’re comparing whether buying today or tomorrow(or the day after that…) is better. The same could be said for selling. Because of the recursiveness, everything should boil down to one final answer which is the best(max) sum for the maximum profit we can achieve for each valid transaction. We can also say all the other sub-problems are computed by induction(Mathematical Induction).</p><p>Our full recurrence relation:</p><blockquote>if (t ===1) {</blockquote><blockquote>memo[i][t] = dp(i+1, 0) -prices[i]</blockquote><blockquote>} else if (t === 0) {</blockquote><blockquote>memo[i[[t] = dp(i+2, 1) + prices[i]</blockquote><blockquote>}</blockquote><blockquote>return memo[i][t] = Math.max(dp(i+1, t), memo[i][t])</blockquote><p><strong>Prove the Recurrence Relation works</strong></p><p>This part can also be challenging because tracking recursive steps, in general, can be confusing, but we need to know if our recurrence relation works and although doing the proof is tedious, it&#39;s a valuable skill to have when you can track all of the recursive steps throughout the method. We can start with a small input and then work up to a bigger input during the proof. If our input was <strong><em>[4,3,6],</em></strong> our proof can look like this:</p><blockquote>const prices = [4,3,6]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5LgBVq-MWU9eswsGCtxng.jpeg" /></figure><p>The recursive relation works and it states the max value for all transactions(in this case only one can be made) is 3(6–3) and we achieve that by buying on day 2(-3) and selling on day 3(+6). We compare that to buying on day 1 and selling on day 3 which would be 2(6–4). Also notice how we start on day 1 and we need to buy during this first step(<strong><em>dp(0,1)</em></strong>).</p><p><strong>The final Algorithm put altogether</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTagzumpz3QrHwAt0KYBiQ.png" /></figure><p><strong>Conclusion</strong></p><p>Dynamic Programming is a pretty wide topic and area. For some DP problems, we are better off just thinking about an iterative approach instead, especially if we can use <em>Kadane’s Algorithm</em>. Find the recurrence relation and it can help find the answer to the problem.</p><p>If you found some of this content useful please follow me and like the article, it may lead me to add more content in the future.</p><p>I</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c54c30f8938" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>