<?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 krunal patel on Medium]]></title>
        <description><![CDATA[Stories by krunal patel on Medium]]></description>
        <link>https://medium.com/@krunalpatel1992?source=rss-4190d12423f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dR6H1Qb0Jhim_eP7rowEOw.jpeg</url>
            <title>Stories by krunal patel on Medium</title>
            <link>https://medium.com/@krunalpatel1992?source=rss-4190d12423f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 16:52:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krunalpatel1992/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[The Case of the Negative Remainder: Why Your Code Might Be Wrong and How to Fix It]]></title>
            <link>https://medium.com/@krunalpatel1992/the-case-of-the-negative-remainder-why-your-code-might-be-wrong-and-how-to-fix-it-d10e07f074b3?source=rss-4190d12423f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d10e07f074b3</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[krunal patel]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 18:34:59 GMT</pubDate>
            <atom:updated>2025-08-19T18:34:59.939Z</atom:updated>
            <content:encoded><![CDATA[<p>As programmers, we frequently rely on fundamental arithmetic operations, and the modulo operator (%) is no exception. It seems straightforward: given two numbers, a dividend and a divisor, the modulo operator returns the remainder of their division. However, the seemingly simple concept of a &quot;remainder&quot; hides a subtle complexity that can lead to unexpected behavior in our code, especially when dealing with negative numbers. This article delves into the nuances of remainders in mathematics and computer science, using the context of a common LeetCode problem to illustrate these points and provide a robust solution.</p><p><strong>The Expected Behavior: Non-Negative Remainders</strong></p><p>In a traditional mathematical context, particularly concerning the <strong>Euclidean division algorithm</strong>, the remainder of a division is always considered to be non-negative and less than the absolute value of the divisor. For integers a (dividend) and n (non-zero divisor), there exist unique integers q (quotient) and r (remainder) such that:</p><blockquote>a = q * n + r, where 0 ≤ r &lt; |n|, q = quotient, r = remainder</blockquote><p>This definition is intuitive and what many of us learn early in mathematics. For instance, when dividing −1 by 2, we expect a remainder of 1 because</p><blockquote>−1 = (−1) * 2 + 1, and 0 ≤ 1 &lt; |2|.</blockquote><p><strong>The Programming Reality: The Case of Negative Modulo</strong></p><p>However, the behavior of the modulo operator in many programming languages, including Java, deviates from this strict non-negative definition, especially when the dividend is negative. In these languages, the sign of the result of the modulo operation typically follows the sign of the dividend.</p><p>Consider the Java code snippet from LeetCode problem 974, “Subarray Sums Divisible by K”:</p><pre>class Solution {<br>    public int subarraysDivByK(int[] nums, int k) {<br>        HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        int sum = 0;<br>        int result = 0;<br>        map.put(0, 1);<br><br>        for(int i=0;i&lt;nums.length;i++){<br>            sum += nums[i];<br><br>            //Calculating reminder<br>            int rem = sum % k;<br><br>            if(map.containsKey(rem)){<br>                result += map.get(rem);<br>            }<br><br>            map.put(rem, map.getOrDefault(rem, 0) + 1);<br>        }<br><br>        return result;<br>    }<br>}</pre><p>This code aims to find the number of subarrays whose sum is divisible by k. It cleverly uses the property that if two prefix sums have the same remainder when divided by k, then the subarray between them has a sum divisible by k. The hash map map stores the frequencies of these remainders.</p><p>The problem arises when the running sum sum becomes negative. For the test case nums = [-1, 2, 9] and k = 2, let&#39;s trace the execution:</p><ol><li>sum = -1, -1 % 2 in Java is -1. The map will store {-1: 1}.</li><li>sum = -1 + 2 = 1, 1 % 2 is 1. The map will store {-1: 1, 1: 1}.</li><li>sum = 1 + 9 = 10, 10 % 2 is 0. The map will store {-1: 1, 1: 1, 0: 1}.</li></ol><p>Mathematically, a remainder of -1 when dividing by 2 is equivalent to a remainder of 1 (since −1 = −1 * 2 + 1). However, the Java modulo operator treats them as distinct, leading to the code failing to correctly identify subarrays with sums divisible by k.</p><p><strong>The Solution: Ensuring Non-Negative Remainders</strong></p><p>To address this discrepancy, we need to ensure that the remainder we work with is always non-negative. This can be achieved using the following formula:</p><blockquote>(sum % k + k) % k</blockquote><p>Let’s break down why this works:</p><ol><li><strong>sum % k</strong>: This performs the standard modulo operation as defined by Java, which can result in a negative value.</li><li><strong>+ k</strong>: By adding k to the potentially negative result, we shift it into a non-negative range. For example, if sum % k is -1 and k is 2, -1 + 2 becomes 1. If sum % k is already non-negative, adding k will result in a value greater than or equal to k.</li><li><strong>% k (again)</strong>: Taking the modulo k of the result ensures that the final remainder is within the range 0 to k-1. If the intermediate value was greater than or equal to k (due to the + k step on a non-negative initial remainder), this second modulo operation brings it back into the desired range. For example, if sum % k was 1 and k is 2, (1 + 2) % 2 becomes 3 % 2 = 1, which is the correct non-negative remainder.</li></ol><p>Applying this correction to the LeetCode solution gives us:</p><pre>class Solution {<br>    public int subarraysDivByK(int[] nums, int k) {<br>        HashMap&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        int sum = 0;<br>        int result = 0;<br>        map.put(0, 1);<br><br>        for(int i=0;i&lt;nums.length;i++){<br>            sum += nums[i];<br><br>            // Correcting for negative remainders<br>            int rem = (sum % k + k) % k;<br><br>            if(map.containsKey(rem)){<br>                result += map.get(rem);<br>            }<br><br>            map.put(rem, map.getOrDefault(rem, 0) + 1);<br>        }<br><br>        return result;<br>    }<br>}</pre><p>This corrected code will now handle negative numbers in the input array correctly, ensuring that the remainders stored in the hash map are always non-negative and accurately reflect the mathematical concept of congruence modulo k.</p><h3>Conclusion</h3><p>The seemingly simple modulo operation can have subtle differences in its implementation between mathematical theory and programming languages. Understanding these differences, particularly the handling of negative numbers, is crucial for writing correct and robust code. The case of finding subarray sums divisible by k serves as a practical example of how a naive application of the modulo operator can lead to errors. By employing the formula (sum % k + k) % k, we can consistently obtain non-negative remainders, aligning our code with the mathematical principles of modular arithmetic and ensuring the accuracy of our solutions.</p><h3>References</h3><ol><li><strong>Euclidean division.</strong> <em>Wikipedia</em>. <a href="https://en.wikipedia.org/wiki/Euclidean_division">https://en.wikipedia.org/wiki/Euclidean_division</a></li><li><strong>Modulo operation.</strong> <em>Wikipedia</em>. <a href="https://en.wikipedia.org/wiki/Modulo_operation">https://en.wikipedia.org/wiki/Modulo_operation</a></li><li><strong>Knuth, D. E. (1997).</strong> <em>The Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd ed.)</em>. Addison-Wesley Professional.</li><li><strong>LeetCode Problem 974: Subarray Sums Divisible by K.</strong> <a href="https://leetcode.com/problems/subarray-sums-divisible-by-k/">https://leetcode.com/problems/subarray-sums-divisible-by-k/</a></li><li><strong>Oracle Java Language Specification, Java SE 8 Edition, Section 15.17.3, Remainder Operator %</strong>. <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3">https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10e07f074b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gauss’s Genius: The Elegant Proof Behind 1+2+…+n]]></title>
            <link>https://medium.com/@krunalpatel1992/gausss-genius-the-elegant-proof-behind-1-2-n-bf793ff86ec7?source=rss-4190d12423f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf793ff86ec7</guid>
            <dc:creator><![CDATA[krunal patel]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 05:25:58 GMT</pubDate>
            <atom:updated>2025-08-09T05:25:58.456Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Formula Gauss Used to Sum Numbers in a Flash</strong></p><p>The story is a classic: a young Carl Friedrich Gauss, told by his teacher to sum all the numbers from 1 to 100 to keep him busy, reportedly came up with the answer in moments. How? He didn’t add them one by one. Instead, he found a brilliant shortcut. The formula he used is a cornerstone of mathematics and computer science, and it’s surprisingly simple.</p><p>The formula for calculating the sum of the first <strong>n</strong> consecutive positive integers is:</p><blockquote>n (n+1)​ / 2</blockquote><p>This isn’t just a trick; it’s a powerful tool with a beautiful, intuitive proof.</p><p><strong>The Logic Behind the Formula</strong></p><p>The easiest way to understand the formula’s logic is to see it in action. Let’s find the sum of the numbers from 1 to 10.</p><p>First, we write out the sum:</p><blockquote>S = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10</blockquote><p>Now, write the same sum, but in reverse order:</p><blockquote>S = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1</blockquote><p>If we add these two sums together, we can pair the numbers vertically. Notice that each pair adds up to the same number:</p><blockquote>(1 + 10) = 11</blockquote><blockquote>(2 + 9) = 11</blockquote><blockquote>(3 + 8) = 11</blockquote><blockquote>(4 + 7) = 11</blockquote><blockquote>(5 + 6) = 11</blockquote><blockquote>…and so on.</blockquote><p>Since there are <strong>10</strong> numbers in our sequence, we have <strong>10 pairs</strong>, and each pair sums to <strong>11</strong>. So, the total of these two series is 10 (n) × 11 (n+1) = 110.</p><p>But wait — we added the series to itself. To get the correct sum of just one series, we must divide our result by 2.</p><blockquote>110 / 2 = 55</blockquote><p>So, the sum of numbers from 1 to 10 is 55.</p><p><strong>Generalizing the Formula</strong></p><p>We can apply this exact same logic to any sequence of consecutive positive integers from 1 to n.</p><ol><li>The sum of the first and last number is always <strong>(1 + n)</strong>.</li><li>The number of pairs in the sequence is <strong>n</strong>.</li><li>The total sum of two such series is <strong>n (n + 1)</strong>.</li><li>Since we doubled the series, we divide by 2 to get the final formula:</li></ol><blockquote>n (n + 1) / 2 ​</blockquote><p>This clever pairing method is why the formula works so elegantly and is famously attributed to Gauss.</p><p><strong>A Practical Application: Finding a Missing Number in DSA</strong></p><p>Beyond its mathematical beauty, this formula is a powerful tool in computer science. One common application in Data Structures and Algorithms (<strong>DSA</strong>) is to efficiently find a missing number in a sequence.</p><p>Let’s say you have an array containing n−1 distinct numbers from a sequence of 1 to n. Your task is to find the single number that is missing.</p><p>Here’s the approach:</p><ol><li><strong>Calculate the Expected Sum:</strong> First, use the formula to find the sum that the complete sequence (from 1 to n) should have. We’ll call this <strong>expectedSum</strong>.</li><li><strong>Calculate the Actual Sum:</strong> Next, iterate through the given array and sum up all the numbers you have. We’ll call this <strong>actualSum</strong>​.</li><li><strong>Find the Missing Number:</strong> The missing number is simply the difference between the expected sum and the actual sum:</li><li><strong>missingSum​ = expectedSum​ − actualSum​</strong></li></ol><p>This method is highly efficient, with a time complexity of <strong>O(n)</strong> (because you only need to loop through the array once) and a space complexity of <strong>O(1)</strong> (since you don’t need to store any extra data). It’s a perfect example of how a simple mathematical formula can provide an elegant and performant solution to a coding problem.</p><p><strong>Conclusion</strong></p><p>And there you have it — a simple, elegant formula with roots in a childhood story that still solves real-world problems today. It’s more than just a math trick; it’s a powerful reminder that sometimes the most efficient solutions come from looking at a problem in a different way.</p><p>So, the next time you’re faced with a seemingly tedious task, whether it’s adding up a long list of numbers or tackling a tough coding challenge, take a moment. You never know, a bit of that Gauss-like creativity might just be all you need to find an elegant shortcut.</p><p>If you like this article, do like it, comment on it, and share it with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf793ff86ec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Android Apps with pseudo-localization]]></title>
            <link>https://medium.com/@krunalpatel1992/testing-android-apps-with-pseudo-localization-ec627210dced?source=rss-4190d12423f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec627210dced</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[krunal patel]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 11:00:47 GMT</pubDate>
            <atom:updated>2024-03-16T11:00:47.595Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing an Android app, reaching a global audience is often a key goal. But simply translating your app’s text isn’t enough. You need to ensure the translated text fits within the UI layout, doesn’t cause any bugs, and reads naturally to users in that language. This is where localization testing comes in.</p><p>Traditional localization testing involves translating your app and then manually testing it with native speakers. While effective, it can be time-consuming and expensive. Here’s where pseudo-localization enters the scene.</p><p><strong>What is Pseudo-localization?</strong></p><p>Pseudo-localization is a technique that uses artificial (pseudo) translations to simulate the characteristics of real translations from languages that might cause issues during localization. These pseudo-translations are typically done in English but are modified to:</p><ul><li>Be significantly longer than the original English text (to test for UI layout issues caused by text expansion).</li><li>Include special characters and non-standard formatting (to test how your app handles these elements).</li><li>Use nonsensical word order or grammar (to highlight areas where the code relies on specific language assumptions).</li></ul><p><strong>Benefits of Pseudo-localization for Android Apps</strong></p><p>By testing your app with pseudo-localized resources, you can identify potential localization issues early in the development process. Here are some key benefits:</p><ul><li><strong>Uncover UI layout issues :</strong> Pseudo-translated text can become much longer than the original English. This exposes areas where the UI might break due to overflowing text boxes or truncated layouts.</li><li><strong>Identify hardcoded strings :</strong> Any strings embedded directly in your code won’t be picked up for pseudo-localization, making them easy to spot and move to a proper resource file.</li><li><strong>Reveal string concatenation problems :</strong> If you’re building strings dynamically by concatenating multiple pieces of text, pseudo-localization can expose cases where the resulting string is split across lines or UI elements.</li><li><strong>Catch right-to-left language issues :</strong> If your app needs to support right-to-left languages, pseudo-localization can help identify areas where the UI layout might not work correctly.</li></ul><p><strong>How to Use Pseudo-localization for Android Testing</strong></p><p>The official <a href="https://developer.android.com/guide/topics/resources/pseudolocales"><strong>Android Developer documentation</strong></a><strong> </strong>provides a detailed guide on using pseudo-locales for testing. Here’s a quick overview:</p><p>First, you need to enable the generation of pseudo-locales in a build type configuration:</p><pre>android {<br>   ...<br>   buildTypes {<br>       debug {<br>           pseudoLocalesEnabled true<br>       }<br>   }<br>}</pre><p>Then, you can change the device or AVD language to <strong>English (XA)</strong> or <strong>AR (XB) </strong>from settings app at path<strong> Languages and input &gt; Language preferences </strong>or<strong> Languages and input &gt; Language preferences &gt; Add a language (based on android version)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Vmc3qQn_vaGJfVP59rxUDw.png" /><figcaption>Select a pseudo-locale</figcaption></figure><p>In the <strong>Language preferences</strong> list, drag the tab to move a pseudo-locale to the top of the list and make it the active language.</p><p><strong>Conclusion</strong></p><p>Pseudo-localization is a valuable technique for any Android developer who wants to ensure a smooth localization process. By proactively identifying and fixing potential issues early on, you can save time and money during the final localization stage, ultimately delivering a high-quality app experience for your global audience.</p><p>If you like this article, do like it, comment on it, and share it with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec627210dced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data binding in android Part 1]]></title>
            <link>https://medium.com/@krunalpatel1992/data-binding-in-android-part-1-8532ed3164f9?source=rss-4190d12423f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8532ed3164f9</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[architecture-components]]></category>
            <dc:creator><![CDATA[krunal patel]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 06:28:23 GMT</pubDate>
            <atom:updated>2023-09-17T06:28:23.578Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is data binding?</strong></p><p>According to the <a href="https://developer.android.com/topic/libraries/data-binding"><strong>official documentation</strong></a>, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app.</p><p>So basically, we can tie the UI with business logic, which allows the UI values to be updated automatically.</p><p><strong>How to use data binding?</strong></p><ol><li>To enable data binding, need to make the below changes in the module’s build.gradle file.</li></ol><pre>android {<br>    buildFeatures {<br>        dataBinding true<br>    }<br>}</pre><p>2. To tell the Android data binding library that this layout is going to use data binding, we need to wrap the layout in between &lt;layout&gt;&lt;/layout&gt; tag in xml file.</p><pre>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br>    &lt;ConstraintLayout... /&gt; &lt;!-- UI layout&#39;s root element --&gt;<br>&lt;/layout&gt;</pre><p>3. When we rebuild the app, the data binding library will recognize the layout as a layout for data binding and it will generate a corresponding class for it.</p><p>The code generator creates the name using the name of the XML file.</p><p>(If the XML layout file’s name is activity_main, the name of the newly generated class will be ActivityMainBinding)</p><p>4. In the Activity we need to create an instance of a newly generated class.</p><pre>private ActivityMainBinding activityMainBinding;<br><br>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.activity_main);<br> <br>    activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);<br>} </pre><p>5. Now we need to pass objects to the layout. To do that we need to create reference variables in the layout. We can do this inside “data” tags.</p><pre>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br>    &lt;data&gt;<br>        &lt;variable<br>            name=&quot;people&quot;<br>            type=&quot;com.myapp.model.People&quot; /&gt;<br>    &lt;/data&gt;<br>    &lt;ConstraintLayout... /&gt; &lt;!-- UI layout&#39;s root element --&gt;<br>&lt;/layout&gt;</pre><p>6. The data binding library will generate setter methods according to the variable name we have given, in the above case, it will generate a “setPeople()” method.</p><p>We can pass our instances to the setter methods.</p><pre>private ActivityMainBinding activityMainBinding;<br><br>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.activity_main);<br> <br>    activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);<br>    activityMainBinding.setPeople(getPeople());<br>} <br><br>private People getPeople(){<br>    People people = new People();<br>    people.setName(&quot;Alex&quot;);<br>}</pre><p>7. We can use properties of the passed object within the layout file using “@{ }”.</p><pre>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br>    &lt;data&gt;<br>        &lt;variable<br>            name=&quot;people&quot;<br>            type=&quot;com.myapp.model.People&quot; /&gt;<br>    &lt;/data&gt;<br>    <br>    &lt;TextView<br>        android:text=&quot;@{people.name}&quot; /&gt;<br>&lt;/layout&gt;</pre><p>So, that’s it for part one. In part 2 we will see more on how to support event callback and how to handle inner layout using data binding.</p><p>If you like this article, do like it, comment on it, and share it with your friends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8532ed3164f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>