<?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 Utkarsh Raj Mishra on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Raj Mishra on Medium]]></description>
        <link>https://medium.com/@utkarshrajmishra?source=rss-8d76291fcdbd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uh-pJ9mz48S_6KKnZ-ky_A.png</url>
            <title>Stories by Utkarsh Raj Mishra on Medium</title>
            <link>https://medium.com/@utkarshrajmishra?source=rss-8d76291fcdbd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:55:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utkarshrajmishra/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[Email Open Tracking with Pixel Tracking in Next.js]]></title>
            <link>https://utkarshrajmishra.medium.com/email-open-tracking-with-pixel-tracking-in-next-js-4ecf96c41d05?source=rss-8d76291fcdbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ecf96c41d05</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[pixel-tracking]]></category>
            <category><![CDATA[email-tracking-tools]]></category>
            <category><![CDATA[email-marketing]]></category>
            <dc:creator><![CDATA[Utkarsh Raj Mishra]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 17:25:32 GMT</pubDate>
            <atom:updated>2025-04-01T17:27:20.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xcHrvQsvijOPCYp4" /><figcaption>Photo by <a href="https://unsplash.com/@justin_morgan?utm_source=medium&amp;utm_medium=referral">Justin Morgan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever sent an important email — whether it’s a job application, a referral request, or a business pitch — only to wonder if the recipient actually opened it? Most email platforms don’t provide open tracking by default, leaving you in the dark.</p><p>The solution is pixel tracking (known less affectionately as the spy pixel). This technique involves putting a small ( 1x1 ) pixel in the body of the email. The user’s agent will in general load the image when the email message is opened. The server delivering the image is able to record the image access along with the User Agent string and IP of the requesting client.</p><p>This article will guide you through building your own email-open tracking system using <strong>Next.js</strong>, <strong>SQLite</strong>, and <strong>Serverless API Routes</strong>.</p><h3><strong>Prerequisites</strong></h3><ul><li>Node installed in your local machine.</li><li>Basic knowledge of Nextjs and SQL.</li></ul><p><strong>Note:</strong> If you want external recipients to open your pixel, your server must be accessible to the outside world. You can use platforms like Vercel, Render, or a tunnel service like ngrok.</p><h3>Logging Opens</h3><p>When a request is made to /api/tracker/[pixel_id], we log:</p><ul><li>Timestamp (when the image was loaded)</li><li>IP Address</li><li>User Agent</li></ul><h3><strong>Setting Up the Next.js Project</strong></h3><p>Install Dependencies</p><pre>npx create-next-app mail-tracker<br>cd mail-tracker<br>npm install sqlite3 uuid</pre><h3>Configure SQLite Database</h3><p>Create a file lib/db.js:</p><pre>import sqlite3 from &#39;sqlite3&#39;;<br>import { open } from &#39;sqlite&#39;;<br>export async function openDb() {<br>  return open({<br>    filename: &#39;./mail-tracker.db&#39;,<br>    driver: sqlite3.Database<br>  });<br>}</pre><p>Create database schema in scripts/initDb.js:</p><pre>import { openDb } from &#39;../lib/db&#39;;<br>(async () =&gt; {<br>  const db = await openDb();<br>  await db.exec(`<br>    CREATE TABLE IF NOT EXISTS pixels (<br>      id TEXT PRIMARY KEY,<br>      name TEXT,<br>      createdAt DATETIME DEFAULT CURRENT_TIMESTAMP<br>    );<br>    CREATE TABLE IF NOT EXISTS logs (<br>      id INTEGER PRIMARY KEY AUTOINCREMENT,<br>      pixelId TEXT,<br>      timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,<br>      ip TEXT,<br>      userAgent TEXT<br>    );<br>  `);<br>  console.log(&#39;Database initialized&#39;);<br>})();</pre><p>Run the script:</p><pre>node scripts/initDb.js</pre><h3>Creating API Routes</h3><blockquote>/api/create-pixel.js</blockquote><pre>import { openDb } from &#39;../../lib/db&#39;;<br>import { v4 as uuidv4 } from &#39;uuid&#39;;<br>export default async function handler(req, res) {<br>  if (req.method === &#39;POST&#39;) {<br>    const { name } = req.body;<br>    const db = await openDb();<br>    const id = uuidv4();<br>    await db.run(&#39;INSERT INTO pixels (id, name) VALUES (?, ?)&#39;, [id, name]);<br>    res.json({ id, url: `/api/tracker/${id}` });<br>  }<br>}</pre><blockquote>/api/tracker/[id].js</blockquote><pre>import { openDb } from &#39;../../../lib/db&#39;;<br>import path from &#39;path&#39;;<br>import fs from &#39;fs&#39;;<br>export default async function handler(req, res) {<br>  const { id } = req.query;<br>  const db = await openDb();<br>  await db.run(&#39;INSERT INTO logs (pixelId, ip, userAgent) VALUES (?, ?, ?)&#39;, [<br>    id,<br>    req.headers[&#39;x-forwarded-for&#39;] || req.connection.remoteAddress,<br>    req.headers[&#39;user-agent&#39;]<br>  ]);<br>  const imagePath = path.resolve(&#39;./public/images/pixel.png&#39;);<br>  const imageBuffer = fs.readFileSync(imagePath);<br>  res.setHeader(&#39;Content-Type&#39;, &#39;image/png&#39;);<br>  res.send(imageBuffer);<br>}</pre><h3>Viewing Open Logs</h3><p>Create /api/logs/[id].js to fetch logs:</p><pre>import { openDb } from &#39;../../../lib/db&#39;;<br>export default async function handler(req, res) {<br>  const { id } = req.query;<br>  const db = await openDb();<br>  const logs = await db.all(&#39;SELECT * FROM logs WHERE pixelId = ?&#39;, [id]);<br>  res.json(logs);<br>}</pre><p>Deploy the it on Vercel or Render.</p><p><strong>Note</strong>: To embed in Gmail, click image icon at the bottom of email and selected url option. Paste the tracking pixel URL and send the email.</p><h3>Limitations</h3><ul><li>Gmail caches images therefore subsequent opens will not trigger logs.</li><li>If a recipient disables viewing images, the tracking pixel won’t load.</li><li>Pixel tracking may be subject to legal or ethical constraints in your region and among your contacts.</li></ul><h3>Conclusion</h3><p>Building a simple email tracking system with <strong>Next.js</strong> is an excellent way to understand how open-tracking works while keeping control over your own data. Despite Gmail’s limitations, this approach provides valuable insights into email engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ecf96c41d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use a .gitignore File]]></title>
            <link>https://utkarshrajmishra.medium.com/how-to-use-a-gitignore-file-4f1b72c1c2cb?source=rss-8d76291fcdbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f1b72c1c2cb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Utkarsh Raj Mishra]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 03:54:33 GMT</pubDate>
            <atom:updated>2023-08-10T03:54:33.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Use a .gitignore File</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tB41tau3cmm61jNx" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When you make commits in a git repository, you choose which files to stage and commit by using git add FILENAME and then git commit. But what if there are some files that you never want to commit? It&#39;s too easy to accidentally commit them (especially if you use git add . to stage all files in the current directory). That&#39;s where a .gitignore file comes in handy. It lets Git know that it should ignore certain files and not track them.</p><h3>What Kind of Files Should You Ignore?</h3><ul><li>Log files</li><li>Files with API keys/secrets, credentials, or sensitive information</li><li>Useless system files like .DS_Store on macOS</li><li>Generated files like dist folders</li><li>Dependencies which can be downloaded from a package manager</li><li>And there might be other reasons (maybe you make little todo.md files)</li></ul><p>You can get an idea for what sort of files to ignore on <a href="https://www.gitignore.io/">gitignore.io</a>, by selecting your operating system, text editor or IDE, languages, and frameworks.</p><h3>How .gitignore Works</h3><p>Here’s how it works. A .gitignore file is a plain text file where each line contains a pattern for files/directories to ignore. Generally, this is placed in the root folder of the repository, and that&#39;s what I recommend. However, you can put it in any folder in the repository and you can also have multiple .gitignore files. The patterns in the files are relative to the location of that .gitignore file.</p><h3>Literal File Names</h3><p>The easiest pattern is a literal file name, for example:</p><pre>.DS_Store</pre><p>This will ignore any files named .DS_Store, which is a common file on macOS.</p><h3>Directories</h3><p>You can ignore entire directories, just by including their paths and putting a / on the end:</p><pre>node_modules/<br>logs/</pre><p>If you leave the slash off of the end, it will match both files and directories with that name.</p><h3>Wildcard</h3><p>The * matches 0 or more characters (except the /). So, for example, *.log matches any file ending with the .log extension.</p><p>Another example is *~, which matches any file ending with ~, such as index.html~</p><p>You can also use the ?, which matches any one character except for the /.</p><h3>Negation</h3><p>You can use a prefix of ! to negate a file that would be ignored.</p><pre>*.log<br>!example.log</pre><p>In this example, example.log is not ignored, even though all other files ending with .log are ignored.</p><p>But be aware, you can’t negate a file inside of an ignored directory:</p><pre>logs/<br>!logs/example.log</pre><p>Due to performance reasons, git will still ignore logs/example.log here because the entire logs directory is ignored.</p><h3>Double Asterisk</h3><p>** can be used to match any number of directories.</p><ul><li>**/logs matches all files or directories named logs (same as the pattern logs)</li><li>**/logs/*.log matches all files ending with .log in a logs directory</li><li>logs/**/*.log matches all files ending with .log in the logs directory and any of its subdirectories</li></ul><p>** can also be used to match all files inside of a directory, so for example logs/** matches all files inside of logs.</p><h3>Comments</h3><p>Any lines that start with # are comments:</p><pre># macOS Files<br>.DS_Store</pre><h3>Personal .gitignore Rules</h3><p>Since the .gitignore file gets checked into the repository, there are a couple of options if you want to ignore some files without adding it to the .gitignore rules for the repository. For example, you may have some special files you&#39;re working with on a particular project, or you may use a different editor than your teammates and always want to ignore those types of files.</p><h3>Local Repository .gitignore Rules</h3><p>If there are some files you want to ignore for just this repository, you can put them in .git/info/exclude.</p><h3>Global .gitignore Rules</h3><p>If there are some files you want to ignore in all repositories on your computer, you can put them in a global .gitignore file. First, you have to add a setting to Git with this command:</p><pre>git config --global core.excludesFile ~/.gitignore</pre><p>Then you can add any global rules to ~/.gitignore.</p><h3>What If I Already Have It Checked In?</h3><p>Git will not ignore the file if you’ve already committed it. You’ll have to untrack the file first, then it will start ignoring it. You can untrack the file with this command:</p><pre>git rm --cached FILENAME</pre><h3>Debugging</h3><p>If you’re having trouble, you can find out why certain files are being ignored by using the git check-ignore command with the verbose option.</p><pre>git check-ignore -v example.log</pre><p>The output will look something like this:</p><pre>.gitignore:1:*.log       example.log</pre><p>In this example, the .gitignore file at the root of the project is causing example.log to be ignored, and the pattern that&#39;s causing it to be ignored is *.log on the first line.</p><h3>Summary</h3><p>Gitignore files are something you’ll come across in almost every project. It’s important to ignore the correct files, as well as your options for personal gitignore rules. For even more details, check out the <a href="https://git-scm.com/docs/gitignore">Pro Git book’s section on gitignore</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f1b72c1c2cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From 1430 to LeetCode Guardian (2239) — My One Year Journey!]]></title>
            <link>https://utkarshrajmishra.medium.com/from-1430-to-leetcode-guardian-2239-my-one-year-journey-e646dd22d28d?source=rss-8d76291fcdbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e646dd22d28d</guid>
            <category><![CDATA[codingjourney]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[my-coding-journey]]></category>
            <dc:creator><![CDATA[Utkarsh Raj Mishra]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 18:38:01 GMT</pubDate>
            <atom:updated>2025-04-01T17:40:38.802Z</atom:updated>
            <content:encoded><![CDATA[<h3>From 1430 to LeetCode Guardian (2239) — My One Year Journey!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGbojAvSq-KZEKaOeTBRNg.png" /><figcaption>LeetCode Screenshot</figcaption></figure><p>After 59 contests I have finally achieved my goal of becoming a Guardian on Leetcode! I have spent hundreds of hours on this platform practicing problems, and the feeling of achievement couldn’t be greater. Here is an overview of my journey to Guardian.</p><p><strong>Discovering / Beginning Leetcode</strong><br> I discovered Leetcode in December of 2021, while I was watching a programming tutorial on youtube. I tried out some easy problems, but really put the platform on hold until the summer started. During the summer, I decided I wanted to improve my algorithmic programming skills, and decided to try to complete the <a href="https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions">Blind 75 Leetcode problems</a>. I tried to do one a day. During the first month and a half, I would try 1–2 hours before reading an editorial or watching a video on the problem. For the rest of the duration, I tried to complete the problem without any help, only giving up after multiple days. By the end of the summer, I could solve a good amount of medium problems in under an hour.</p><p><strong>My first Contest</strong><br> By the end of the summer, I was confident enough in my programming skills to set 2 goals: To do (almost) every daily problem without any help, and to achieve top 10% in contest rating. I participated in my first contest in August of 2022 and slowly solved 1 problem, achieving an initial rating of 1440.</p><p><strong>1400–1600</strong><br> My rating actually went down the next contest, mostly because I carelessly submitted and racked up penalty time on an easy problem. I knew I could do better, and on my third contest, solved 3 problems for the first time, placing in the 7000 and gaining rating for the first time. I had finished the Blind 75 by now, and my practice consisted of the daily problem and 1–3 easy/medium dynamic programming tagged problems a day. I felt I didn’t really understand DP at all, so I committed to solving every medium DP problem on Leetcode. I got faster at solving problems in general, and was much more careful when submitting in contests so that I would only get 2–3 penalties per contest. Solving 2 problems relatively quickly and occasionally getting the 3rd one was enough to increase my rating to 1600 by mid September.</p><p><strong>1600–1800</strong><br> It was surprisingly easier for me to go from 1600 to 1800 than it was to go from 1400 to 1600. By October I was still doing DP problems every day but was much more confident in them, and began looking at medium graph problems as I still really didn’t understand BFS. I learned basic graph topics like topological ordering and BFS, which might have been the missing piece for me to solve 3 problems consistently as I began to solve 3/4 problems more often than 2/4. I felt like medium graph problems were much easier to conceptually grasp than DP, which made the learning curve much quicker. By now I also achieved my goal of top 10% in contest rating, but I felt I could go farther!</p><p><strong>1800–2000</strong><br> Here it started to get hard again as I almost always had to solve 3 problems to even break even on rating in contests. By now I could solve most mediums in 30 minutes, and had begun to start trying out hard problems with a little success. I still could not solve them consistently or quickly, but I felt like I was at the level where I could at least comprehend the problem statements and techniques. I started practicing less on medium problems, and instead would spend a lot more time on hard problems. After about 2 months of practicing hard problems, I felt like I had a chance to solve some of them during contests. By good luck, I was able to solve 4/4 problems very quickly on a particular contest, gaining nearly 100 rating points to soar past 2000!</p><p><strong>2000–2100</strong><br> This rating range was probably my greatest struggle. It was now March of 2023, and I had to give more priority to studying for my final exams in May than LeetCode. I continued to do the daily problem, as well as an occasional hard problem as well as contests. But my full attention wasn’t on programming, and it showed in my rating. While I usually had the idea for some problems, I had a hard time implementing them quickly as I just wasn’t practicing programming much during this period. I came up with solutions slower and spent a long time debugging problems I used to be able to visualize quickly. My rating fluctuated between 2000 and 2100 during this period until my exams finished, allowing me to devote my full attention to programming again.</p><p><strong>2100–2200 (Guardian!)</strong><br> It took a few weeks to fully get my mind back into programming, but by the end of May I was feeling sharp again and could visualize problems properly again. I have been working on hard problems every day again and feel like I could solve at least 50% of them during contests. I have had my best performance ever in the past 2 weeks, having top 200 finishes 2 weeks in a row. Now I believe the sky is the limit, as there are less and less problems that I cannot solve.</p><p><strong>Final Thoughts</strong><br> This one year journey has been extremely rewarding and I am so much more confident in my programming skills now than I was one year ago. I believe that almost anyone with adequate dedication can reach Guardian. There will be plateaus and even periods of decline, but you will always continue to improve with meaningful practice. Whether you are passionate in competitive programming or simply trying to brush up on your algorithmic skills, I wish you good luck in your problem solving!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e646dd22d28d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sum of Apartment Skyline]]></title>
            <link>https://utkarshrajmishra.medium.com/sum-of-apartment-skyline-516995a5f3b2?source=rss-8d76291fcdbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/516995a5f3b2</guid>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Utkarsh Raj Mishra]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 14:49:32 GMT</pubDate>
            <atom:updated>2023-02-26T14:49:32.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNHSnhn1h7vXDaVpb5x2pA.jpeg" /></figure><p>Given an apartment composed of n x n buildings shaped. Given a 0-based n x n integer matrix where matri[x][y] represents the height of the building in row x and column y. You can increase the height of any building (different per building), but the increased height of a building should not affect the skyline of the apartment. (contour formed when viewing the city from a distance from any direction)</p><p>Return the maximum sum of heights you can increase without disturbing the skyline of the apartment.</p><p><strong>Example</strong>:</p><blockquote>Input:<br>grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]</blockquote><blockquote>Output: 35</blockquote><p>The apartment skyline viewed from the top or bottom is: [9, 10, 9, 8]<br>The apartment skyline viewed from left or right is: [9, 8, 10, 8]</p><p>The matrix after increasing the height of buildings without affecting skylines is:</p><p>[ [9, 9, 9, 8],<br> [8, 8, 8, 8],<br> [9, 10, 9, 8],<br> [8, 8, 8, 8] ]</p><p><strong>Approach</strong>:</p><p>For grid[i][j], it can’t be higher than the maximum of its row or the maximum of its column. So the maximum increasing height for a building at (i, j) is min(row[i], col[j]) — grid[i][j].</p><p><strong>Code Implementation:</strong></p><pre>import java.io.*;<br>class skyline{<br>  <br>   public static int inc_heights(int[][] grid) {<br>        int n = grid.length;<br>        int[] col = new int[n], row = new int[n];<br>    <br>   <br>        for (int i = 0; i &lt; n; i++) {<br>            for (int j = 0; j &lt; n; j++) {<br>                 // maximum for every row and every column<br>                row[i] = Math.max(row[i], grid[i][j]);<br>                col[j] = Math.max(col[j], grid[i][j]);<br>            }<br>        }<br>    <br>        int res = 0;<br>        for (int i = 0; i &lt; n; i++)<br>            for (int j = 0; j &lt; n; j++)<br>              //the maximum increasing height for every building<br>                res += Math.min(row[i], col[j]) - grid[i][j];<br>        return res;<br>    }<br>  <br>    public static void main (String[] args) {<br>        int grids [][] = {{4,0,9,2},{7,6,1,8},{9,10,3,4},{3,2,1,8}};<br>      System.out.println(inc_heights(grids));<br>    }<br>}</pre><p><strong>Time Complexity</strong>: O(N)</p><p><strong>Space Complexity:</strong> O(N²)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=516995a5f3b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java tricks for competitive programming]]></title>
            <link>https://utkarshrajmishra.medium.com/java-tricks-for-competitive-programming-4f47290264af?source=rss-8d76291fcdbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f47290264af</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[codeforces]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[codechef]]></category>
            <dc:creator><![CDATA[Utkarsh Raj Mishra]]></dc:creator>
            <pubDate>Sat, 04 Feb 2023 18:22:28 GMT</pubDate>
            <atom:updated>2023-02-04T18:22:28.160Z</atom:updated>
            <content:encoded><![CDATA[<p>Although the practice is the only way to ensure increased performance in programming contests, having some tricks up your sleeve ensures an upper edge and fast debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WZicyxDYcUbLgIpI" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>1) Checking if the number is even or odd without using the % operator:</strong> <br>Although this trick is not much better than using a % operator but is sometimes efficient (with large numbers).</p><p><strong>Use &amp; operator:</strong></p><pre>System.out.println((a &amp; 1) == 0 ?  &quot;EVEN&quot; : &quot;ODD&quot; );</pre><p><strong>2) Fast Multiplication or Division by 2</strong></p><p>Multiplying by 2 means shifting all the bits to the left and dividing by 2 means shifting to the right.</p><p><strong>Example:</strong> 2 (Binary 10): shifting left 4 (Binary 100) and right 1 (Binary 1)</p><pre>n = n &lt;&lt; 1;   // Multiply n with 2<br>n = n &gt;&gt; 1;   // Divide n by 2</pre><p><strong>3) Swapping of 2 numbers using XOR:</strong></p><p>This method is fast and doesn’t require the use of the 3rd variable.</p><pre>// A quick way to swap a and b<br>  a ^= b;<br>  b ^= a;<br>  a ^= b;</pre><p><strong>4) Faster I/O:</strong></p><p>Refer <a href="https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/">here</a> for Fast I/O in java</p><p><strong>5) For String manipulations:</strong></p><p>Use <a href="https://www.geeksforgeeks.org/stringbuffer-class-in-java/">StringBuffer</a> for string manipulations, as <a href="https://www.geeksforgeeks.org/g-fact-27-string-vs-stringbuilder-vs-stringbuffer/">String</a> in java is immutable. Refer <a href="https://www.geeksforgeeks.org/g-fact-27-string-vs-stringbuilder-vs-stringbuffer/">here</a>.</p><p><strong>6) Calculating the most significant digit:</strong></p><p>To calculate the most significant digit of any number log can be directly used to calculate it.</p><pre>Suppose the number is N then <br>Let double K = Math.log10(N);<br>now K = K - Math.floor(K);<br>int X = (int)Math.pow(10, K);<br>X will be the most significant digit.</pre><p><strong>7) Calculating the number of digits directly:</strong></p><p>To calculate the number of digits in a number, instead of looping we can efficiently use log :</p><pre>No. of digits in N = Math.floor(Math.log10(N)) + 1;</pre><p><strong>8) Inbuilt GCD Method:</strong></p><p>Java has inbuilt GCD method in <a href="https://www.geeksforgeeks.org/biginteger-class-in-java/">BigInteger class</a>. It returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this==0 &amp;&amp; val==0.</p><p><strong>Syntax :</strong></p><pre>public BigInteger gcd(BigInteger val)<br>Parameters :<br>val - value with which the GCD is to be computed.<br>Returns :<br>GCD(abs(this), abs(val))</pre><p><strong>9) checking for a prime number:</strong></p><p>Java has an inbuilt isProbablePrime() method in <a href="https://www.geeksforgeeks.org/biginteger-class-in-java/">BigInteger class</a>. It returns true if this BigInteger is probably prime(with some certainty), false if it’s definitely composite.</p><pre>BigInteger.valueOf(1235).isProbablePrime(1)</pre><p><strong>10) </strong><a href="https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/"><strong>Efficient trick to know if a number is a power of 2</strong></a><strong>:</strong></p><p>The normal technique of division the complexity comes out to be O(logN), but it can be solved using O(v) where v is the number of digits of the number in binary form.</p><pre>// Method to check if x is power of 2*/<br>static boolean isPowerOfTwo (int x)<br>{<br>j<br>return x!=0 &amp;&amp; ((x&amp;(x-1)) == 0);<br>}</pre><p><strong>11) Sorting Algorithm:</strong></p><ol><li><a href="https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/">Arrays.sort()</a> used to sort elements of an array.</li><li><a href="https://www.geeksforgeeks.org/collections-sort-java-examples/">Collections.sort()</a> used to sort elements of a collection.</li></ol><p>For primitives, Arrays.sort() uses <a href="https://www.geeksforgeeks.org/3-way-quicksort-dutch-national-flag/">dual pivot quicksort </a>algorithms.</p><p><strong>12) Searching Algorithm:</strong></p><ol><li>Arrays.binarySearch()(<a href="https://www.geeksforgeeks.org/arrays-binarysearch-java-examples-set-1/">SET 1</a> | <a href="https://www.geeksforgeeks.org/arrays-binarysearch-in-java-with-examples-set-2-search-in-subarray/">SET2</a>) used to apply binary search on a sorted array.</li><li><a href="https://www.geeksforgeeks.org/collections-binarysearch-java-examples/">Collections.binarySearch()</a> used to apply binary search on a collection based on comparators.</li></ol><p><strong>13) Copy Algorithm:</strong></p><ol><li><a href="https://write.geeksforgeeks.org/wp-admin/post.php?post=188444&amp;action=edit">Arrays.copyOf() and copyOfRange()</a> copy the specified array.</li><li><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#copy(java.util.List,%20%20java.util.List)">Collections.copy()</a> copies specified collection.</li></ol><p><strong>14) Rotation and Frequency</strong></p><p>We can use <a href="https://www.geeksforgeeks.org/java-util-collections-rotate-method-java-examples/">Collections.rotate()</a> to rotate a collection or an array by a specified distance. You can also use <a href="https://www.geeksforgeeks.org/java-util-collections-frequency-java-examples/">Collections.frequency()</a> method to get the frequency of a specified element in a collection or an array.</p><p><strong>15) Most data structures are already implemented in the </strong><a href="https://www.geeksforgeeks.org/collections-in-java-2/"><strong>Collections Framework</strong></a>.</p><p>For example <a href="https://www.geeksforgeeks.org/stack-class-in-java/">Stack</a>, <a href="https://www.geeksforgeeks.org/linked-list-in-java/">LinkedList</a>, <a href="https://www.geeksforgeeks.org/hashset-in-java/">HashSet</a>, <a href="https://www.geeksforgeeks.org/java-util-hashmap-in-java/">HashMaps</a>, <a href="https://www.geeksforgeeks.org/priority-queue-class-in-java-2/">Heaps</a> etc.</p><p><strong>16) Use </strong><a href="https://www.geeksforgeeks.org/wrapper-classes-java/"><strong>Wrapper class</strong></a><strong> functions for getting radix conversions of a number</strong> Sometimes you require radix conversion of a number. For this, you can use wrapper classes.</p><p>Here is Java template you can use for CP:</p><pre>import java.io.*;<br>import java.util.StringTokenizer;<br>import java.util.*;<br>import java.lang.*;<br>// Main Class<br> <br>public class Main{<br> <br> <br>//main function<br> public static void main(String[] args) throws IOException<br>    {<br> <br>  <br>       try {<br>            FastReader x=new FastReader();<br>            FastWriter out = new FastWriter();<br>            int MOD = (int) (1e9 + 7);<br>             int testcases=x.nextInt();<br>             while(testcases--&gt;0){<br>                <br>             //your code here<br><br><br>         }<br>            <br>            <br>        out.close();<br>        } catch (Exception e) {<br>            return;<br>        }<br>    }<br> <br> <br> <br>     //gcd function<br>    public static long gcd(long a, long b){<br>        if(b==0) return a;<br>        return gcd(b,a%b);<br>    }<br> <br> <br>    //lcm function<br>    public static long lcm(long a, long b){<br>        return (a*b)/gcd(a,b);<br>    }<br> <br> <br>    //function to check prime<br>    public static boolean isprime(long a){<br>        if(a==2){<br>            return true;<br>        }<br>        for(int i=2;i&lt;Math.sqrt(a);i++)<br>        {<br>            if(a%i==0){<br>                return false;<br>            }<br>        }<br>        return true;<br>    }<br> <br> <br>    //function to reverse an array<br>    public static void reverseArray(int nums[], int low, int high){<br>        while(low&lt;=high){<br>            int temp=nums[low];<br>            nums[low]=nums[high];<br>            nums[high]=temp;<br>        }<br>    }<br> <br> <br>    //power function<br>    public static long power(long a, long b){<br>        if(b==0){<br>            return 1;}<br>        <br>        long res=power(a,b/2);<br>        if(b%2==0){<br>            return res*res;<br>        }<br>        else{<br>            return res*res*a;<br>        }<br>    }<br> <br>    public static long  max(long a, long b){<br>        long k=a&gt;b?a:b;<br>        return k;<br>    }<br>    public static long min(long a, long b){<br>        return a&gt;b?b:a;<br>    }<br> <br>    public static boolean equal(long a,long b){<br>        return a==b?true:false;<br>    }<br> <br>    public static String reverseString(String stu){<br>        StringBuilder s=new StringBuilder();<br>        s.append(stu);<br>        return s.reverse().toString();<br>    }<br> <br>    public static String convert(long number, int base)<br>    {<br>         String con = Long.toString(number, base);<br>         return con;<br>    }<br> <br>//fast input<br>public static class FastReader{<br>        BufferedReader br;<br>          <br>  <br>        StringTokenizer st;<br>        public FastReader(){<br>            br=new BufferedReader(new InputStreamReader(System.in));<br> <br>            if (System.getProperty(<br>                    &quot;ONLINE_JUDGE&quot;)<br>                == null) {<br>                try {<br>                   br = new BufferedReader(<br>                        new InputStreamReader(<br>                            new FileInputStream(<br>                                &quot;input.txt&quot;)));<br>                }<br>                catch (Exception e) {<br>                }<br>            }<br>        <br>        }<br>        String next(){<br>            while(st==null || !st.hasMoreTokens()){<br>                try {<br>                    st=new StringTokenizer(br.readLine());<br>                } catch (IOException e) {<br>                    e.printStackTrace();<br>                }<br>            }<br>            return st.nextToken();<br>        }<br>        int nextInt(){<br>            return Integer.parseInt(next());<br>        }<br>        long nextLong(){<br>            return Long.parseLong(next());<br>        }<br>        double nextDouble(){<br>            return Double.parseDouble(next());<br>        }<br>        String nextLine(){<br>            String str=&quot;&quot;;<br>            try {<br>                str=br.readLine().trim();<br>            } catch (Exception e) {<br>                e.printStackTrace();<br>            }<br>            return str;<br>   <br>        }<br> <br>}<br> <br> <br>//fast output<br>     public static class FastWriter {<br>         BufferedWriter bwr;<br> <br>         <br> <br>        public FastWriter() {<br>            bwr = new BufferedWriter(new OutputStreamWriter(System.out));<br>            <br>            if (System.getProperty(<br>                    &quot;ONLINE_JUDGE&quot;)<br>                == null) {<br>                try {<br>                bwr = new BufferedWriter(<br>                        new OutputStreamWriter(<br>                            new FileOutputStream(<br>                                &quot;output.txt&quot;)));<br>                }<br>                catch (Exception e) {<br>                }<br>            }<br>           <br>            <br>        }<br> <br>        public void print(Object object) throws IOException {<br>            bwr.append(&quot;&quot; + object);<br>        }<br> <br>        public void println(Object object) throws IOException {<br>            print(object);<br>            bwr.append(&quot;\n&quot;);<br>        }<br> <br>        public void close() throws IOException {<br>            bwr.close();<br>        }<br>    }<br> <br> <br> <br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f47290264af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Square root of a number]]></title>
            <link>https://utkarshrajmishra.medium.com/square-root-of-a-number-d3f0d3733d75?source=rss-8d76291fcdbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f0d3733d75</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[amazon-interview-question]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[microsoft-interview]]></category>
            <category><![CDATA[flipkart]]></category>
            <dc:creator><![CDATA[Utkarsh Raj Mishra]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 07:17:10 GMT</pubDate>
            <atom:updated>2023-01-23T07:25:54.190Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a common problem asked in companies like <strong>Amazon</strong>, <strong>Flipkart</strong>, <strong>VMWare</strong>,<strong> Accolite</strong> and <strong>Microsoft</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sMsxFHPMs-TjYDdD" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Problem:</strong></h3><p>Given an integer <strong>x,</strong> find the square root of x. If <strong>x</strong> is not a perfect square, then return floor(√x).</p><h3>Example 1:</h3><pre><strong>Input:</strong><br>x = 5<br><strong>Output:</strong> 2<br><strong>Explanation</strong>: Since, 5 is not a perfect <br>square, floor of square_root of 5 is 2.</pre><h3>Example 2:</h3><pre><strong>Input:</strong><br>x = 4<br><strong>Output:</strong> 2<br>Explanation: Since, 4 is a perfect <br>square, so its square root is 2.</pre><h3><strong>Approach 1:</strong></h3><p><strong>Naive Approach:</strong> Starting from 1 continue to increment the number until the square of that number is greater than the given number.</p><p>Follow the steps below to implement the above idea</p><ol><li>Create a variable (counter)<strong> <em>i</em></strong> and take care of some base cases, (i.e when the given number is 0 or 1).</li><li>Run a loop until<strong> <em>i*i &lt;= n</em></strong>, where n is the given number. Increment i by 1.</li><li>The floor of the square root of the number is <em>i — 1</em></li></ol><pre>class Solution{<br> <br>    // Returns floor of square root of n<br>   public static long floorSqrt(long n)<br>    {<br>        // Base cases<br>        if (n == 0 || n== 1)<br>            return n;<br> <br>        // Starting from 1, try all numbers until<br>        // i*i is greater than or equal to x.<br>        long i = 1, result = 1;<br> <br>        while (result &lt;= x) {<br>            i++;<br>            result = i * i;<br>        }<br>        return i - 1;<br>    }<br><br>}</pre><p><strong>Time Complexity:</strong> O(n)</p><p><strong>Space Complexity: </strong>O(1)</p><p>The solution can be further <strong>optimized using Binary Search</strong></p><h3>Approach 2:</h3><p><strong>Binary Search:</strong> The idea is to find the largest integer <strong>i</strong> whose square is less than or equal to the given number. The values of <strong>i * i</strong> is monotonically increasing, so the problem can be solved using binary search.</p><p>Follow the steps below to implement the above idea</p><ol><li>Take care of the edge case that if n==0 or 1, return n</li><li>Create variables low, high and ans, initialize low with 1 and high with n/2 (Square root of a number will be always ≤ n/2) and ans with 0.</li><li>Run loop until low ≤ high and find mid.</li><li>Check if mid*mid ≤ n, update ans = mid and low with mid+1 else update high with mid-1;</li></ol><pre>class Solution<br>{<br>     long floorSqrt(long n)<br>  {<br>  // Checking the edge case<br>  if(n==1 or n==0) return 1;<br>  long ans=0;<br>  long low=1, high=n/2;<br>  while(low&lt;=high)<br>  {<br>     //finding the mid<br>      long mid=low+(high-low)/2;<br>      if(mid*mid&lt;=n)<br>      {<br>          //updating the answer with mid<br>          ans=mid;<br>          low=mid+1;<br>      }<br>      else high=mid-1;<br>  }<br>  return ans;<br>  }<br>}</pre><p>Time Complexity: O(log n)</p><p>Space Complexity: O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f0d3733d75" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>