<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Vansh Aggarwal</title>
    <description>The latest articles on DEV Community by Vansh Aggarwal (@vansh_aggarwal_5fb2fff667).</description>
    <link>https://dev.to/vansh_aggarwal_5fb2fff667</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3840143%2F0a808966-4b40-40a8-9beb-f30de0fa323d.png</url>
      <title>DEV Community: Vansh Aggarwal</title>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vansh_aggarwal_5fb2fff667"/>
    <language>en</language>
    <item>
      <title>LeetCode Solution: 48. Rotate Image</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Mon, 04 May 2026 06:35:20 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-48-rotate-image-5403</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-48-rotate-image-5403</guid>
      <description>&lt;h1&gt;
  
  
  Spin That Image! Rotating a 2D Matrix Like a Pro (LeetCode #48)
&lt;/h1&gt;

&lt;p&gt;Hey fellow coders and aspiring problem-solvers! 👋 Vansh here, diving into another classic LeetCode challenge that's more about visual thinking than complex algorithms. Today, we're tackling problem &lt;strong&gt;#48: Rotate Image&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This one is fantastic because it pushes us to think &lt;em&gt;in-place&lt;/em&gt;, meaning we can't just create a new matrix and copy rotated values. We have to be clever and modify the original! Ready to give your matrix a spin? Let's go!&lt;/p&gt;




&lt;h3&gt;
  
  
  Understanding the Challenge: Rotate That Image!
&lt;/h3&gt;

&lt;p&gt;You're given a square 2D matrix (think of it like a grid or an image made of pixels). Your task is to rotate this "image" by 90 degrees clockwise.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The catch?&lt;/strong&gt; You &lt;em&gt;must&lt;/em&gt; do it &lt;strong&gt;in-place&lt;/strong&gt;. No creating a brand new matrix to store the result. You have to transform the given matrix directly.&lt;/p&gt;

&lt;p&gt;Let's look at an example to make it super clear:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: A simple 3x3 matrix&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Input:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Imagine physically turning this piece of paper 90 degrees clockwise.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Output:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[[7, 4, 1],
 [8, 5, 2],
 [9, 6, 3]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice how &lt;code&gt;1&lt;/code&gt; (top-left) moves to &lt;code&gt;(0, 2)&lt;/code&gt; (top-right of &lt;em&gt;new&lt;/em&gt; matrix), &lt;code&gt;3&lt;/code&gt; (top-right) moves to &lt;code&gt;(2, 2)&lt;/code&gt; (bottom-right of &lt;em&gt;new&lt;/em&gt; matrix), and so on.&lt;/p&gt;




&lt;h3&gt;
  
  
  The "Aha!" Moment: Two Simple Steps to Rotation
&lt;/h3&gt;

&lt;p&gt;Rotating an image 90 degrees clockwise in-place might seem tricky at first. If you try to move elements one by one, you'll quickly realize you need to store temporary values to avoid overwriting numbers you still need. That can get messy fast!&lt;/p&gt;

&lt;p&gt;But what if we could break down this complex rotation into simpler, more intuitive transformations?&lt;/p&gt;

&lt;p&gt;The "aha!" moment comes when you realize that a 90-degree clockwise rotation can be achieved by &lt;strong&gt;two fundamental operations&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Transpose the matrix:&lt;/strong&gt; This means swapping elements across its main diagonal. &lt;code&gt;matrix[i][j]&lt;/code&gt; becomes &lt;code&gt;matrix[j][i]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Reverse each row:&lt;/strong&gt; After transposing, each row needs to be reversed to get the final clockwise rotation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's visualize this with our 3x3 example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Original Matrix:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 1: Transpose&lt;/strong&gt; (Swap &lt;code&gt;(0,1)&lt;/code&gt; with &lt;code&gt;(1,0)&lt;/code&gt;, &lt;code&gt;(0,2)&lt;/code&gt; with &lt;code&gt;(2,0)&lt;/code&gt;, &lt;code&gt;(1,2)&lt;/code&gt; with &lt;code&gt;(2,1)&lt;/code&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[[1, 4, 7],   &amp;lt;-- 1 (0,0) stays, 2 (0,1) swapped with 4 (1,0), 3 (0,2) swapped with 7 (2,0)
 [2, 5, 8],   &amp;lt;-- 5 (1,1) stays, 6 (1,2) swapped with 8 (2,1)
 [3, 6, 9]]   &amp;lt;-- 9 (2,2) stays
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Reverse Each Row&lt;/strong&gt;&lt;br&gt;
Row 0: &lt;code&gt;[1, 4, 7]&lt;/code&gt; becomes &lt;code&gt;[7, 4, 1]&lt;/code&gt;&lt;br&gt;
Row 1: &lt;code&gt;[2, 5, 8]&lt;/code&gt; becomes &lt;code&gt;[8, 5, 2]&lt;/code&gt;&lt;br&gt;
Row 2: &lt;code&gt;[3, 6, 9]&lt;/code&gt; becomes &lt;code&gt;[9, 6, 3]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Final Rotated Matrix:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[[7, 4, 1],
 [8, 5, 2],
 [9, 6, 3]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Voila! This matches our desired output. This two-step process does the job perfectly, and it's all done in-place!&lt;/p&gt;




&lt;h3&gt;
  
  
  The Step-by-Step Approach
&lt;/h3&gt;

&lt;p&gt;Let's break down how to implement these two steps efficiently in code.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 1: Transposing the Matrix
&lt;/h4&gt;

&lt;p&gt;To transpose a matrix in-place, we iterate through the upper triangle of the matrix and swap &lt;code&gt;matrix[i][j]&lt;/code&gt; with &lt;code&gt;matrix[j][i]&lt;/code&gt;. We only need to consider &lt;code&gt;j&lt;/code&gt; starting from &lt;code&gt;i + 1&lt;/code&gt; to avoid:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Swapping elements twice (e.g., swapping &lt;code&gt;(0,1)&lt;/code&gt; with &lt;code&gt;(1,0)&lt;/code&gt; and then &lt;code&gt;(1,0)&lt;/code&gt; with &lt;code&gt;(0,1)&lt;/code&gt; again would revert the change).&lt;/li&gt;
&lt;li&gt; Swapping elements on the main diagonal with themselves (e.g., &lt;code&gt;(0,0)&lt;/code&gt; with &lt;code&gt;(0,0)&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Algorithm for Transposition:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Get the size of the matrix, &lt;code&gt;n&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; Loop with &lt;code&gt;i&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt; (for rows).&lt;/li&gt;
&lt;li&gt; Inside this, loop with &lt;code&gt;j&lt;/code&gt; from &lt;code&gt;i+1&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt; (for columns, starting from &lt;code&gt;i+1&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt; Swap &lt;code&gt;matrix[i][j]&lt;/code&gt; with &lt;code&gt;matrix[j][i]&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Step 2: Reversing Each Row
&lt;/h4&gt;

&lt;p&gt;After transposition, each individual row needs to be reversed. This is a straightforward operation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm for Reversing Rows:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Loop with &lt;code&gt;i&lt;/code&gt; from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt; (for each row).&lt;/li&gt;
&lt;li&gt; For each &lt;code&gt;matrix[i]&lt;/code&gt;, use a &lt;code&gt;reverse&lt;/code&gt; function (most languages have one built-in for containers like vectors or arrays) to reverse its elements. If not, you can implement a simple two-pointer swap from start and end of the row.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And that's it! These two operations combined give you the 90-degree clockwise rotation, all without using extra space.&lt;/p&gt;




&lt;h3&gt;
  
  
  The Code (C++)
&lt;/h3&gt;

&lt;p&gt;Here's the C++ implementation of this elegant solution:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for std::swap and std::reverse&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="n"&gt;rotate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Get the dimension of the square matrix&lt;/span&gt;

        &lt;span class="c1"&gt;// Step 1: Transpose the matrix&lt;/span&gt;
        &lt;span class="c1"&gt;// Iterate through the upper triangle (j starts from i+1)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Swap matrix[i][j] with matrix[j][i]&lt;/span&gt;
                &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Step 2: Reverse each row&lt;/span&gt;
        &lt;span class="c1"&gt;// Iterate through each row and reverse its elements&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Complexity Analysis
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Transposition:&lt;/strong&gt; We have a nested loop. The outer loop runs &lt;code&gt;n&lt;/code&gt; times, and the inner loop runs approximately &lt;code&gt;n/2&lt;/code&gt; times on average (&lt;code&gt;j&lt;/code&gt; goes from &lt;code&gt;i+1&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;). In total, we perform &lt;code&gt;(n-1) + (n-2) + ... + 1 = n*(n-1)/2&lt;/code&gt; swaps. This is proportional to &lt;code&gt;n^2&lt;/code&gt;. So, it's &lt;code&gt;O(n^2)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Reversing Rows:&lt;/strong&gt; We iterate through &lt;code&gt;n&lt;/code&gt; rows. For each row, we iterate through its &lt;code&gt;n&lt;/code&gt; elements to reverse them. This also takes &lt;code&gt;O(n * n) = O(n^2)&lt;/code&gt; time.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Overall:&lt;/strong&gt; The dominant factor is &lt;code&gt;n^2&lt;/code&gt;. Therefore, the total time complexity is &lt;strong&gt;&lt;code&gt;O(n^2)&lt;/code&gt;&lt;/strong&gt;, where &lt;code&gt;n&lt;/code&gt; is the dimension of the square matrix.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We are performing all operations directly on the input matrix without allocating any additional matrices or significant data structures. The &lt;code&gt;std::swap&lt;/code&gt; and &lt;code&gt;std::reverse&lt;/code&gt; operations work in-place.&lt;/li&gt;
&lt;li&gt;  Therefore, the space complexity is &lt;strong&gt;&lt;code&gt;O(1)&lt;/code&gt;&lt;/strong&gt; (constant space).&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;




&lt;h3&gt;
  
  
  Key Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;In-Place Challenges:&lt;/strong&gt; Problems requiring "in-place" modification often hint at clever manipulations like swapping or using existing memory efficiently.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Decomposition:&lt;/strong&gt; Complex transformations (like 90-degree rotation) can often be broken down into simpler, sequential operations (like transpose + reverse).&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Visual Thinking:&lt;/strong&gt; Drawing out the matrix and how elements move is incredibly helpful for problems involving 2D arrays.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Standard Library Functions:&lt;/strong&gt; Don't forget powerful standard library functions like &lt;code&gt;std::swap&lt;/code&gt; and &lt;code&gt;std::reverse&lt;/code&gt; in C++ (or equivalent in other languages) – they can simplify your code and often are highly optimized.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope this breakdown made the "Rotate Image" problem feel less daunting and more like a fun puzzle! Happy coding, and keep spinning those matrices!&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Author Account: Vansh2710&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Time Published: 2026-05-04 12:03:48&lt;/em&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 69. Sqrt(x)</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Sat, 02 May 2026 13:01:36 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-69-sqrtx-322</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-69-sqrtx-322</guid>
      <description>&lt;h1&gt;
  
  
  ✨ Unlocking &lt;code&gt;Sqrt(x)&lt;/code&gt;: Your First Dive into Binary Search! 🚀
&lt;/h1&gt;

&lt;p&gt;Hey amazing developers! 👋 Vansh2710 here, ready to embark on another exciting LeetCode adventure with you. Today, we're tackling problem #69: &lt;code&gt;Sqrt(x)&lt;/code&gt;. Sounds simple, right? Just find the square root! But here's the twist: we can't use any fancy built-in functions. We're going old-school and building our own square root finder from scratch. Get ready to discover the magic of &lt;strong&gt;Binary Search&lt;/strong&gt;!&lt;/p&gt;




&lt;h2&gt;
  
  
  🧐 Problem Explanation: What are we actually doing?
&lt;/h2&gt;

&lt;p&gt;The problem asks us to find the square root of a given non-negative integer &lt;code&gt;x&lt;/code&gt;. The catch? We need to &lt;em&gt;round down&lt;/em&gt; the result to the nearest whole number. So, if &lt;code&gt;sqrt(x)&lt;/code&gt; is &lt;code&gt;2.828...&lt;/code&gt;, we return &lt;code&gt;2&lt;/code&gt;. And a critical constraint: &lt;strong&gt;NO built-in functions like &lt;code&gt;pow(x, 0.5)&lt;/code&gt; or &lt;code&gt;x ** 0.5&lt;/code&gt; allowed!&lt;/strong&gt; This means we have to come up with our own algorithm.&lt;/p&gt;

&lt;p&gt;Let's look at the examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Example 1: &lt;code&gt;x = 4&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The square root of 4 is exactly 2.&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;2&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Example 2: &lt;code&gt;x = 8&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The actual square root of 8 is approximately 2.82842...&lt;/li&gt;
&lt;li&gt;  When we round this down to the nearest integer, we get 2.&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;2&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;The constraints tell us &lt;code&gt;x&lt;/code&gt; can be pretty large (&lt;code&gt;0 &amp;lt;= x &amp;lt;= 2^31 - 1&lt;/code&gt;), so our solution needs to be efficient!&lt;/p&gt;




&lt;h2&gt;
  
  
  🤔 Intuition: How would &lt;em&gt;you&lt;/em&gt; guess the square root?
&lt;/h2&gt;

&lt;p&gt;Imagine you're a human calculator, and I ask you to find the square root of, say, 49. How would you do it without a calculator?&lt;/p&gt;

&lt;p&gt;You'd probably start guessing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  "Is it 1? &lt;code&gt;1 * 1 = 1&lt;/code&gt; (Too small!)"&lt;/li&gt;
&lt;li&gt;  "Is it 10? &lt;code&gt;10 * 10 = 100&lt;/code&gt; (Too big!)"&lt;/li&gt;
&lt;li&gt;  "Okay, somewhere between 1 and 10. Let's try 5. &lt;code&gt;5 * 5 = 25&lt;/code&gt; (Still too small!)"&lt;/li&gt;
&lt;li&gt;  "Let's try 8. &lt;code&gt;8 * 8 = 64&lt;/code&gt; (Too big!)"&lt;/li&gt;
&lt;li&gt;  "Okay, between 5 and 8. How about 7? &lt;code&gt;7 * 7 = 49&lt;/code&gt; (Bingo! Just right!)"&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Notice a pattern here? You're constantly narrowing down your search space based on whether your guess squared is too small or too big. This exact thought process is the cornerstone of an incredibly powerful algorithm: &lt;strong&gt;Binary Search!&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  🚀 Approach: Binary Search to the Rescue!
&lt;/h2&gt;

&lt;p&gt;Binary Search is perfect for problems where you need to find a specific value within a &lt;em&gt;sorted range&lt;/em&gt; or determine a "point" where a condition changes (like &lt;code&gt;y*y&lt;/code&gt; goes from less than &lt;code&gt;x&lt;/code&gt; to greater than &lt;code&gt;x&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here's how we'll apply it:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Define our Search Space:&lt;/strong&gt; What's the smallest possible square root for &lt;code&gt;x&lt;/code&gt;? &lt;code&gt;0&lt;/code&gt; (for &lt;code&gt;x=0&lt;/code&gt;). What's the largest? It can't be more than &lt;code&gt;x&lt;/code&gt; itself (e.g., &lt;code&gt;sqrt(1)&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt;). So, our search range will be from &lt;code&gt;0&lt;/code&gt; (or &lt;code&gt;1&lt;/code&gt; if we handle &lt;code&gt;x=0&lt;/code&gt; separately) to &lt;code&gt;x&lt;/code&gt;. Let's call these &lt;code&gt;s&lt;/code&gt; (start) and &lt;code&gt;e&lt;/code&gt; (end).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Iterate and Conquer:&lt;/strong&gt; We'll keep guessing the &lt;code&gt;mid&lt;/code&gt;point of our &lt;code&gt;s&lt;/code&gt; and &lt;code&gt;e&lt;/code&gt; range.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*   Initialize `s = 0` (or `1`), `e = x`.
*   Also, initialize an `ans` variable to store our best possible rounded-down answer, starting at `0` (or `1`).
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;The Loop:&lt;/strong&gt; While &lt;code&gt;s&lt;/code&gt; is less than or equal to &lt;code&gt;e&lt;/code&gt; (meaning our search space is still valid):&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;*   **Calculate `mid`:** `mid = s + (e - s) / 2;` (This way of calculating `mid` prevents potential integer overflow compared to `(s+e)/2` if `s` and `e` are very large).

*   **Calculate `square`:** `long long square = mid * mid;`
    *   **CRITICAL STEP:** We use `long long` here! Why? Because `x` can be up to `2^31 - 1`. If `mid` is, say, `60000`, `mid * mid` is `3,600,000,000`, which is larger than the maximum value for a standard `int` (`~2*10^9`). Using `long long` prevents overflow and ensures our calculations are accurate.

*   **Compare `square` with `x`:**
    *   **Case 1: `square == x`**
        *   We found the exact square root! Return `mid` immediately.
    *   **Case 2: `square &amp;lt; x`**
        *   `mid` is too small, or it *could* be our rounded-down answer, but we might find a larger, more accurate one.
        *   So, we store `mid` in `ans` (because `mid` is the largest integer whose square is `_less than or equal to_ x` *so far*).
        *   Then, we search in the **right half** to find a potentially larger `mid`: `s = mid + 1;`
    *   **Case 3: `square &amp;gt; x`**
        *   `mid` is too big. Its square exceeds `x`.
        *   We need to search in the **left half**: `e = mid - 1;`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Return &lt;code&gt;ans&lt;/code&gt;:&lt;/strong&gt; After the loop finishes (when &lt;code&gt;s&lt;/code&gt; becomes greater than &lt;code&gt;e&lt;/code&gt;), our &lt;code&gt;ans&lt;/code&gt; variable will hold the largest integer &lt;code&gt;y&lt;/code&gt; such that &lt;code&gt;y * y &amp;lt;= x&lt;/code&gt;. This is precisely the square root of &lt;code&gt;x&lt;/code&gt; rounded down!&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  💻 Code (C++)
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;mySqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Handle edge case for x = 0&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Initialize our binary search range&lt;/span&gt;
        &lt;span class="c1"&gt;// The square root of x will be between 1 and x&lt;/span&gt;
        &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;         &lt;span class="c1"&gt;// 's' for start&lt;/span&gt;
        &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;         &lt;span class="c1"&gt;// 'e' for end&lt;/span&gt;
        &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;       &lt;span class="c1"&gt;// To store the potential answer (rounded down)&lt;/span&gt;

        &lt;span class="c1"&gt;// Perform binary search&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Calculate mid-point. Using this formula to prevent potential overflow&lt;/span&gt;
            &lt;span class="c1"&gt;// if s and e were both very large and their sum exceeded MAX_INT&lt;/span&gt;
            &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Calculate the square of mid. Use long long to prevent overflow&lt;/span&gt;
            &lt;span class="c1"&gt;// since mid * mid could exceed the maximum value of an int.&lt;/span&gt;
            &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Found the exact square root, return it&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nf"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// mid is too small, or it could be our rounded-down answer.&lt;/span&gt;
                &lt;span class="c1"&gt;// We keep mid as a potential answer and try to find a larger one&lt;/span&gt;
                &lt;span class="c1"&gt;// by searching in the right half.&lt;/span&gt;
                &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// square &amp;gt; x&lt;/span&gt;
                &lt;span class="c1"&gt;// mid is too large, search in the left half&lt;/span&gt;
                &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// After the loop, 'ans' holds the largest integer whose square is less than or equal to x.&lt;/span&gt;
        &lt;span class="c1"&gt;// This is our square root rounded down.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  ⏱️ Time &amp;amp; Space Complexity Analysis
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity: O(log x)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Binary search works by repeatedly halving the search space. If our initial search space has &lt;code&gt;N&lt;/code&gt; elements (in our case, &lt;code&gt;x&lt;/code&gt; possibilities), it takes &lt;code&gt;log N&lt;/code&gt; steps to find the target. Here, &lt;code&gt;N&lt;/code&gt; is roughly &lt;code&gt;x&lt;/code&gt;, so it's &lt;code&gt;O(log x)&lt;/code&gt;. This is super efficient for large &lt;code&gt;x&lt;/code&gt;!&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We are only using a few variables (&lt;code&gt;s&lt;/code&gt;, &lt;code&gt;e&lt;/code&gt;, &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;square&lt;/code&gt;, &lt;code&gt;ans&lt;/code&gt;) regardless of the input &lt;code&gt;x&lt;/code&gt;. We don't use any extra data structures that grow with the input size.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;




&lt;h2&gt;
  
  
  🎯 Key Takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Binary Search is Versatile:&lt;/strong&gt; It's not just for finding exact values! It's incredibly powerful for finding "thresholds" or "transition points" in a sorted or monotonically changing range (like &lt;code&gt;y*y&lt;/code&gt; increasing as &lt;code&gt;y&lt;/code&gt; increases).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Beware of Integer Overflow:&lt;/strong&gt; Always be mindful of the maximum possible values your variables can hold, especially when multiplying large numbers. &lt;code&gt;long long&lt;/code&gt; is your friend!&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Rounded Down Logic:&lt;/strong&gt; When a problem asks for a rounded-down (floor) value, you often need to keep track of the "best valid answer so far" when your &lt;code&gt;mid&lt;/code&gt; is still too small, but potentially correct.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This problem is a fantastic introduction to the elegance and efficiency of binary search. Keep practicing, and you'll master it in no time! Happy coding!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Author Account:&lt;/strong&gt; Vansh2710&lt;br&gt;
&lt;strong&gt;Time Published:&lt;/strong&gt; 2026-05-02 18:31:13&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 69. Sqrt(x)</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Sat, 02 May 2026 12:56:20 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-69-sqrtx-3712</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-69-sqrtx-3712</guid>
      <description>&lt;h1&gt;
  
  
  Unlocking the Power of Binary Search: Solving Sqrt(x) ⚡
&lt;/h1&gt;

&lt;p&gt;Hey awesome coders! 👋 Vansh here, ready to demystify another LeetCode classic. Today, we're tackling problem 69: Sqrt(x). Sounds simple, right? Just find the square root! But here's the twist: we can't use any fancy built-in functions like &lt;code&gt;pow(x, 0.5)&lt;/code&gt; or &lt;code&gt;x ** 0.5&lt;/code&gt;. This challenge pushes us to think deeper and build our own solution from scratch.&lt;/p&gt;

&lt;p&gt;Don't worry, even if you're just starting your coding journey, we'll break down this problem step by step, making it super accessible and fun! By the end, you'll have a powerful new tool in your algorithmic belt: &lt;strong&gt;Binary Search&lt;/strong&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  🧐 Problem Explanation: What are we actually doing?
&lt;/h2&gt;

&lt;p&gt;Imagine you're given a number, let's say &lt;code&gt;x&lt;/code&gt;. Your mission is to find its square root. But there's a catch: you need to round the result &lt;em&gt;down&lt;/em&gt; to the nearest whole number.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;x = 4&lt;/code&gt;, the square root is exactly &lt;code&gt;2&lt;/code&gt;. So, we return &lt;code&gt;2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;x = 8&lt;/code&gt;, the square root is approximately &lt;code&gt;2.82842...&lt;/code&gt;. Since we need to round &lt;em&gt;down&lt;/em&gt;, we return &lt;code&gt;2&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The problem also tells us &lt;code&gt;x&lt;/code&gt; will always be a non-negative integer. And remember, &lt;strong&gt;no built-in square root functions allowed!&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  🤔 Intuition: The "Aha!" Moment
&lt;/h2&gt;

&lt;p&gt;How would you find the square root of a number &lt;code&gt;x&lt;/code&gt; if you could only use multiplication and comparison?&lt;/p&gt;

&lt;p&gt;Let's take &lt;code&gt;x = 25&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Is &lt;code&gt;1 * 1&lt;/code&gt; equal to &lt;code&gt;25&lt;/code&gt;? No, too small.&lt;/li&gt;
&lt;li&gt;  Is &lt;code&gt;2 * 2&lt;/code&gt; equal to &lt;code&gt;25&lt;/code&gt;? No.&lt;/li&gt;
&lt;li&gt;  ...&lt;/li&gt;
&lt;li&gt;  Is &lt;code&gt;5 * 5&lt;/code&gt; equal to &lt;code&gt;25&lt;/code&gt;? Yes! So &lt;code&gt;5&lt;/code&gt; is the answer.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What about &lt;code&gt;x = 8&lt;/code&gt;?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;1 * 1 = 1&lt;/code&gt; (too small)&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;2 * 2 = 4&lt;/code&gt; (too small)&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;3 * 3 = 9&lt;/code&gt; (too large!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since &lt;code&gt;3 * 3&lt;/code&gt; is too large, and &lt;code&gt;2 * 2&lt;/code&gt; is the largest square less than or equal to &lt;code&gt;8&lt;/code&gt;, our answer (rounded down) must be &lt;code&gt;2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Notice a pattern? As we try larger numbers, their squares also get larger. This monotonic property (always increasing) is a huge hint! It screams &lt;strong&gt;Binary Search&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;Binary search is super efficient for finding a target value within a sorted range. Here, we're looking for a number &lt;code&gt;ans&lt;/code&gt; such that &lt;code&gt;ans * ans &amp;lt;= x&lt;/code&gt; and &lt;code&gt;(ans + 1) * (ans + 1) &amp;gt; x&lt;/code&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  🚶‍♀️ Approach: Step-by-Step with Binary Search
&lt;/h2&gt;

&lt;p&gt;Let's outline our binary search strategy:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Define Search Space:&lt;/strong&gt; What's the possible range for our square root?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The smallest possible square root is &lt;code&gt;0&lt;/code&gt; (for &lt;code&gt;x=0&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  The largest possible square root for &lt;code&gt;x&lt;/code&gt; will be &lt;code&gt;x&lt;/code&gt; itself (since &lt;code&gt;1*1=1&lt;/code&gt;, &lt;code&gt;x*x&lt;/code&gt; will be much larger than &lt;code&gt;x&lt;/code&gt; unless &lt;code&gt;x=1&lt;/code&gt; or &lt;code&gt;x=0&lt;/code&gt;). So, our search space &lt;code&gt;[start, end]&lt;/code&gt; can be &lt;code&gt;[0, x]&lt;/code&gt;. For &lt;code&gt;x=0&lt;/code&gt;, the answer is &lt;code&gt;0&lt;/code&gt;. For &lt;code&gt;x=1&lt;/code&gt;, the answer is &lt;code&gt;1&lt;/code&gt;. We can safely start our search from &lt;code&gt;1&lt;/code&gt; if &lt;code&gt;x &amp;gt; 0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Initialize Variables:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;s&lt;/code&gt; (start): &lt;code&gt;1&lt;/code&gt; (or &lt;code&gt;0&lt;/code&gt; for &lt;code&gt;x=0&lt;/code&gt; edge case)&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;e&lt;/code&gt; (end): &lt;code&gt;x&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;ans&lt;/code&gt;: A variable to store our potential answer, initialized to &lt;code&gt;0&lt;/code&gt;. This will eventually hold the largest &lt;code&gt;mid&lt;/code&gt; whose square is less than or equal to &lt;code&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Loop:&lt;/strong&gt; We'll use a &lt;code&gt;while&lt;/code&gt; loop that continues as long as &lt;code&gt;s &amp;lt;= e&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Calculate &lt;code&gt;mid&lt;/code&gt;:&lt;/strong&gt; In each iteration, find the middle of our current search space:&lt;br&gt;
&lt;code&gt;mid = s + (e - s) / 2;&lt;/code&gt;&lt;br&gt;
This way of calculating &lt;code&gt;mid&lt;/code&gt; (&lt;code&gt;s + (e - s) / 2&lt;/code&gt;) is safer than &lt;code&gt;(s + e) / 2&lt;/code&gt; because it prevents potential integer overflow if &lt;code&gt;s&lt;/code&gt; and &lt;code&gt;e&lt;/code&gt; are very large.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Calculate &lt;code&gt;square&lt;/code&gt;:&lt;/strong&gt; Compute the square of &lt;code&gt;mid&lt;/code&gt;:&lt;br&gt;
&lt;code&gt;long long int square = mid * mid;&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Crucial Point:&lt;/strong&gt; &lt;code&gt;mid * mid&lt;/code&gt; can become very large and exceed the maximum value of an &lt;code&gt;int&lt;/code&gt; if &lt;code&gt;x&lt;/code&gt; is large (e.g., &lt;code&gt;x = 2^31 - 1&lt;/code&gt;). To prevent overflow, we &lt;em&gt;must&lt;/em&gt; use &lt;code&gt;long long int&lt;/code&gt; for &lt;code&gt;square&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Compare and Adjust:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;square == x&lt;/code&gt;:&lt;/strong&gt; We found the exact square root! Return &lt;code&gt;mid&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;square &amp;lt; x&lt;/code&gt;:&lt;/strong&gt; This &lt;code&gt;mid&lt;/code&gt; is a potential candidate for our answer (since we need to round down, and its square is not too big). Store &lt;code&gt;mid&lt;/code&gt; in &lt;code&gt;ans&lt;/code&gt;. Now, we need to check if we can find an even larger number whose square is &lt;em&gt;still&lt;/em&gt; less than or equal to &lt;code&gt;x&lt;/code&gt;. So, we shift our search to the right half: &lt;code&gt;s = mid + 1;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;square &amp;gt; x&lt;/code&gt;:&lt;/strong&gt; This &lt;code&gt;mid&lt;/code&gt; is too large, its square exceeds &lt;code&gt;x&lt;/code&gt;. We need to look for smaller numbers. So, we shift our search to the left half: &lt;code&gt;e = mid - 1;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Return &lt;code&gt;ans&lt;/code&gt;:&lt;/strong&gt; Once the loop finishes (&lt;code&gt;s &amp;gt; e&lt;/code&gt;), &lt;code&gt;ans&lt;/code&gt; will hold the largest integer whose square was less than or equal to &lt;code&gt;x&lt;/code&gt;. This is exactly our desired rounded-down square root!&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  💻 Code
&lt;/h2&gt;

&lt;p&gt;Let's put it all together in C++:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;mySqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Handle edge case for x = 0 separately&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Initialize our search range&lt;/span&gt;
        &lt;span class="c1"&gt;// The square root of x will be between 1 and x (inclusive for x=1)&lt;/span&gt;
        &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="c1"&gt;// 'ans' will store the potential answer (the largest integer whose square is &amp;lt;= x)&lt;/span&gt;
        &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="c1"&gt;// Perform binary search&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Calculate mid to prevent potential integer overflow for large s and e&lt;/span&gt;
            &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Calculate the square of mid.&lt;/span&gt;
            &lt;span class="c1"&gt;// Use long long to prevent overflow if mid * mid exceeds int max value.&lt;/span&gt;
            &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Found the exact square root, return it immediately&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nf"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// If mid*mid is less than x, mid could be our answer.&lt;/span&gt;
                &lt;span class="c1"&gt;// Store it and try to find a larger potential answer in the right half.&lt;/span&gt;
                &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// square &amp;gt; x&lt;/span&gt;
                &lt;span class="c1"&gt;// If mid*mid is greater than x, mid is too large.&lt;/span&gt;
                &lt;span class="c1"&gt;// Search in the left half.&lt;/span&gt;
                &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// After the loop, 'ans' holds the largest integer whose square is less than or equal to x.&lt;/span&gt;
        &lt;span class="c1"&gt;// This is the square root rounded down.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  ⏱️ Time &amp;amp; Space Complexity Analysis
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Time Complexity: O(log x)&lt;/strong&gt;&lt;br&gt;
Binary search works by repeatedly dividing the search space in half. For a search space of size &lt;code&gt;x&lt;/code&gt;, it takes &lt;code&gt;log x&lt;/code&gt; operations to find the target. This is incredibly efficient!&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;&lt;br&gt;
We are only using a few constant variables (&lt;code&gt;s&lt;/code&gt;, &lt;code&gt;e&lt;/code&gt;, &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;ans&lt;/code&gt;, &lt;code&gt;square&lt;/code&gt;) regardless of the input &lt;code&gt;x&lt;/code&gt;. Therefore, the space complexity is constant.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  ✨ Key Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Binary Search Power:&lt;/strong&gt; Whenever you see a problem asking to find a value within a sorted (or monotonically increasing/decreasing) range, think Binary Search!&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Preventing Overflow:&lt;/strong&gt; Be mindful of potential integer overflows, especially when multiplying large numbers. Using &lt;code&gt;long long int&lt;/code&gt; is a common fix.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Rounding Down:&lt;/strong&gt; For "round down" problems, binary search often involves storing a &lt;code&gt;potential_answer&lt;/code&gt; and then trying to find a &lt;em&gt;better&lt;/em&gt; one in the appropriate half.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This problem is a fantastic entry point into binary search and a great way to build your foundational algorithmic skills. Keep practicing, and you'll be a LeetCode master in no time! Happy coding! 🚀&lt;/p&gt;




&lt;p&gt;&lt;sup&gt;Authored by Vansh2710 | Published on 2026-05-02 18:25:11&lt;/sup&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 34. Find First and Last Position of Element in Sorted Array</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Fri, 01 May 2026 18:04:20 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-34-find-first-and-last-position-of-element-in-sorted-array-lo0</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-34-find-first-and-last-position-of-element-in-sorted-array-lo0</guid>
      <description>&lt;h1&gt;
  
  
  Finding Your Way: First and Last Occurrences in a Sorted Array (LeetCode 34 Explained!)
&lt;/h1&gt;

&lt;p&gt;Hey there, future coding rockstars! 👋 Vansh here, and today we're diving into a super common, yet incredibly insightful problem from LeetCode: "Find First and Last Position of Element in Sorted Array."&lt;/p&gt;

&lt;p&gt;This problem is a fantastic way to level up your understanding of one of the most fundamental algorithms out there: &lt;strong&gt;Binary Search&lt;/strong&gt;. While simple binary search finds &lt;em&gt;if&lt;/em&gt; an element exists, this problem challenges us to find its &lt;em&gt;boundaries&lt;/em&gt; in a sorted list. Let's break it down!&lt;/p&gt;




&lt;h3&gt;
  
  
  🔍 Problem Explanation: What are We Even Doing?
&lt;/h3&gt;

&lt;p&gt;Imagine you have a phonebook (remember those?) where all names are sorted alphabetically. Now, imagine you're looking for every "Smith" in that phonebook. You don't just want &lt;em&gt;any&lt;/em&gt; Smith; you want to know where the first "Smith" starts and where the last "Smith" ends. That's exactly what this problem asks!&lt;/p&gt;

&lt;p&gt;Formally, we're given:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  An array of integers &lt;code&gt;nums&lt;/code&gt;. Crucially, this array is &lt;strong&gt;sorted in non-decreasing order&lt;/strong&gt; (meaning numbers either stay the same or go up).&lt;/li&gt;
&lt;li&gt;  A &lt;code&gt;target&lt;/code&gt; integer value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Our mission:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Find the &lt;strong&gt;starting index&lt;/strong&gt; (first occurrence) of &lt;code&gt;target&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Find the &lt;strong&gt;ending index&lt;/strong&gt; (last occurrence) of &lt;code&gt;target&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Return these as an array &lt;code&gt;[start_index, end_index]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If the &lt;code&gt;target&lt;/code&gt; isn't found anywhere in &lt;code&gt;nums&lt;/code&gt;, we should return &lt;code&gt;[-1, -1]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The kicker? We &lt;em&gt;must&lt;/em&gt; do this with an &lt;strong&gt;O(log n) runtime complexity&lt;/strong&gt;. This is a strong hint for using Binary Search!&lt;/p&gt;

&lt;p&gt;Let's look at a few examples:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: &lt;code&gt;nums = [5,7,7,8,8,10], target = 8&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The first &lt;code&gt;8&lt;/code&gt; is at index &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  The last &lt;code&gt;8&lt;/code&gt; is at index &lt;code&gt;4&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;[3, 4]&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 2: &lt;code&gt;nums = [5,7,7,8,8,10], target = 6&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;6&lt;/code&gt; is not in the array.&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;[-1, -1]&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 3: &lt;code&gt;nums = [], target = 0&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The array is empty. &lt;code&gt;0&lt;/code&gt; can't be found.&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;[-1, -1]&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  🤔 Intuition: The "Aha!" Moment
&lt;/h3&gt;

&lt;p&gt;When you see a &lt;strong&gt;sorted array&lt;/strong&gt; and an &lt;strong&gt;O(log n)&lt;/strong&gt; complexity requirement, your brain should immediately scream: &lt;strong&gt;BINARY SEARCH!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A standard binary search helps you find &lt;em&gt;if&lt;/em&gt; an element exists and its index. But here, if &lt;code&gt;target&lt;/code&gt; appears multiple times, a standard binary search might give you &lt;em&gt;any&lt;/em&gt; of its occurrences, not necessarily the first or last.&lt;/p&gt;

&lt;p&gt;The "aha!" moment is realizing that we can &lt;strong&gt;adapt binary search&lt;/strong&gt; to specifically look for the leftmost (first) occurrence and then, with a slight modification, for the rightmost (last) occurrence.&lt;/p&gt;

&lt;p&gt;Think about it:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;To find the &lt;em&gt;first&lt;/em&gt; occurrence:&lt;/strong&gt; If we find the &lt;code&gt;target&lt;/code&gt; at &lt;code&gt;mid&lt;/code&gt;, we store this &lt;code&gt;mid&lt;/code&gt; as a potential answer, but then we try to find an even &lt;em&gt;earlier&lt;/em&gt; &lt;code&gt;target&lt;/code&gt; by continuing our search in the &lt;strong&gt;left half&lt;/strong&gt; of the current array (&lt;code&gt;end = mid - 1&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;To find the &lt;em&gt;last&lt;/em&gt; occurrence:&lt;/strong&gt; If we find the &lt;code&gt;target&lt;/code&gt; at &lt;code&gt;mid&lt;/code&gt;, we store this &lt;code&gt;mid&lt;/code&gt; as a potential answer, but then we try to find an even &lt;em&gt;later&lt;/em&gt; &lt;code&gt;target&lt;/code&gt; by continuing our search in the &lt;strong&gt;right half&lt;/strong&gt; of the current array (&lt;code&gt;start = mid + 1&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This way, we "squeeze" our search space until we pinpoint the extreme positions!&lt;/p&gt;




&lt;h3&gt;
  
  
  🪜 Approach: Step-by-Step Logic
&lt;/h3&gt;

&lt;p&gt;We'll essentially perform two separate binary searches: one for the first occurrence and one for the last occurrence.&lt;/p&gt;

&lt;p&gt;Let's define a helper function, say &lt;code&gt;find_occurrence(nums, target, find_first)&lt;/code&gt;, that can do both based on a flag.&lt;/p&gt;

&lt;h4&gt;
  
  
  1. &lt;code&gt;find_occurrence(nums, target, find_first)&lt;/code&gt; Function Logic:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;  Initialize &lt;code&gt;ans = -1&lt;/code&gt;. This will store our found index.&lt;/li&gt;
&lt;li&gt;  Initialize &lt;code&gt;start = 0&lt;/code&gt; and &lt;code&gt;end = len(nums) - 1&lt;/code&gt;. These define our search space.&lt;/li&gt;
&lt;li&gt;  While &lt;code&gt;start &amp;lt;= end&lt;/code&gt;:

&lt;ul&gt;
&lt;li&gt;  Calculate &lt;code&gt;mid = start + (end - start) // 2&lt;/code&gt;. (Using &lt;code&gt;(end - start) // 2&lt;/code&gt; instead of &lt;code&gt;(start + end) // 2&lt;/code&gt; helps prevent potential integer overflow for very large &lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; values, though less critical in Python).&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Case 1: &lt;code&gt;nums[mid] == target&lt;/code&gt;&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We found a &lt;code&gt;target&lt;/code&gt;! Store &lt;code&gt;mid&lt;/code&gt; in &lt;code&gt;ans&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Now, the crucial part:

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;find_first&lt;/code&gt; is &lt;code&gt;True&lt;/code&gt; (we're looking for the first occurrence): We know &lt;code&gt;mid&lt;/code&gt; &lt;em&gt;could&lt;/em&gt; be our first, but there might be an even earlier one. So, we shrink our search space to the &lt;strong&gt;left&lt;/strong&gt;: &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;find_first&lt;/code&gt; is &lt;code&gt;False&lt;/code&gt; (we're looking for the last occurrence): We know &lt;code&gt;mid&lt;/code&gt; &lt;em&gt;could&lt;/em&gt; be our last, but there might be an even later one. So, we shrink our search space to the &lt;strong&gt;right&lt;/strong&gt;: &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;Case 2: &lt;code&gt;nums[mid] &amp;lt; target&lt;/code&gt;&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;target&lt;/code&gt; must be in the right half (if it exists). Shift our search to the right: &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;Case 3: &lt;code&gt;nums[mid] &amp;gt; target&lt;/code&gt;&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;target&lt;/code&gt; must be in the left half (if it exists). Shift our search to the left: &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;/li&gt;

&lt;li&gt;  Return &lt;code&gt;ans&lt;/code&gt;.&lt;/li&gt;

&lt;/ul&gt;

&lt;h4&gt;
  
  
  2. Main Function Logic:
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt; Call &lt;code&gt;find_occurrence(nums, target, True)&lt;/code&gt; to get the &lt;code&gt;first_occurrence&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; Call &lt;code&gt;find_occurrence(nums, target, False)&lt;/code&gt; to get the &lt;code&gt;last_occurrence&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; Return &lt;code&gt;[first_occurrence, last_occurrence]&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This elegant modification to binary search allows us to pinpoint both boundaries efficiently!&lt;/p&gt;




&lt;h3&gt;
  
  
  💻 Code
&lt;/h3&gt;

&lt;p&gt;Here's the Python implementation based on our approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;searchRange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;

        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;find_first&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;
            Helper function to find either the first or last occurrence of the target.

            Args:
                nums (list): The sorted array.
                target (int): The value to search for.
                find_first (bool): If True, search for the first occurrence.
                                   If False, search for the last occurrence.

            Returns:
                int: The index of the found occurrence, or -1 if not found.
            &lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
            &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
            &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;

                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;  &lt;span class="c1"&gt;# Store potential answer
&lt;/span&gt;                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;find_first&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                        &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Try to find an even earlier occurrence on the left
&lt;/span&gt;                    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                        &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Try to find an even later occurrence on the right
&lt;/span&gt;                &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Target is in the right half
&lt;/span&gt;                &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# nums[mid] &amp;gt; target
&lt;/span&gt;                    &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Target is in the left half
&lt;/span&gt;            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;

        &lt;span class="c1"&gt;# Find the first occurrence
&lt;/span&gt;        &lt;span class="n"&gt;first_pos&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;find_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Find the last occurrence
&lt;/span&gt;        &lt;span class="n"&gt;last_pos&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;find_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;first_pos&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;last_pos&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  ⏱️ Time &amp;amp; Space Complexity Analysis
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Time Complexity: O(log n)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We perform two independent binary searches. Each binary search takes &lt;code&gt;O(log n)&lt;/code&gt; time because we repeatedly halve the search space. Therefore, &lt;code&gt;O(log n) + O(log n)&lt;/code&gt; simplifies to &lt;code&gt;O(log n)&lt;/code&gt;. This satisfies the problem's constraint!&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We only use a few constant extra variables (&lt;code&gt;start&lt;/code&gt;, &lt;code&gt;end&lt;/code&gt;, &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;ans&lt;/code&gt;). We don't allocate any data structures that grow with the input size &lt;code&gt;n&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;




&lt;h3&gt;
  
  
  💡 Key Takeaways
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Binary Search is your best friend for sorted arrays!&lt;/strong&gt; Always consider it when you see "sorted" and "O(log n)".&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Binary Search isn't just for exact matches.&lt;/strong&gt; It's a versatile algorithm that can be adapted to find boundaries, closest elements, and more, with slight modifications to its core logic (especially how you adjust &lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; when &lt;code&gt;nums[mid] == target&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Modularize your code.&lt;/strong&gt; Breaking down the problem into a helper function for &lt;code&gt;find_occurrence&lt;/code&gt; makes the main &lt;code&gt;searchRange&lt;/code&gt; function clean, readable, and less repetitive.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This problem is a fantastic stepping stone from basic binary search to more complex variations. Master this, and you'll be well on your way to tackling trickier search problems!&lt;/p&gt;

&lt;p&gt;Happy coding! ✨&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Author: Vansh2710 | Published: 2026-05-01 23:33:33&lt;/em&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 74. Search a 2D Matrix</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Thu, 30 Apr 2026 17:11:20 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-74-search-a-2d-matrix-2p3f</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-74-search-a-2d-matrix-2p3f</guid>
      <description>&lt;h1&gt;
  
  
  LeetCode 74: Search a 2D Matrix - Conquer the Grid with Binary Search!
&lt;/h1&gt;

&lt;p&gt;Hey fellow coders and problem-solvers! 👋 Vansh2710 here, diving into another LeetCode adventure. Today, we're tackling a classic problem that brilliantly combines the elegance of a sorted structure with the power of binary search: &lt;strong&gt;"Search a 2D Matrix"&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This problem is a fantastic stepping stone for understanding how seemingly complex 2D data structures can often be simplified and optimized using fundamental algorithms. Ready to unlock its secrets? Let's go!&lt;/p&gt;




&lt;h2&gt;
  
  
  Problem Explanation: What's the Challenge?
&lt;/h2&gt;

&lt;p&gt;Imagine you're given a special kind of grid, an &lt;code&gt;m x n&lt;/code&gt; matrix, filled with integers. This isn't just any grid, though; it has two super helpful properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Each row is sorted:&lt;/strong&gt; If you pick any row and read it from left to right, the numbers are always increasing (non-decreasing, to be precise).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Rows are also "sorted" relative to each other:&lt;/strong&gt; The very first number in any given row is &lt;em&gt;always&lt;/em&gt; greater than the very last number of the row directly above it. Think of it like a staircase where each step starts higher than the previous one ended.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Your mission? Given this unique matrix and a &lt;code&gt;target&lt;/code&gt; integer, you need to figure out if &lt;code&gt;target&lt;/code&gt; exists anywhere in this matrix. The catch? You &lt;strong&gt;must&lt;/strong&gt; do it super efficiently, in &lt;code&gt;O(log(m * n))&lt;/code&gt; time.&lt;/p&gt;

&lt;p&gt;Let's look at an example to make it crystal clear:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]&lt;/code&gt;, &lt;code&gt;target = 3&lt;/code&gt;&lt;br&gt;
Output: &lt;code&gt;true&lt;/code&gt; (Because &lt;code&gt;3&lt;/code&gt; is in the first row!)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]&lt;/code&gt;, &lt;code&gt;target = 13&lt;/code&gt;&lt;br&gt;
Output: &lt;code&gt;false&lt;/code&gt; (13 is nowhere to be found in this matrix.)&lt;/p&gt;

&lt;p&gt;Notice how the numbers &lt;code&gt;1,3,5,7&lt;/code&gt; are sorted. Then &lt;code&gt;10&lt;/code&gt; (first of second row) is greater than &lt;code&gt;7&lt;/code&gt; (last of first row). &lt;code&gt;10,11,16,20&lt;/code&gt; are sorted. &lt;code&gt;23&lt;/code&gt; (first of third row) is greater than &lt;code&gt;20&lt;/code&gt; (last of second row). This pattern is key!&lt;/p&gt;


&lt;h2&gt;
  
  
  Intuition: The "Aha!" Moment 💡
&lt;/h2&gt;

&lt;p&gt;When you hear "sorted data" and "logarithmic time complexity" in the same sentence, what's the first algorithm that pops into your mind? If you thought &lt;strong&gt;Binary Search&lt;/strong&gt;, you're absolutely on the right track!&lt;/p&gt;

&lt;p&gt;Binary search works wonders on 1D sorted arrays. But we have a 2D matrix here. How can we apply binary search to it?&lt;/p&gt;

&lt;p&gt;This is where the magic happens! Look at those two properties again:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Each row is sorted.&lt;/li&gt;
&lt;li&gt;  The first element of a row is greater than the last element of the previous row.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These two properties combined mean that if you were to "flatten" or "unroll" this entire 2D matrix into a single 1D array, that resulting 1D array would also be &lt;strong&gt;perfectly sorted&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;Imagine taking all elements from the first row, then all elements from the second row, and so on, and concatenating them. You'd get something like &lt;code&gt;[1,3,5,7,10,11,16,20,23,30,34,60]&lt;/code&gt;. See? It's completely sorted!&lt;/p&gt;

&lt;p&gt;So, the "aha!" moment is: &lt;strong&gt;We can treat this 2D matrix as a single, giant, sorted 1D array and perform a standard binary search on it!&lt;/strong&gt;&lt;/p&gt;


&lt;h2&gt;
  
  
  Approach: From 2D to 1D (and Back!)
&lt;/h2&gt;

&lt;p&gt;Our strategy will be to simulate a binary search on this "flattened" 1D array. But how do we access elements if we're only actually given a 2D matrix? We need a way to map the index of an element in our conceptual 1D array back to its corresponding &lt;code&gt;(row, column)&lt;/code&gt; in the original 2D matrix.&lt;/p&gt;

&lt;p&gt;Let's say our matrix has &lt;code&gt;m&lt;/code&gt; rows and &lt;code&gt;n&lt;/code&gt; columns. The total number of elements is &lt;code&gt;m * n&lt;/code&gt;.&lt;br&gt;
If we have a 1D index &lt;code&gt;k&lt;/code&gt; (where &lt;code&gt;k&lt;/code&gt; ranges from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;(m*n - 1)&lt;/code&gt;), how do we find its &lt;code&gt;(row, col)&lt;/code&gt; in the 2D matrix?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Row Calculation:&lt;/strong&gt; In a matrix with &lt;code&gt;n&lt;/code&gt; columns, each row contains &lt;code&gt;n&lt;/code&gt; elements. So, an element at 1D index &lt;code&gt;k&lt;/code&gt; would be in row &lt;code&gt;k / n&lt;/code&gt; (integer division).&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Column Calculation:&lt;/strong&gt; Within that row, its column index would be &lt;code&gt;k % n&lt;/code&gt; (remainder after division by &lt;code&gt;n&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, in a &lt;code&gt;3x4&lt;/code&gt; matrix (&lt;code&gt;n=4&lt;/code&gt; columns):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  1D index &lt;code&gt;0&lt;/code&gt; -&amp;gt; &lt;code&gt;(0/4, 0%4)&lt;/code&gt; -&amp;gt; &lt;code&gt;(0, 0)&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  1D index &lt;code&gt;3&lt;/code&gt; -&amp;gt; &lt;code&gt;(3/4, 3%4)&lt;/code&gt; -&amp;gt; &lt;code&gt;(0, 3)&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  1D index &lt;code&gt;4&lt;/code&gt; -&amp;gt; &lt;code&gt;(4/4, 4%4)&lt;/code&gt; -&amp;gt; &lt;code&gt;(1, 0)&lt;/code&gt; (This is the start of the second row!)&lt;/li&gt;
&lt;li&gt;  1D index &lt;code&gt;7&lt;/code&gt; -&amp;gt; &lt;code&gt;(7/4, 7%4)&lt;/code&gt; -&amp;gt; &lt;code&gt;(1, 3)&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  1D index &lt;code&gt;8&lt;/code&gt; -&amp;gt; &lt;code&gt;(8/4, 8%4)&lt;/code&gt; -&amp;gt; &lt;code&gt;(2, 0)&lt;/code&gt; (Start of the third row!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This mapping is the core of our solution!&lt;/p&gt;

&lt;p&gt;Here's the step-by-step approach:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Initialize Pointers:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;start&lt;/code&gt;: Set to &lt;code&gt;0&lt;/code&gt; (representing the first element of our conceptual 1D array).&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;end&lt;/code&gt;: Set to &lt;code&gt;(m * n) - 1&lt;/code&gt; (representing the last element).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Binary Search Loop:&lt;/strong&gt; Continue as long as &lt;code&gt;start &amp;lt;= end&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Calculate Midpoint:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;mid = start + (end - start) / 2&lt;/code&gt; (This prevents potential integer overflow compared to &lt;code&gt;(start + end) / 2&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Map Midpoint to 2D Coordinates:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;currentRow = mid / numberOfColumns&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;currentColumn = mid % numberOfColumns&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Retrieve Element:&lt;/strong&gt; Get &lt;code&gt;element = matrix[currentRow][currentColumn]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Compare and Adjust Pointers:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;element == target&lt;/code&gt;: We found it! Return &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;element &amp;lt; target&lt;/code&gt;: The target is larger, so we need to search in the right half of our conceptual array. Update &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;element &amp;gt; target&lt;/code&gt;: The target is smaller, so we need to search in the left half. Update &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Target Not Found:&lt;/strong&gt; If the loop finishes without finding the target, it means the target isn't in the matrix. Return &lt;code&gt;false&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;
  
  
  Code 🖥️
&lt;/h2&gt;

&lt;p&gt;Here's the C++ implementation following our binary search approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;searchMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Get the dimensions of the matrix&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;numRows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numRows&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Handle empty matrix edge case&lt;/span&gt;

        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numCols&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Handle empty rows edge case&lt;/span&gt;

        &lt;span class="c1"&gt;// Initialize binary search pointers for the conceptual 1D array&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numRows&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Total elements - 1&lt;/span&gt;

        &lt;span class="c1"&gt;// Perform binary search&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Calculate the middle index for the 1D conceptual array&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Map the 1D 'mid' index back to 2D (row, col) coordinates&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;elementRow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;elementCol&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Get the element at the calculated 2D coordinates&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;elementRow&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;elementCol&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

            &lt;span class="c1"&gt;// Compare the element with the target&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Target found!&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nf"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Element is too small, search in the right half&lt;/span&gt;
                &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Element is too large, search in the left half&lt;/span&gt;
                &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// If the loop finishes, the target was not found&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Time &amp;amp; Space Complexity Analysis
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Time Complexity: O(log(m * n))&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We are performing a binary search on a conceptual 1D array of &lt;code&gt;m * n&lt;/code&gt; elements.&lt;/li&gt;
&lt;li&gt;  In each step of binary search, we cut the search space in half.&lt;/li&gt;
&lt;li&gt;  Therefore, the number of operations is proportional to the logarithm of the total number of elements.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We are only using a few extra variables (&lt;code&gt;start&lt;/code&gt;, &lt;code&gt;end&lt;/code&gt;, &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;numRows&lt;/code&gt;, &lt;code&gt;numCols&lt;/code&gt;, etc.) which take up constant extra space regardless of the input matrix size.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;This solution perfectly meets the &lt;code&gt;O(log(m * n))&lt;/code&gt; requirement!&lt;/p&gt;




&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Binary Search Power:&lt;/strong&gt; Don't limit binary search to just 1D arrays! It can be applied to any data structure that can be conceptually "flattened" into a sorted sequence.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;2D to 1D Mapping:&lt;/strong&gt; Understanding how to convert a 1D index to 2D coordinates (&lt;code&gt;index / numCols&lt;/code&gt; for row, &lt;code&gt;index % numCols&lt;/code&gt; for column) is a powerful technique for grid problems.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Leverage Properties:&lt;/strong&gt; Always pay close attention to the problem constraints and properties. The two "sorted" properties were the keys that unlocked this efficient solution.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Edge Cases:&lt;/strong&gt; Remember to handle edge cases like empty matrices or empty rows, though the problem constraints (1 &amp;lt;= m, n) might sometimes make this less critical depending on the platform's test cases.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;That's it for LeetCode 74! I hope this breakdown helped you understand how to approach and solve this problem efficiently. Binary search is truly a fundamental algorithm, and seeing its application in a 2D context is a great way to solidify your understanding.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;




&lt;p&gt;Author Account: Vansh2710&lt;br&gt;
Published: 2026-04-30 22:40:57&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 74. Search a 2D Matrix</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Thu, 30 Apr 2026 17:04:43 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-74-search-a-2d-matrix-hm7</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-74-search-a-2d-matrix-hm7</guid>
      <description>&lt;h1&gt;
  
  
  Conquer the Sorted Labyrinth: Searching a 2D Matrix with Binary Search Magic! ✨
&lt;/h1&gt;

&lt;p&gt;Hey LeetCoders and aspiring developers! Vansh2710 here, ready to demystify another classic problem that's far simpler than it looks, especially if you know a neat trick. Today, we're diving into LeetCode problem 74: "Search a 2D Matrix."&lt;/p&gt;

&lt;p&gt;This problem is a fantastic way to solidify your understanding of binary search and see how it can be applied in seemingly non-standard situations. If you've ever felt intimidated by anything beyond a simple sorted array, this post is for you!&lt;/p&gt;

&lt;h2&gt;
  
  
  The Quest: Search a 2D Matrix
&lt;/h2&gt;

&lt;p&gt;Imagine you have a spreadsheet filled with numbers, but it has two very special properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Each row is perfectly sorted:&lt;/strong&gt; From left to right, the numbers in every row are in increasing order.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Rows are also "sorted" relative to each other:&lt;/strong&gt; The very first number in any row is always larger than the very last number of the row directly above it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;matrix&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
  &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
  &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
  &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;23&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;34&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice how &lt;code&gt;7&lt;/code&gt; (last in row 0) is less than &lt;code&gt;10&lt;/code&gt; (first in row 1), and &lt;code&gt;20&lt;/code&gt; (last in row 1) is less than &lt;code&gt;23&lt;/code&gt; (first in row 2). This is a crucial detail!&lt;/p&gt;

&lt;p&gt;Your mission? Given this &lt;code&gt;matrix&lt;/code&gt; and an integer &lt;code&gt;target&lt;/code&gt;, you need to figure out if &lt;code&gt;target&lt;/code&gt; exists anywhere in the &lt;code&gt;matrix&lt;/code&gt;. You also have a secret constraint: your solution &lt;strong&gt;must be super-efficient&lt;/strong&gt;, running in &lt;code&gt;O(log(m * n))&lt;/code&gt; time. That's a big hint!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
Input: &lt;code&gt;matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]&lt;/code&gt;, &lt;code&gt;target = 3&lt;/code&gt;&lt;br&gt;
Output: &lt;code&gt;true&lt;/code&gt; (3 is right there in the first row!)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;br&gt;
Input: &lt;code&gt;matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]&lt;/code&gt;, &lt;code&gt;target = 13&lt;/code&gt;&lt;br&gt;
Output: &lt;code&gt;false&lt;/code&gt; (13 is nowhere to be found in this matrix.)&lt;/p&gt;
&lt;h2&gt;
  
  
  The "Aha!" Moment: Flattening the Matrix (Mentally!)
&lt;/h2&gt;

&lt;p&gt;At first glance, you might think of iterating through each row and then doing a binary search on that row. That's a decent start, but it might not hit our &lt;code&gt;O(log(m * n))&lt;/code&gt; target directly. A binary search on &lt;code&gt;m&lt;/code&gt; rows, each of length &lt;code&gt;n&lt;/code&gt;, would be &lt;code&gt;O(m * log n)&lt;/code&gt; in the worst case (if we had to search every row).&lt;/p&gt;

&lt;p&gt;However, those two special properties of the matrix are screaming a secret: &lt;strong&gt;this 2D matrix behaves exactly like a single, giant, perfectly sorted 1D array!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Think about it:&lt;br&gt;
If you take the first row &lt;code&gt;[1, 3, 5, 7]&lt;/code&gt;, then the second row &lt;code&gt;[10, 11, 16, 20]&lt;/code&gt;, and so on, and just concatenate them all together, you'd get:&lt;br&gt;
&lt;code&gt;[1, 3, 5, 7, 10, 11, 16, 20, 23, 30, 34, 60]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This new "flattened" array is completely sorted! And what do we use for finding elements efficiently in a sorted array? &lt;strong&gt;Binary Search!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The "aha!" is realizing we don't &lt;em&gt;actually&lt;/em&gt; need to flatten the array. We can just pretend it's a 1D array and use clever math to translate our 1D binary search indices back into 2D &lt;code&gt;(row, column)&lt;/code&gt; coordinates.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Approach: Binary Search on a Virtual 1D Array
&lt;/h2&gt;

&lt;p&gt;Here's how we apply the binary search magic:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Count Elements:&lt;/strong&gt; First, determine the total number of elements in the matrix. If the matrix has &lt;code&gt;m&lt;/code&gt; rows and &lt;code&gt;n&lt;/code&gt; columns, the total number of elements is &lt;code&gt;m * n&lt;/code&gt;. Let's call this &lt;code&gt;totalElements&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Define Search Space:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Our "virtual" 1D array has indices from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;totalElements - 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Initialize &lt;code&gt;start = 0&lt;/code&gt; and &lt;code&gt;end = totalElements - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Binary Search Loop:&lt;/strong&gt; Continue as long as &lt;code&gt;start &amp;lt;= end&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Calculate &lt;code&gt;mid&lt;/code&gt;:&lt;/strong&gt; Find the middle index using &lt;code&gt;mid = start + (end - start) / 2&lt;/code&gt;. This formula helps prevent integer overflow compared to &lt;code&gt;(start + end) / 2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Convert 1D &lt;code&gt;mid&lt;/code&gt; to 2D &lt;code&gt;(row, column)&lt;/code&gt;:&lt;/strong&gt; This is the clever part!

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;row&lt;/code&gt; index for our &lt;code&gt;mid&lt;/code&gt; element will be &lt;code&gt;mid / n&lt;/code&gt; (integer division).&lt;/li&gt;
&lt;li&gt;  The &lt;code&gt;column&lt;/code&gt; index for our &lt;code&gt;mid&lt;/code&gt; element will be &lt;code&gt;mid % n&lt;/code&gt; (modulo operator).&lt;/li&gt;
&lt;li&gt;  Why does this work? Imagine a 1D array mapped to a 2D grid. The first &lt;code&gt;n&lt;/code&gt; elements are in row 0, the next &lt;code&gt;n&lt;/code&gt; elements are in row 1, and so on. &lt;code&gt;mid / n&lt;/code&gt; tells you how many full rows &lt;code&gt;mid&lt;/code&gt; has "passed", giving you its row. &lt;code&gt;mid % n&lt;/code&gt; tells you its position within that specific row.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Get the &lt;code&gt;element&lt;/code&gt;:&lt;/strong&gt; Retrieve the actual value from the matrix using &lt;code&gt;matrix[mid / n][mid % n]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Compare and Adjust:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;element == target&lt;/code&gt;: Congratulations! You found it. Return &lt;code&gt;true&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;element &amp;lt; target&lt;/code&gt;: The target must be in the "right half" of our virtual array (i.e., larger values). So, update &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;element &amp;gt; target&lt;/code&gt;: The target must be in the "left half" of our virtual array (i.e., smaller values). So, update &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Not Found:&lt;/strong&gt; If the loop finishes (meaning &lt;code&gt;start&lt;/code&gt; became greater than &lt;code&gt;end&lt;/code&gt;), it means the &lt;code&gt;target&lt;/code&gt; was not present in the matrix. Return &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That's it! By treating the 2D matrix as a flat, sorted 1D array, we can leverage the power of binary search directly.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Code
&lt;/h2&gt;

&lt;p&gt;Here's the C++ implementation of this approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;searchMatrix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Get dimensions of the matrix&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;numRows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numRows&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Handle empty matrix edge case&lt;/span&gt;

        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numCols&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Handle empty rows edge case&lt;/span&gt;

        &lt;span class="c1"&gt;// Initialize binary search pointers for our virtual 1D array&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="c1"&gt;// Total number of elements, our 1D array's last index&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numRows&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

        &lt;span class="c1"&gt;// Standard binary search loop&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Calculate mid-point, preventing potential overflow&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Convert the 1D 'mid' index back to 2D (row, column) coordinates&lt;/span&gt;
            &lt;span class="c1"&gt;// row = mid / numCols&lt;/span&gt;
            &lt;span class="c1"&gt;// col = mid % numCols&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;matrix&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;numCols&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

            &lt;span class="c1"&gt;// Compare the element at mid with the target&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Target found!&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nf"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// Target is larger, so search in the right half&lt;/span&gt;
                &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// element &amp;gt; target&lt;/span&gt;
                &lt;span class="c1"&gt;// Target is smaller, so search in the left half&lt;/span&gt;
                &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// If the loop completes, the target was not found&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Complexity Analysis
&lt;/h2&gt;

&lt;p&gt;This is where our clever approach truly shines!&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Aspect&lt;/th&gt;
&lt;th&gt;Complexity&lt;/th&gt;
&lt;th&gt;Explanation&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Time Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;O(log(m * n))&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;We perform a binary search over &lt;code&gt;m * n&lt;/code&gt; elements. Each step reduces the search space by half.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Space Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;O(1)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;We only use a few constant extra variables (&lt;code&gt;start&lt;/code&gt;, &lt;code&gt;end&lt;/code&gt;, &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;numRows&lt;/code&gt;, &lt;code&gt;numCols&lt;/code&gt;, &lt;code&gt;element&lt;/code&gt;), regardless of the input matrix size.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;This beautifully meets the &lt;code&gt;O(log(m * n))&lt;/code&gt; time complexity requirement!&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Look for Hidden Order:&lt;/strong&gt; Many problems, especially involving matrices, might have implicit properties that transform them into simpler, well-known data structures (like a sorted array).&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Binary Search Power:&lt;/strong&gt; Binary search isn't just for 1D arrays! With a little mathematical mapping, it can be applied to 2D structures or even more complex search spaces.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;1D to 2D Index Mapping:&lt;/strong&gt; Remember the trick: &lt;code&gt;row = index / num_cols&lt;/code&gt; and &lt;code&gt;col = index % num_cols&lt;/code&gt; is your go-to for converting a 1D index to 2D coordinates.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Efficiency Matters:&lt;/strong&gt; Understanding the time and space complexity helps you choose the most optimal algorithm, especially in competitive programming.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I hope this breakdown helped you understand how to approach this problem and empowered you to look for creative binary search applications! Keep coding, keep learning, and see you in the next post!&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Author: Vansh2710 | Published: 2026-04-30 22:33:53&lt;/em&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 283. Move Zeroes</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Sun, 26 Apr 2026 18:08:06 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-283-move-zeroes-5ema</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-283-move-zeroes-5ema</guid>
      <description>&lt;h1&gt;
  
  
  Zeroes Got You Down? Let's Kick 'Em to the Curb! (LeetCode 283: Move Zeroes)
&lt;/h1&gt;

&lt;p&gt;Hey there, future coding rockstars! 👋 Vansh2710 here, and today we're tackling a super common, yet incredibly insightful, LeetCode problem: &lt;strong&gt;283. Move Zeroes&lt;/strong&gt;. This problem is a fantastic introduction to a powerful technique and teaches us to think cleverly about modifying arrays.&lt;/p&gt;

&lt;p&gt;Don't let the simplicity fool you; mastering this kind of problem builds a solid foundation for much tougher challenges. Ready to make those zeroes move? Let's dive in!&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem: Zeroes on the Loose!
&lt;/h2&gt;

&lt;p&gt;Imagine you have a list of numbers, like &lt;code&gt;[0, 1, 0, 3, 12]&lt;/code&gt;. Your mission, should you choose to accept it, is to rearrange this list so that all the zeroes are at the very end. But there are a couple of crucial rules:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Maintain Relative Order:&lt;/strong&gt; The non-zero numbers must stay in their original order. So, &lt;code&gt;1&lt;/code&gt; must still come before &lt;code&gt;3&lt;/code&gt;, and &lt;code&gt;3&lt;/code&gt; before &lt;code&gt;12&lt;/code&gt;. You can't just sort the array!

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;[0, 1, 0, 3, 12]&lt;/code&gt; should become &lt;code&gt;[1, 3, 12, 0, 0]&lt;/code&gt;, not &lt;code&gt;[0, 0, 1, 3, 12]&lt;/code&gt; or &lt;code&gt;[1, 12, 3, 0, 0]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;In-Place Modification:&lt;/strong&gt; This is the big one! You can't create a &lt;em&gt;new&lt;/em&gt; array and copy elements over. You have to modify the &lt;em&gt;original&lt;/em&gt; array directly. This is like tidying up your room without using an extra box to put things into temporarily – you're just moving things around within the existing space.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
Input: &lt;code&gt;nums = [0, 1, 0, 3, 12]&lt;/code&gt;&lt;br&gt;
Output: &lt;code&gt;[1, 3, 12, 0, 0]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;br&gt;
Input: &lt;code&gt;nums = [0]&lt;/code&gt;&lt;br&gt;
Output: &lt;code&gt;[0]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Seems simple enough, right? But the "in-place" and "relative order" constraints make us think a little more deeply!&lt;/p&gt;

&lt;h2&gt;
  
  
  The "Aha!" Moment: Focus on What Matters!
&lt;/h2&gt;

&lt;p&gt;When faced with a problem that asks us to move certain elements to the end while maintaining the order of others, a common pitfall is to try and move the "bad" elements (the zeroes) to their destination directly. You might think, "If I see a zero, swap it with the next element until it's at the end!" But this quickly gets messy and breaks the relative order of non-zeroes.&lt;/p&gt;

&lt;p&gt;Instead, let's flip our perspective: &lt;strong&gt;what if we focus on the elements we &lt;em&gt;want&lt;/em&gt; to keep in order – the non-zero numbers?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The "aha!" moment here is realizing that we can effectively "collect" all the non-zero elements at the beginning of the array, in their correct relative order. Once we've done that, all the remaining spots at the end of the array &lt;em&gt;must&lt;/em&gt; be zeroes. This way, we ensure both the relative order and the in-place requirement.&lt;/p&gt;

&lt;h2&gt;
  
  
  Our Strategy: The Two-Pointer Dance!
&lt;/h2&gt;

&lt;p&gt;This problem is a classic candidate for the &lt;strong&gt;two-pointer technique&lt;/strong&gt;. We'll use two pointers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;&lt;code&gt;nonZeroPointer&lt;/code&gt;&lt;/strong&gt;: This pointer will keep track of where the &lt;em&gt;next non-zero element should be placed&lt;/em&gt;. It essentially marks the boundary between the "non-zero section" and the "unknown/zero section" of our array. It starts at the beginning (&lt;code&gt;index 0&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;&lt;code&gt;i&lt;/code&gt; (or &lt;code&gt;currentPointer&lt;/code&gt;)&lt;/strong&gt;: This pointer will iterate through the entire array from left to right, checking each element.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here's the step-by-step breakdown:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Initialize &lt;code&gt;nonZeroPointer&lt;/code&gt; to 0.&lt;/strong&gt; This is where our first non-zero number will go.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Iterate through the array with &lt;code&gt;i&lt;/code&gt;&lt;/strong&gt; (from &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;nums.size() - 1&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;For each &lt;code&gt;nums[i]&lt;/code&gt;:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[i]&lt;/code&gt; is NOT a zero&lt;/strong&gt;: This is a number we want to keep at the beginning!

&lt;ul&gt;
&lt;li&gt;  We put &lt;code&gt;nums[i]&lt;/code&gt; at &lt;code&gt;nums[nonZeroPointer]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Crucially&lt;/strong&gt;, if &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;nonZeroPointer&lt;/code&gt; are &lt;em&gt;different&lt;/em&gt;, it means we just moved a non-zero number from a later position (&lt;code&gt;i&lt;/code&gt;) to an earlier position (&lt;code&gt;nonZeroPointer&lt;/code&gt;). The element that was originally at &lt;code&gt;nums[i]&lt;/code&gt; (which was a zero that we overwrote, or a non-zero that we moved) is now at &lt;code&gt;nums[nonZeroPointer]&lt;/code&gt;. To ensure the "fill with zeroes" part implicitly, we perform a &lt;code&gt;swap&lt;/code&gt;. If &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;nonZeroPointer&lt;/code&gt; are the same, it means &lt;code&gt;nums[i]&lt;/code&gt; is already in its correct non-zero position, and we don't need to swap it with itself.&lt;/li&gt;
&lt;li&gt;  Increment &lt;code&gt;nonZeroPointer&lt;/code&gt; by 1, because the spot it was pointing to is now filled with a non-zero value, and the next non-zero should go to the &lt;em&gt;next&lt;/em&gt; available spot.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; After the loop finishes, all non-zero elements will be at the beginning of the array, in their correct relative order. All elements from &lt;code&gt;nonZeroPointer&lt;/code&gt; to the end of the array will implicitly be zeroes (due to the swaps moving zeroes out of the way or overwriting them with zeroes when &lt;code&gt;i == nonZeroPointer&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's trace &lt;code&gt;[0, 1, 0, 3, 12]&lt;/code&gt;:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;code&gt;i&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;nums[i]&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;nonZeroPointer&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;
&lt;code&gt;nums&lt;/code&gt; (before swap)&lt;/th&gt;
&lt;th&gt;Condition &lt;code&gt;(nums[i] != 0)&lt;/code&gt;
&lt;/th&gt;
&lt;th&gt;Action&lt;/th&gt;
&lt;th&gt;
&lt;code&gt;nums&lt;/code&gt; (after swap)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[0, 1, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;False&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[0, 1, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[0, 1, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;True&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;swap(nums[1], nums[0])&lt;/code&gt;; &lt;code&gt;nonZeroPointer&lt;/code&gt; becomes 1&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 0, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 0, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;False&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 0, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 0, 0, 3, 12]&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;True&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;swap(nums[3], nums[1])&lt;/code&gt;; &lt;code&gt;nonZeroPointer&lt;/code&gt; becomes 2&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 3, 0, 0, 12]&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;12&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 3, 0, 0, 12]&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;True&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;swap(nums[4], nums[2])&lt;/code&gt;; &lt;code&gt;nonZeroPointer&lt;/code&gt; becomes 3&lt;/td&gt;
&lt;td&gt;&lt;code&gt;[1, 3, 12, 0, 0]&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Loop ends. The array is &lt;code&gt;[1, 3, 12, 0, 0]&lt;/code&gt;. Perfect!&lt;/p&gt;

&lt;h2&gt;
  
  
  The Code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for std::vector&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;algorithm&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for std::swap&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="n"&gt;moveZeroes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;nonZeroPointer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Pointer for the next position for a non-zero element&lt;/span&gt;

        &lt;span class="c1"&gt;// Iterate through the array with 'i'&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// If the current element is non-zero,&lt;/span&gt;
            &lt;span class="c1"&gt;// it means we found an element that belongs in the non-zero section&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// If 'i' and 'nonZeroPointer' are different, it means&lt;/span&gt;
                &lt;span class="c1"&gt;// nums[i] is a non-zero element and nonZeroPointer is pointing&lt;/span&gt;
                &lt;span class="c1"&gt;// to a zero (or an element that will be a zero after the swap).&lt;/span&gt;
                &lt;span class="c1"&gt;// We swap to move the non-zero element to its correct position.&lt;/span&gt;
                &lt;span class="c1"&gt;// If i == nonZeroPointer, the element is already in place,&lt;/span&gt;
                &lt;span class="c1"&gt;// so we don't need to swap it with itself.&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;nonZeroPointer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;swap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;nonZeroPointer&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="c1"&gt;// Move the nonZeroPointer forward, indicating the next spot&lt;/span&gt;
                &lt;span class="c1"&gt;// for another non-zero element.&lt;/span&gt;
                &lt;span class="n"&gt;nonZeroPointer&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Complexity Analysis
&lt;/h2&gt;

&lt;p&gt;Let's break down how efficient our solution is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Time Complexity: O(N)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We iterate through the array exactly once with our &lt;code&gt;i&lt;/code&gt; pointer.&lt;/li&gt;
&lt;li&gt;  Inside the loop, operations like &lt;code&gt;if&lt;/code&gt; checks, &lt;code&gt;!=&lt;/code&gt;, and &lt;code&gt;swap&lt;/code&gt; take constant time, O(1).&lt;/li&gt;
&lt;li&gt;  Therefore, the total time complexity is directly proportional to the number of elements in the array, &lt;code&gt;N&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  We are modifying the array directly "in-place" without creating any auxiliary data structures that scale with the input size.&lt;/li&gt;
&lt;li&gt;  The &lt;code&gt;nonZeroPointer&lt;/code&gt; and &lt;code&gt;i&lt;/code&gt; variables only take up a constant amount of extra space.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;This solution is highly optimized, satisfying the "minimize total number of operations" follow-up as it performs at most &lt;code&gt;N&lt;/code&gt; swaps and &lt;code&gt;N&lt;/code&gt; comparisons.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Two-Pointer Power:&lt;/strong&gt; The two-pointer technique is your best friend for array manipulation problems, especially those involving sorting, partitioning, or relative ordering.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;In-Place Challenges:&lt;/strong&gt; When a problem demands "in-place" modification, think about how you can reuse the existing memory. Often, this involves overwriting elements or clever swapping.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Flip the Perspective:&lt;/strong&gt; Sometimes, focusing on what you &lt;em&gt;don't&lt;/em&gt; want can be harder than focusing on what you &lt;em&gt;do&lt;/em&gt; want. Instead of chasing zeroes, we collected non-zeroes.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Practice Makes Perfect:&lt;/strong&gt; This problem might seem straightforward now, but the "aha!" moment comes with practice. Keep solving, keep thinking, and soon these patterns will be second nature!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Happy coding, and may your arrays always be perfectly ordered!&lt;/p&gt;




&lt;p&gt;Author Account: Vansh2710&lt;br&gt;
Time Published: 2026-04-26 23:36:47&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 34. Find First and Last Position of Element in Sorted Array</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Sat, 25 Apr 2026 17:56:15 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-34-find-first-and-last-position-of-element-in-sorted-array-3mnd</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-34-find-first-and-last-position-of-element-in-sorted-array-3mnd</guid>
      <description>&lt;h1&gt;
  
  
  Uncover the Hidden Range: Finding First &amp;amp; Last Occurrences in Sorted Arrays (LeetCode #34)
&lt;/h1&gt;

&lt;p&gt;Hey everyone! Vansh2710 here, diving deep into another classic LeetCode problem that might seem tricky at first, but unravels beautifully with a touch of algorithmic magic. Today, we're tackling problem &lt;strong&gt;#34: Find First and Last Position of Element in Sorted Array&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This problem is a fantastic way to stretch your understanding of one of the most fundamental algorithms: Binary Search! Ready to find those elusive boundaries? Let's get started!&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem Explanation
&lt;/h2&gt;

&lt;p&gt;Imagine you have a super organized bookshelf where all the books are sorted alphabetically. Now, someone asks you to find &lt;em&gt;all&lt;/em&gt; copies of "The Great Gatsby" and tell them exactly where the first one starts and the last one ends on the shelf. That's essentially what we're doing here!&lt;/p&gt;

&lt;p&gt;Given an array of integers &lt;code&gt;nums&lt;/code&gt; that is already sorted in &lt;strong&gt;non-decreasing order&lt;/strong&gt; (meaning numbers are either increasing or staying the same), and a specific &lt;code&gt;target&lt;/code&gt; integer:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We need to find the &lt;strong&gt;starting index&lt;/strong&gt; (first occurrence) and the &lt;strong&gt;ending index&lt;/strong&gt; (last occurrence) of the &lt;code&gt;target&lt;/code&gt; value in &lt;code&gt;nums&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If the &lt;code&gt;target&lt;/code&gt; isn't found anywhere in the array, we should return &lt;code&gt;[-1, -1]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Crucially, your solution &lt;strong&gt;must run in O(log n) time complexity&lt;/strong&gt;. This is a massive hint!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's look at the examples:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;Input: nums = [5,7,7,8,8,10], target = 8&lt;/code&gt;&lt;br&gt;
&lt;code&gt;Output: [3,4]&lt;/code&gt;&lt;br&gt;
(The first '8' is at index 3, the last '8' is at index 4)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;Input: nums = [5,7,7,8,8,10], target = 6&lt;/code&gt;&lt;br&gt;
&lt;code&gt;Output: [-1,-1]&lt;/code&gt;&lt;br&gt;
(6 is not in the array)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 3:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;Input: nums = [], target = 0&lt;/code&gt;&lt;br&gt;
&lt;code&gt;Output: [-1,-1]&lt;/code&gt;&lt;br&gt;
(Empty array, target cannot be found)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Constraints to keep in mind:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The array &lt;code&gt;nums&lt;/code&gt; can be empty or have up to 10^5 elements.&lt;/li&gt;
&lt;li&gt;  Numbers and target can be quite large or small (negative values included).&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;nums&lt;/code&gt; is guaranteed to be sorted non-decreasingly.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Intuition: The "Aha!" Moment
&lt;/h2&gt;

&lt;p&gt;The moment you see "sorted array" and "O(log n) runtime complexity" in the same sentence, your brain should immediately yell &lt;strong&gt;"BINARY SEARCH!"&lt;/strong&gt; 🚀&lt;/p&gt;

&lt;p&gt;A standard binary search is excellent for telling you if an element &lt;em&gt;exists&lt;/em&gt; in a sorted array, and if so, it typically returns &lt;em&gt;one&lt;/em&gt; of its indices. But here, we need &lt;em&gt;two&lt;/em&gt; specific indices: the very first and the very last.&lt;/p&gt;

&lt;p&gt;So, how do we adapt our trusty binary search? Instead of stopping once we find the &lt;code&gt;target&lt;/code&gt;, we need to keep searching!&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  If we find the &lt;code&gt;target&lt;/code&gt; and we're looking for the &lt;strong&gt;first occurrence&lt;/strong&gt;, we mark that index as a potential answer, but then we try to find an even earlier &lt;code&gt;target&lt;/code&gt; by searching in the &lt;strong&gt;left half&lt;/strong&gt; of the current segment.&lt;/li&gt;
&lt;li&gt;  Conversely, if we find the &lt;code&gt;target&lt;/code&gt; and we're looking for the &lt;strong&gt;last occurrence&lt;/strong&gt;, we mark that index and then try to find an even later &lt;code&gt;target&lt;/code&gt; by searching in the &lt;strong&gt;right half&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This tweak transforms our standard binary search into a powerful tool for finding boundaries!&lt;/p&gt;

&lt;h2&gt;
  
  
  Approach: Two-Pronged Binary Search
&lt;/h2&gt;

&lt;p&gt;Our strategy will involve two separate, slightly modified binary searches:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;&lt;code&gt;find_first_occurrence(nums, target)&lt;/code&gt;&lt;/strong&gt;: This function will find the index of the first &lt;code&gt;target&lt;/code&gt; in the array.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;&lt;code&gt;find_last_occurrence(nums, target)&lt;/code&gt;&lt;/strong&gt;: This function will find the index of the last &lt;code&gt;target&lt;/code&gt; in the array.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's detail each one:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Finding the First Occurrence
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Initialize &lt;code&gt;ans = -1&lt;/code&gt; (this will store our result, default to not found).&lt;/li&gt;
&lt;li&gt;  Set &lt;code&gt;start = 0&lt;/code&gt; and &lt;code&gt;end = len(nums) - 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  While &lt;code&gt;start &amp;lt;= end&lt;/code&gt;:

&lt;ul&gt;
&lt;li&gt;  Calculate &lt;code&gt;mid = start + (end - start) // 2&lt;/code&gt; to prevent potential integer overflow.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[mid] == target&lt;/code&gt;&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  We found the &lt;code&gt;target&lt;/code&gt;! This &lt;code&gt;mid&lt;/code&gt; could be our first occurrence. Store it: &lt;code&gt;ans = mid&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  But wait, there might be an even &lt;em&gt;earlier&lt;/em&gt; &lt;code&gt;target&lt;/code&gt; to its left. So, we try to shrink our search space to the left: &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[mid] &amp;lt; target&lt;/code&gt;&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;target&lt;/code&gt; must be in the right half (or not present). So, search right: &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[mid] &amp;gt; target&lt;/code&gt;&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;target&lt;/code&gt; must be in the left half (or not present). So, search left: &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;/li&gt;

&lt;li&gt;  Return &lt;code&gt;ans&lt;/code&gt;.&lt;/li&gt;

&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. Finding the Last Occurrence
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Initialize &lt;code&gt;ans = -1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Set &lt;code&gt;start = 0&lt;/code&gt; and &lt;code&gt;end = len(nums) - 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  While &lt;code&gt;start &amp;lt;= end&lt;/code&gt;:

&lt;ul&gt;
&lt;li&gt;  Calculate &lt;code&gt;mid = start + (end - start) // 2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[mid] == target&lt;/code&gt;&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  We found the &lt;code&gt;target&lt;/code&gt;! This &lt;code&gt;mid&lt;/code&gt; could be our last occurrence. Store it: &lt;code&gt;ans = mid&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  But wait, there might be an even &lt;em&gt;later&lt;/em&gt; &lt;code&gt;target&lt;/code&gt; to its right. So, we try to shrink our search space to the right: &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[mid] &amp;lt; target&lt;/code&gt;&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;target&lt;/code&gt; must be in the right half (or not present). So, search right: &lt;code&gt;start = mid + 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;  &lt;strong&gt;If &lt;code&gt;nums[mid] &amp;gt; target&lt;/code&gt;&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;target&lt;/code&gt; must be in the left half (or not present). So, search left: &lt;code&gt;end = mid - 1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;/li&gt;

&lt;li&gt;  Return &lt;code&gt;ans&lt;/code&gt;.&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Finally, our main &lt;code&gt;searchRange&lt;/code&gt; function will simply call these two helper functions and return their results as &lt;code&gt;[first_occurrence, last_occurrence]&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;searchRange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
        &lt;span class="c1"&gt;# Helper function to find the first occurrence of the target
&lt;/span&gt;        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find_first_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;      &lt;span class="c1"&gt;# Potentially the first occurrence
&lt;/span&gt;                    &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Try to find an even earlier occurrence in the left half
&lt;/span&gt;                &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# arr[mid] &amp;gt; val
&lt;/span&gt;                    &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;

        &lt;span class="c1"&gt;# Helper function to find the last occurrence of the target
&lt;/span&gt;        &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find_last_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;ans&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;     &lt;span class="c1"&gt;# Potentially the last occurrence
&lt;/span&gt;                    &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;# Try to find an even later occurrence in the right half
&lt;/span&gt;                &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
                &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="c1"&gt;# arr[mid] &amp;gt; val
&lt;/span&gt;                    &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;

        &lt;span class="n"&gt;first&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;find_first_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;last&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;find_last_occurrence&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nums&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;last&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Time &amp;amp; Space Complexity Analysis
&lt;/h2&gt;

&lt;p&gt;Let's break down the efficiency of our solution:&lt;/p&gt;

&lt;h3&gt;
  
  
  Time Complexity: O(log n)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  We perform two independent binary searches: &lt;code&gt;find_first_occurrence&lt;/code&gt; and &lt;code&gt;find_last_occurrence&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Each binary search operates on a sorted array of &lt;code&gt;n&lt;/code&gt; elements and halves its search space in each step. This gives each individual search a time complexity of &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Since we do two of these operations sequentially, the total time complexity is &lt;code&gt;O(log n) + O(log n)&lt;/code&gt;, which simplifies to &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  This perfectly satisfies the problem's constraint!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Space Complexity: O(1)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Our solution uses a few constant variables (&lt;code&gt;left&lt;/code&gt;, &lt;code&gt;right&lt;/code&gt;, &lt;code&gt;mid&lt;/code&gt;, &lt;code&gt;ans&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  We are not using any auxiliary data structures that grow with the input size &lt;code&gt;n&lt;/code&gt; (like extra arrays or lists).&lt;/li&gt;
&lt;li&gt;  Therefore, the space complexity is &lt;code&gt;O(1)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Binary Search Power-Up&lt;/strong&gt;: Binary search isn't just for checking existence! By carefully adjusting the &lt;code&gt;start&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt; pointers when &lt;code&gt;nums[mid] == target&lt;/code&gt;, you can find specific boundaries like first/last occurrences, smallest element greater than &lt;code&gt;target&lt;/code&gt;, etc.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Two Searches for Two Boundaries&lt;/strong&gt;: For problems requiring both a start and an end index in a sorted array, often two slightly modified binary searches are the most straightforward and efficient approach.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Edge Cases&lt;/strong&gt;: Always consider empty arrays or cases where the target isn't found. Our solution handles these gracefully by initializing &lt;code&gt;ans = -1&lt;/code&gt; and letting the binary search naturally return it if no &lt;code&gt;target&lt;/code&gt; is ever found.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;&lt;code&gt;mid&lt;/code&gt; Calculation&lt;/strong&gt;: Using &lt;code&gt;mid = left + (right - left) // 2&lt;/code&gt; is a good practice to prevent potential integer overflow, especially in languages like C++ where &lt;code&gt;left + right&lt;/code&gt; could exceed &lt;code&gt;MAX_INT&lt;/code&gt; for very large &lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt;. In Python, this is less critical due to arbitrary precision integers, but it's a good habit!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hopefully, this breakdown helps you understand how to approach range-finding problems in sorted arrays! Keep practicing, and you'll master these variations in no time. Happy coding!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Author Account&lt;/strong&gt;: Vansh2710&lt;br&gt;
&lt;strong&gt;Time Published&lt;/strong&gt;: 2026-04-25 23:25:30&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 7. Reverse Integer</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Thu, 23 Apr 2026 19:52:22 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-22fj</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-22fj</guid>
      <description>&lt;h1&gt;
  
  
  Cracking LeetCode 7: Reversing Integers Without Breaking the Bank (or the Integer Limit!) 🚀
&lt;/h1&gt;

&lt;p&gt;Hey everyone! Vansh here, ready to dive into another classic LeetCode problem that might seem simple on the surface but hides a crucial twist: &lt;strong&gt;integer overflow&lt;/strong&gt;. Today, we're tackling &lt;a href="https://leetcode.com/problems/reverse-integer/" rel="noopener noreferrer"&gt;LeetCode Problem 7: Reverse Integer&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This problem is a fantastic stepping stone for beginners because it teaches you not just about basic arithmetic manipulations but also about handling the often-overlooked boundaries of data types. Let's get cracking!&lt;/p&gt;




&lt;h3&gt;
  
  
  Understanding the Challenge: Reverse Integer 🔄
&lt;/h3&gt;

&lt;p&gt;Imagine you have a number, say &lt;code&gt;123&lt;/code&gt;. The goal is to reverse its digits to get &lt;code&gt;321&lt;/code&gt;. Sounds easy, right? What if it's &lt;code&gt;-123&lt;/code&gt;? Then it should be &lt;code&gt;-321&lt;/code&gt;. And &lt;code&gt;120&lt;/code&gt; should become &lt;code&gt;21&lt;/code&gt; (leading zeros are dropped).&lt;/p&gt;

&lt;p&gt;Here's the catch: We're dealing with a &lt;strong&gt;signed 32-bit integer&lt;/strong&gt;. This means our number &lt;code&gt;x&lt;/code&gt; can range from &lt;code&gt;-2,147,483,648&lt;/code&gt; (which is -2&lt;sup&gt;31&lt;/sup&gt;) to &lt;code&gt;2,147,483,647&lt;/code&gt; (which is 2&lt;sup&gt;31&lt;/sup&gt; - 1).&lt;/p&gt;

&lt;p&gt;If, after reversing the digits, the number goes &lt;em&gt;outside&lt;/em&gt; this specific range, we're supposed to return &lt;code&gt;0&lt;/code&gt;. And to make things spicier, we &lt;strong&gt;cannot&lt;/strong&gt; use 64-bit integers to store our result temporarily. This constraint forces us to be clever with our overflow checks!&lt;/p&gt;

&lt;p&gt;Let's look at the examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;x = 123&lt;/code&gt;
&lt;strong&gt;Output:&lt;/strong&gt; &lt;code&gt;321&lt;/code&gt; (Perfectly within range)&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;x = -123&lt;/code&gt;
&lt;strong&gt;Output:&lt;/strong&gt; &lt;code&gt;-321&lt;/code&gt; (Also good!)&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;x = 120&lt;/code&gt;
&lt;strong&gt;Output:&lt;/strong&gt; &lt;code&gt;21&lt;/code&gt; (Trailing zero vanishes, as expected)&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Consider this tricky one:&lt;/strong&gt; If &lt;code&gt;x = 2147483647&lt;/code&gt; (the maximum 32-bit integer), reversing it would give &lt;code&gt;7463847412&lt;/code&gt;. This number is much larger than &lt;code&gt;2147483647&lt;/code&gt;, so we should return &lt;code&gt;0&lt;/code&gt;. This is where the overflow check comes in!&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  The "Aha!" Moment: Intuition ✨
&lt;/h3&gt;

&lt;p&gt;How do we reverse a number, digit by digit? Think about how you'd get the last digit of a number and then remove it.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Get the last digit:&lt;/strong&gt; The modulo operator (&lt;code&gt;%&lt;/code&gt;) is our best friend here! &lt;code&gt;123 % 10&lt;/code&gt; gives &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Remove the last digit:&lt;/strong&gt; Integer division (&lt;code&gt;/&lt;/code&gt;) does the trick! &lt;code&gt;123 / 10&lt;/code&gt; gives &lt;code&gt;12&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Build the reversed number:&lt;/strong&gt; If our &lt;code&gt;reversed_num&lt;/code&gt; starts at &lt;code&gt;0&lt;/code&gt;, and we get a &lt;code&gt;digit&lt;/code&gt;, we can do &lt;code&gt;reversed_num = reversed_num * 10 + digit&lt;/code&gt;.

&lt;ul&gt;
&lt;li&gt;  Start: &lt;code&gt;reversed_num = 0&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;x = 123&lt;/code&gt;, &lt;code&gt;digit = 3&lt;/code&gt;. &lt;code&gt;reversed_num = 0 * 10 + 3 = 3&lt;/code&gt;. &lt;code&gt;x = 12&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;x = 12&lt;/code&gt;, &lt;code&gt;digit = 2&lt;/code&gt;. &lt;code&gt;reversed_num = 3 * 10 + 2 = 32&lt;/code&gt;. &lt;code&gt;x = 1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;x = 1&lt;/code&gt;, &lt;code&gt;digit = 1&lt;/code&gt;. &lt;code&gt;reversed_num = 32 * 10 + 1 = 321&lt;/code&gt;. &lt;code&gt;x = 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Loop ends! We have &lt;code&gt;321&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This basic process works perfectly. But remember the overflow constraint? That's the real "aha!" moment. We can't just let &lt;code&gt;reversed_num * 10 + digit&lt;/code&gt; happen blindly. We need to check for potential overflow &lt;em&gt;before&lt;/em&gt; it occurs, because once an integer overflows, its value becomes unpredictable (or wraps around, which is incorrect for this problem).&lt;/p&gt;

&lt;p&gt;The trick for overflow is to check if &lt;code&gt;reversed_num&lt;/code&gt; is &lt;em&gt;already&lt;/em&gt; too large (or too small) such that multiplying it by 10 or adding the next digit would push it past &lt;code&gt;INT_MAX&lt;/code&gt; or &lt;code&gt;INT_MIN&lt;/code&gt;. Specifically, we check if &lt;code&gt;reversed_num &amp;gt; INT_MAX / 10&lt;/code&gt; or &lt;code&gt;reversed_num &amp;lt; INT_MIN / 10&lt;/code&gt;. If &lt;code&gt;reversed_num&lt;/code&gt; equals these thresholds, we need a final check on the &lt;code&gt;digit&lt;/code&gt;.&lt;/p&gt;




&lt;h3&gt;
  
  
  Step-by-Step Approach 🚶‍♂️
&lt;/h3&gt;

&lt;p&gt;Let's outline our robust approach:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Initialize &lt;code&gt;result&lt;/code&gt;:&lt;/strong&gt; We'll need a variable, let's call it &lt;code&gt;result&lt;/code&gt;, to store our reversed number. Initialize it to &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Loop while &lt;code&gt;x&lt;/code&gt; is not &lt;code&gt;0&lt;/code&gt;:&lt;/strong&gt; We continue this process until all digits from &lt;code&gt;x&lt;/code&gt; have been extracted.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Extract the last digit:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;int digit = x % 10;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Crucial Overflow Check (before updating &lt;code&gt;result&lt;/code&gt;!):&lt;/strong&gt; This is the heart of handling the constraints.

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Positive Overflow Check:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;result&lt;/code&gt; is already greater than &lt;code&gt;INT_MAX / 10&lt;/code&gt;, then multiplying &lt;code&gt;result&lt;/code&gt; by 10 will definitely overflow. Return &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;result&lt;/code&gt; is exactly equal to &lt;code&gt;INT_MAX / 10&lt;/code&gt;, then we need to check the &lt;code&gt;digit&lt;/code&gt;. &lt;code&gt;INT_MAX&lt;/code&gt; ends in &lt;code&gt;7&lt;/code&gt; (&lt;code&gt;2,147,483,647&lt;/code&gt;). If our &lt;code&gt;digit&lt;/code&gt; is greater than &lt;code&gt;7&lt;/code&gt; (i.e., &lt;code&gt;8&lt;/code&gt; or &lt;code&gt;9&lt;/code&gt;), then &lt;code&gt;result * 10 + digit&lt;/code&gt; will overflow. Return &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Negative Overflow Check:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;result&lt;/code&gt; is already less than &lt;code&gt;INT_MIN / 10&lt;/code&gt;, then multiplying &lt;code&gt;result&lt;/code&gt; by 10 will definitely underflow. Return &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;result&lt;/code&gt; is exactly equal to &lt;code&gt;INT_MIN / 10&lt;/code&gt;, then we need to check the &lt;code&gt;digit&lt;/code&gt;. &lt;code&gt;INT_MIN&lt;/code&gt; ends in &lt;code&gt;8&lt;/code&gt; (&lt;code&gt;-2,147,483,648&lt;/code&gt;). If our &lt;code&gt;digit&lt;/code&gt; is less than &lt;code&gt;-8&lt;/code&gt; (i.e., &lt;code&gt;-9&lt;/code&gt;), then &lt;code&gt;result * 10 + digit&lt;/code&gt; will underflow. Return &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Build the reversed number:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;result = result * 10 + digit;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Remove the last digit from &lt;code&gt;x&lt;/code&gt;:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;x = x / 10;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Return &lt;code&gt;result&lt;/code&gt;:&lt;/strong&gt; Once the loop finishes, &lt;code&gt;result&lt;/code&gt; holds our fully reversed integer (or &lt;code&gt;0&lt;/code&gt; if an overflow was detected).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This approach handles positive numbers, negative numbers, and most importantly, gracefully manages the overflow conditions without needing 64-bit integers!&lt;/p&gt;




&lt;h3&gt;
  
  
  The Code 💻
&lt;/h3&gt;

&lt;p&gt;Here's the C++ implementation using the &lt;code&gt;INT_MAX&lt;/code&gt; and &lt;code&gt;INT_MIN&lt;/code&gt; constants found in &lt;code&gt;&amp;lt;limits.h&amp;gt;&lt;/code&gt; (or &lt;code&gt;&amp;lt;climits&amp;gt;&lt;/code&gt; for C++):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;limits.h&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for INT_MAX and INT_MIN&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// This will store our reversed integer&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Step 1: Extract the last digit&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Step 2: Crucial Overflow Check BEFORE updating result&lt;/span&gt;
            &lt;span class="c1"&gt;// Check for potential positive overflow:&lt;/span&gt;
            &lt;span class="c1"&gt;// If result is already greater than INT_MAX / 10, then multiplying by 10 will surely overflow.&lt;/span&gt;
            &lt;span class="c1"&gt;// If result is exactly INT_MAX / 10, then adding a digit &amp;gt; 7 will cause overflow (since INT_MAX is 2,147,483,647).&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// Check for potential negative overflow (underflow):&lt;/span&gt;
            &lt;span class="c1"&gt;// If result is already less than INT_MIN / 10, then multiplying by 10 will surely underflow.&lt;/span&gt;
            &lt;span class="c1"&gt;// If result is exactly INT_MIN / 10, then adding a digit &amp;lt; -8 will cause underflow (since INT_MIN is -2,147,483,648).&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// Step 3: Build the reversed number&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Step 4: Remove the last digit from the original number&lt;/span&gt;
            &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Return the final reversed integer&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Time &amp;amp; Space Complexity Analysis ⏱️📏
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Time Complexity: O(log |x|)&lt;/strong&gt;&lt;br&gt;
We iterate through the digits of the input number &lt;code&gt;x&lt;/code&gt;. The number of digits in an integer &lt;code&gt;x&lt;/code&gt; is proportional to &lt;code&gt;log10(|x|)&lt;/code&gt;. For example, a 1-digit number takes 1 iteration, a 2-digit number takes 2 iterations, and so on. Since we process each digit exactly once, the time complexity is logarithmic with respect to the absolute value of &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;&lt;br&gt;
We use a fixed number of variables (&lt;code&gt;result&lt;/code&gt;, &lt;code&gt;digit&lt;/code&gt;). The amount of memory used does not grow with the size of the input &lt;code&gt;x&lt;/code&gt;. Hence, the space complexity is constant.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  Key Takeaways 💡
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Digit Manipulation:&lt;/strong&gt; The modulo (&lt;code&gt;% 10&lt;/code&gt;) and integer division (&lt;code&gt;/ 10&lt;/code&gt;) operators are your go-to tools for extracting and removing digits from an integer.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Building Numbers:&lt;/strong&gt; To construct a number from individual digits, multiply the current result by 10 and add the new digit.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Overflow is Critical:&lt;/strong&gt; Always be mindful of integer limits, especially in competitive programming problems where data type constraints are common.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Pre-emptive Checks:&lt;/strong&gt; For overflow problems where a larger data type isn't allowed, check for overflow &lt;em&gt;before&lt;/em&gt; performing operations that might cause it. The &lt;code&gt;INT_MAX / 10&lt;/code&gt; and &lt;code&gt;INT_MIN / 10&lt;/code&gt; trick is a standard way to do this.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This problem is a fantastic blend of basic arithmetic and careful edge-case handling. Master it, and you'll be well on your way to tackling more complex LeetCode challenges!&lt;/p&gt;

&lt;p&gt;Happy coding! 👩‍💻👨‍💻&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Author Account: Vansh2710&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Published: 2026-04-24 01:21:55&lt;/em&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 7. Reverse Integer</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Thu, 23 Apr 2026 19:14:28 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-1oi1</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-1oi1</guid>
      <description>&lt;h1&gt;
  
  
  Brain Teaser: Can You Reverse an Integer Without Breaking the Bank? (LeetCode #7)
&lt;/h1&gt;

&lt;p&gt;Hey there, fellow coding adventurers! 👋 Vansh2710 here, ready to dive into another classic LeetCode challenge. Today, we're tackling problem #7: &lt;strong&gt;Reverse Integer&lt;/strong&gt;. It sounds super simple, right? Just flip the digits! But as with many LeetCode problems, there's a sneaky little twist that makes it a fantastic learning experience about handling real-world integer limits.&lt;/p&gt;

&lt;p&gt;Let's unravel this puzzle together!&lt;/p&gt;




&lt;h3&gt;
  
  
  📚 Problem Explanation: The Core Challenge
&lt;/h3&gt;

&lt;p&gt;Imagine you have a number, say &lt;code&gt;123&lt;/code&gt;. Your task is to reverse its digits to get &lt;code&gt;321&lt;/code&gt;. Sounds simple, right? What about negative numbers? If &lt;code&gt;x = -123&lt;/code&gt;, the output should be &lt;code&gt;-321&lt;/code&gt;. And if &lt;code&gt;x = 120&lt;/code&gt;, the reversed number is &lt;code&gt;21&lt;/code&gt; (we naturally drop leading zeros, so &lt;code&gt;021&lt;/code&gt; becomes &lt;code&gt;21&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Here's the catch: We're dealing with a "signed 32-bit integer". This means our numbers have a strict upper and lower limit: they can go from &lt;code&gt;(-2^31)&lt;/code&gt; to &lt;code&gt;(2^31 - 1)&lt;/code&gt;. That's roughly from -2 billion to +2 billion. If reversing the number causes it to go beyond these limits (an "overflow"), your function &lt;em&gt;must&lt;/em&gt; return &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;And another critical rule&lt;/strong&gt;: You cannot use 64-bit integers (like &lt;code&gt;long long&lt;/code&gt; in C++) to store your result temporarily. This forces us to be clever with our overflow checks!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;x = 123&lt;/code&gt;
&lt;strong&gt;Output:&lt;/strong&gt; &lt;code&gt;321&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;x = -123&lt;/code&gt;
&lt;strong&gt;Output:&lt;/strong&gt; &lt;code&gt;-321&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Input:&lt;/strong&gt; &lt;code&gt;x = 120&lt;/code&gt;
&lt;strong&gt;Output:&lt;/strong&gt; &lt;code&gt;21&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  🧠 Intuition: How Do We "Flip" Numbers Digit by Digit?
&lt;/h3&gt;

&lt;p&gt;Let's break down the mechanics of reversing a number. How would you do it manually, one digit at a time?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Getting the Last Digit&lt;/strong&gt;: To grab the last digit of any integer, we can use the &lt;code&gt;modulo&lt;/code&gt; operator (&lt;code&gt;% 10&lt;/code&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  For &lt;code&gt;123&lt;/code&gt;, &lt;code&gt;123 % 10&lt;/code&gt; gives &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  For &lt;code&gt;12&lt;/code&gt;, &lt;code&gt;12 % 10&lt;/code&gt; gives &lt;code&gt;2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  For &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;1 % 10&lt;/code&gt; gives &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Removing the Last Digit&lt;/strong&gt;: After we've extracted a digit, we need to chop it off the original number. We can do this with &lt;code&gt;integer division&lt;/code&gt; (&lt;code&gt;/ 10&lt;/code&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  For &lt;code&gt;123&lt;/code&gt;, &lt;code&gt;123 / 10&lt;/code&gt; gives &lt;code&gt;12&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  For &lt;code&gt;12&lt;/code&gt;, &lt;code&gt;12 / 10&lt;/code&gt; gives &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  For &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;1 / 10&lt;/code&gt; gives &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Building the Reversed Number&lt;/strong&gt;: We need a variable to store our reversed number, let's call it &lt;code&gt;reversed_num&lt;/code&gt;, initialized to &lt;code&gt;0&lt;/code&gt;. Each time we extract a digit, we'll "shift" our current &lt;code&gt;reversed_num&lt;/code&gt; one place to the left (by multiplying by 10) and then add the new digit.&lt;/p&gt;

&lt;p&gt;Let's trace &lt;code&gt;x = 123&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Start&lt;/strong&gt;: &lt;code&gt;x = 123&lt;/code&gt;, &lt;code&gt;reversed_num = 0&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Iteration 1&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;digit = 123 % 10 = 3&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;reversed_num = 0 * 10 + 3 = 3&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;x = 123 / 10 = 12&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Iteration 2&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;digit = 12 % 10 = 2&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;reversed_num = 3 * 10 + 2 = 32&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;x = 12 / 10 = 1&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Iteration 3&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;digit = 1 % 10 = 1&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;reversed_num = 32 * 10 + 1 = 321&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;x = 1 / 10 = 0&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Loop ends&lt;/strong&gt; because &lt;code&gt;x&lt;/code&gt; is now &lt;code&gt;0&lt;/code&gt;. Return &lt;code&gt;321&lt;/code&gt;. Perfect!&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The "aha!" moment is realizing this iterative process. The &lt;em&gt;BIGGEST&lt;/em&gt; "aha!" (and the trickiest part) is figuring out how to check for overflow &lt;em&gt;before&lt;/em&gt; it actually happens, because once an integer overflows, its value becomes unpredictable!&lt;/p&gt;




&lt;h3&gt;
  
  
  🛠️ Approach: The Step-by-Step Logic
&lt;/h3&gt;

&lt;p&gt;Combining our intuition, here's the detailed plan to solve the Reverse Integer problem, keeping the overflow constraint in mind:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initialize &lt;code&gt;num = 0&lt;/code&gt;&lt;/strong&gt;: This variable will store our result as we build it digit by digit. We're using &lt;code&gt;num&lt;/code&gt; as per the provided solution snippet's variable name.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Loop While &lt;code&gt;x&lt;/code&gt; is Not Zero&lt;/strong&gt;: We'll keep extracting digits from &lt;code&gt;x&lt;/code&gt; and adding them to &lt;code&gt;num&lt;/code&gt; until &lt;code&gt;x&lt;/code&gt; becomes &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Critical Overflow Check&lt;/strong&gt;: This is the most vital part! Before we update &lt;code&gt;num&lt;/code&gt; (by multiplying by 10 and adding a new digit), we need to check if this operation will cause &lt;code&gt;num&lt;/code&gt; to exceed the &lt;code&gt;INT_MAX&lt;/code&gt; (maximum 32-bit integer) or fall below &lt;code&gt;INT_MIN&lt;/code&gt; (minimum 32-bit integer).&lt;/p&gt;

&lt;p&gt;The specific check provided in the solution snippet is:&lt;br&gt;
&lt;code&gt;if (num &amp;gt; INT_MAX / 10 || num &amp;lt; INT_MIN / 10)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let's break down &lt;em&gt;why&lt;/em&gt; this works:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;INT_MAX&lt;/code&gt; is the largest positive 32-bit integer (typically &lt;code&gt;2,147,483,647&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;INT_MIN&lt;/code&gt; is the smallest negative 32-bit integer (typically &lt;code&gt;-2,147,483,648&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;num&lt;/code&gt; is &lt;em&gt;already&lt;/em&gt; greater than &lt;code&gt;INT_MAX / 10&lt;/code&gt;, then multiplying &lt;code&gt;num&lt;/code&gt; by &lt;code&gt;10&lt;/code&gt; (even before adding the &lt;code&gt;digit&lt;/code&gt;) will &lt;em&gt;definitely&lt;/em&gt; exceed &lt;code&gt;INT_MAX&lt;/code&gt;. For example, if &lt;code&gt;INT_MAX / 10&lt;/code&gt; is roughly &lt;code&gt;2.1e8&lt;/code&gt;, and &lt;code&gt;num&lt;/code&gt; is &lt;code&gt;3e8&lt;/code&gt;, then &lt;code&gt;3e8 * 10 = 3e9&lt;/code&gt; is clearly too big.&lt;/li&gt;
&lt;li&gt;  The same logic applies to &lt;code&gt;INT_MIN / 10&lt;/code&gt; for checking negative overflow.&lt;/li&gt;
&lt;li&gt;  If this condition is true, we immediately &lt;code&gt;return 0&lt;/code&gt; because an overflow is imminent.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Extract the Last Digit&lt;/strong&gt;: &lt;code&gt;int digit = x % 10;&lt;/code&gt; (e.g., if &lt;code&gt;x=123&lt;/code&gt;, &lt;code&gt;digit=3&lt;/code&gt;). This digit will be appended to &lt;code&gt;num&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Build the Reversed Number&lt;/strong&gt;: &lt;code&gt;num = num * 10 + digit;&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  This shifts the existing digits in &lt;code&gt;num&lt;/code&gt; one position to the left and adds the newly extracted &lt;code&gt;digit&lt;/code&gt; to the rightmost position.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Remove the Last Digit from &lt;code&gt;x&lt;/code&gt;&lt;/strong&gt;: &lt;code&gt;x = x / 10;&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  This prepares &lt;code&gt;x&lt;/code&gt; for the next iteration, effectively "eating away" its digits from right to left.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Return &lt;code&gt;num&lt;/code&gt;&lt;/strong&gt;: Once the &lt;code&gt;while&lt;/code&gt; loop finishes (meaning &lt;code&gt;x&lt;/code&gt; has become &lt;code&gt;0&lt;/code&gt; and all digits have been processed), &lt;code&gt;num&lt;/code&gt; will hold the correctly reversed integer. If any overflow was detected, we would have returned &lt;code&gt;0&lt;/code&gt; earlier.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h3&gt;
  
  
  💻 Code: Bringing It All Together (C++)
&lt;/h3&gt;

&lt;p&gt;Here's the C++ implementation following our approach. Note that &lt;code&gt;INT_MAX&lt;/code&gt; and &lt;code&gt;INT_MIN&lt;/code&gt; are defined in the &lt;code&gt;&amp;lt;limits.h&amp;gt;&lt;/code&gt; (or &lt;code&gt;&amp;lt;climits&amp;gt;&lt;/code&gt;) header.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;limits.h&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for INT_MAX and INT_MIN&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// This variable will store our reversed number&lt;/span&gt;

        &lt;span class="c1"&gt;// Loop as long as there are digits left in x&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// --- OVERFLOW CHECK ---&lt;/span&gt;
            &lt;span class="c1"&gt;// This is the critical step. We check for potential overflow *before*&lt;/span&gt;
            &lt;span class="c1"&gt;// we perform the multiplication and addition that could cause it.&lt;/span&gt;
            &lt;span class="c1"&gt;// If 'num' is already so large (or small) that multiplying by 10&lt;/span&gt;
            &lt;span class="c1"&gt;// would exceed INT_MAX (or INT_MIN) even before adding the last digit,&lt;/span&gt;
            &lt;span class="c1"&gt;// we know an overflow is inevitable.&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Overflow detected, return 0 as per problem statement&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="c1"&gt;// --- END OVERFLOW CHECK ---&lt;/span&gt;

            &lt;span class="c1"&gt;// Extract the last digit of x&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Build the reversed number:&lt;/span&gt;
            &lt;span class="c1"&gt;// 1. Multiply 'num' by 10 to shift its existing digits one position to the left.&lt;/span&gt;
            &lt;span class="c1"&gt;// 2. Add the newly extracted 'digit' to the rightmost position.&lt;/span&gt;
            &lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Remove the last digit from x to process the next digit in the next iteration&lt;/span&gt;
            &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// After the loop, 'num' holds the completely reversed integer&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;num&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  ⏱️ Time &amp;amp; Space Complexity Analysis
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity: O(log |x|)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The &lt;code&gt;while&lt;/code&gt; loop runs once for each digit in the input number &lt;code&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  The number of digits in an integer &lt;code&gt;x&lt;/code&gt; is proportional to &lt;code&gt;log10(|x|)&lt;/code&gt;. For example, &lt;code&gt;log10(100)&lt;/code&gt; is &lt;code&gt;2&lt;/code&gt;, meaning 3 digits.&lt;/li&gt;
&lt;li&gt;  Therefore, the time complexity is logarithmic with respect to the absolute value of &lt;code&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We are only using a few constant-space variables (&lt;code&gt;num&lt;/code&gt;, &lt;code&gt;digit&lt;/code&gt;, &lt;code&gt;x&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  The memory usage does not grow with the size of the input number.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;




&lt;h3&gt;
  
  
  🌟 Key Takeaways
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Digit Manipulation is Key&lt;/strong&gt;: The &lt;code&gt;modulo % 10&lt;/code&gt; and &lt;code&gt;integer division / 10&lt;/code&gt; operators are your best friends for breaking down and building numbers digit by digit.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Edge Cases are Crucial&lt;/strong&gt;: Always consider negative inputs and numbers ending in zero (like &lt;code&gt;120&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;The Overflow Challenge&lt;/strong&gt;: When working with fixed-size integer types, understanding and implementing pre-emptive overflow checks is paramount. Doing the check &lt;em&gt;before&lt;/em&gt; the potentially overflowing operation is the way to go, especially when you can't use larger data types.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Practice Makes Perfect&lt;/strong&gt;: These types of problems build a strong foundation for thinking about integer properties and constraints.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Happy coding, and see you in the next LeetCode adventure! ✨&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Author Account: Vansh2710&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Time Published: 2026-04-24 00:43:37&lt;/em&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 7. Reverse Integer</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Thu, 23 Apr 2026 19:05:49 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-343a</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-343a</guid>
      <description>&lt;h1&gt;
  
  
  🚀 Master LeetCode 7: Reversing Integers Without Breaking the Bank (or Your Code!)
&lt;/h1&gt;

&lt;p&gt;Hey LeetCoders and aspiring developers! 👋 Vansh2710 here, your friendly neighborhood competitive programmer and technical writer. Today, we're diving into a classic LeetCode problem that might seem simple on the surface but hides a crucial detail that trips up many beginners (and even some seasoned folks!): &lt;strong&gt;Reverse Integer (Problem 7)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It's a fantastic problem to learn about integer manipulation and, more importantly, how to handle those pesky &lt;strong&gt;overflow&lt;/strong&gt; scenarios. Let's conquer it together!&lt;/p&gt;

&lt;h2&gt;
  
  
  📖 Problem Explained: The Digit Dilemma
&lt;/h2&gt;

&lt;p&gt;You're given a &lt;strong&gt;signed 32-bit integer&lt;/strong&gt; &lt;code&gt;x&lt;/code&gt;. Your task is to return &lt;code&gt;x&lt;/code&gt; with its digits reversed. Sounds easy, right?&lt;/p&gt;

&lt;p&gt;Here's the catch: If reversing &lt;code&gt;x&lt;/code&gt; causes its value to go &lt;strong&gt;outside the signed 32-bit integer range&lt;/strong&gt; (which is &lt;code&gt;[-2^31, 2^31 - 1]&lt;/code&gt;), you must return &lt;code&gt;0&lt;/code&gt;. Oh, and you can't use 64-bit integers. This last constraint is key!&lt;/p&gt;

&lt;p&gt;Let's look at some examples to get a feel for it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Input: &lt;code&gt;x = 123&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;321&lt;/code&gt; (Simple positive reversal)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Input: &lt;code&gt;x = -123&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;-321&lt;/code&gt; (Negative numbers reverse similarly, keeping the sign)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Example 3:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Input: &lt;code&gt;x = 120&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  Output: &lt;code&gt;21&lt;/code&gt; (Trailing zeros become leading zeros and get dropped)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;The core idea seems straightforward, but the "overflow" part is where the real challenge lies!&lt;/p&gt;

&lt;h2&gt;
  
  
  ✨ Intuition: Building Backwards, Digit by Digit
&lt;/h2&gt;

&lt;p&gt;Imagine you have the number &lt;code&gt;123&lt;/code&gt;. How would you "reverse" it manually?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; You'd grab the &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; Then the &lt;code&gt;2&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; Then the &lt;code&gt;1&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And then you'd put them together as &lt;code&gt;321&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;How can we do this programmatically?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Getting the last digit&lt;/strong&gt;: The modulo operator (&lt;code&gt;%&lt;/code&gt;) is our best friend! &lt;code&gt;123 % 10&lt;/code&gt; gives us &lt;code&gt;3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Removing the last digit&lt;/strong&gt;: Integer division (&lt;code&gt;/&lt;/code&gt;) comes to the rescue! &lt;code&gt;123 / 10&lt;/code&gt; gives us &lt;code&gt;12&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Building the reversed number&lt;/strong&gt;: Let's say we have a &lt;code&gt;reversed_num&lt;/code&gt; variable, initially &lt;code&gt;0&lt;/code&gt;.

&lt;ul&gt;
&lt;li&gt;  When we get &lt;code&gt;3&lt;/code&gt;: &lt;code&gt;reversed_num = 0 * 10 + 3 = 3&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  When we get &lt;code&gt;2&lt;/code&gt;: &lt;code&gt;reversed_num = 3 * 10 + 2 = 32&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  When we get &lt;code&gt;1&lt;/code&gt;: &lt;code&gt;reversed_num = 32 * 10 + 1 = 321&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;This "extract-and-build" loop forms the heart of our solution. But wait! What if &lt;code&gt;x&lt;/code&gt; is &lt;code&gt;2147483647&lt;/code&gt; (which is &lt;code&gt;INT_MAX&lt;/code&gt;)? Reversing it would give &lt;code&gt;7463847412&lt;/code&gt;, which is &lt;em&gt;much&lt;/em&gt; larger than &lt;code&gt;INT_MAX&lt;/code&gt;. This is where our &lt;strong&gt;overflow check&lt;/strong&gt; becomes absolutely vital! We need to detect this &lt;em&gt;before&lt;/em&gt; it happens.&lt;/p&gt;

&lt;h2&gt;
  
  
  🧠 Our Step-by-Step Approach
&lt;/h2&gt;

&lt;p&gt;Let's break down the logic into clear, manageable steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Initialize &lt;code&gt;reversed_num&lt;/code&gt;&lt;/strong&gt;: We'll need a variable, let's call it &lt;code&gt;reversed_num&lt;/code&gt;, initialized to &lt;code&gt;0&lt;/code&gt;. This will store our result as we build it.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Loop While &lt;code&gt;x&lt;/code&gt; Has Digits&lt;/strong&gt;: We'll use a &lt;code&gt;while&lt;/code&gt; loop that continues as long as &lt;code&gt;x&lt;/code&gt; is not &lt;code&gt;0&lt;/code&gt;. Each iteration will process one digit.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Extract the Last Digit&lt;/strong&gt;: Inside the loop, get the last digit of &lt;code&gt;x&lt;/code&gt; using &lt;code&gt;int digit = x % 10;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;🚨 CRITICAL OVERFLOW CHECK 🚨&lt;/strong&gt;: This is the most important part! &lt;em&gt;Before&lt;/em&gt; we actually update &lt;code&gt;reversed_num&lt;/code&gt; with the new digit, we need to check if doing so would cause an overflow (i.e., exceed &lt;code&gt;INT_MAX&lt;/code&gt; or go below &lt;code&gt;INT_MIN&lt;/code&gt;).

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;How to check?&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;reversed_num&lt;/code&gt; is already greater than &lt;code&gt;INT_MAX / 10&lt;/code&gt;, then multiplying &lt;code&gt;reversed_num&lt;/code&gt; by &lt;code&gt;10&lt;/code&gt; will definitely overflow.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;reversed_num&lt;/code&gt; is exactly &lt;code&gt;INT_MAX / 10&lt;/code&gt;, then adding a &lt;code&gt;digit&lt;/code&gt; greater than &lt;code&gt;7&lt;/code&gt; (since &lt;code&gt;INT_MAX&lt;/code&gt; is &lt;code&gt;2,147,483,647&lt;/code&gt; and &lt;code&gt;7&lt;/code&gt; is its last digit) will cause an overflow.&lt;/li&gt;
&lt;li&gt;  Similar logic applies for &lt;code&gt;INT_MIN&lt;/code&gt;: if &lt;code&gt;reversed_num &amp;lt; INT_MIN / 10&lt;/code&gt; or (&lt;code&gt;reversed_num == INT_MIN / 10&lt;/code&gt; and &lt;code&gt;digit &amp;lt; -8&lt;/code&gt;), it will underflow.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;  If any overflow/underflow is detected, immediately return &lt;code&gt;0&lt;/code&gt; as per the problem statement.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Build &lt;code&gt;reversed_num&lt;/code&gt;&lt;/strong&gt;: If no overflow is detected, safely update &lt;code&gt;reversed_num&lt;/code&gt;: &lt;code&gt;reversed_num = reversed_num * 10 + digit;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Shrink &lt;code&gt;x&lt;/code&gt;&lt;/strong&gt;: Remove the last digit from &lt;code&gt;x&lt;/code&gt; by integer division: &lt;code&gt;x /= 10;&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Return Result&lt;/strong&gt;: Once the loop finishes (meaning &lt;code&gt;x&lt;/code&gt; is &lt;code&gt;0&lt;/code&gt; and all digits have been processed), return the final &lt;code&gt;reversed_num&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  ✍️ The Code (C++)
&lt;/h2&gt;

&lt;p&gt;Here's the C++ implementation incorporating the logic we just discussed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;limits.h&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for INT_MAX and INT_MIN&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// This will store our reversed integer&lt;/span&gt;

        &lt;span class="c1"&gt;// Loop until x becomes 0 (all digits processed)&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Extract the last digit of x&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// --- CRITICAL OVERFLOW CHECK ---&lt;/span&gt;
            &lt;span class="c1"&gt;// This check must happen BEFORE we update `reversed_num`.&lt;/span&gt;
            &lt;span class="c1"&gt;// We're essentially asking: "If I multiply `reversed_num` by 10&lt;/span&gt;
            &lt;span class="c1"&gt;// and add `digit`, will it go out of bounds?"&lt;/span&gt;

            &lt;span class="c1"&gt;// Positive overflow check:&lt;/span&gt;
            &lt;span class="c1"&gt;// 1. If `reversed_num` is already greater than `INT_MAX / 10`,&lt;/span&gt;
            &lt;span class="c1"&gt;//    multiplying by 10 will *definitely* overflow.&lt;/span&gt;
            &lt;span class="c1"&gt;// 2. If `reversed_num` is exactly `INT_MAX / 10`,&lt;/span&gt;
            &lt;span class="c1"&gt;//    adding `digit` will cause overflow IF `digit` is greater than 7.&lt;/span&gt;
            &lt;span class="c1"&gt;//    (Because INT_MAX = 2,147,483,647, so the last digit is 7).&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Overflow detected, return 0&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// Negative overflow check:&lt;/span&gt;
            &lt;span class="c1"&gt;// 1. If `reversed_num` is already less than `INT_MIN / 10`,&lt;/span&gt;
            &lt;span class="c1"&gt;//    multiplying by 10 will *definitely* underflow.&lt;/span&gt;
            &lt;span class="c1"&gt;// 2. If `reversed_num` is exactly `INT_MIN / 10`,&lt;/span&gt;
            &lt;span class="c1"&gt;//    adding `digit` will cause underflow IF `digit` is less than -8.&lt;/span&gt;
            &lt;span class="c1"&gt;//    (Because INT_MIN = -2,147,483,648, so the last digit is -8).&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Underflow detected, return 0&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// If no overflow, safely build the reversed number&lt;/span&gt;
            &lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;reversed_num&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Remove the last digit from x&lt;/span&gt;
            &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;/=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// All digits processed, return the final reversed number&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;reversed_num&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  ⏱️ Time &amp;amp; Space Complexity Analysis
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Time Complexity: O(log |x|)
&lt;/h3&gt;

&lt;p&gt;Why O(log |x|)?&lt;br&gt;
Because in each iteration of our &lt;code&gt;while&lt;/code&gt; loop, we're effectively removing one digit from &lt;code&gt;x&lt;/code&gt; (by dividing &lt;code&gt;x&lt;/code&gt; by 10). The number of digits in an integer &lt;code&gt;x&lt;/code&gt; is proportional to &lt;code&gt;log10 |x|&lt;/code&gt;. For a 32-bit integer, the maximum number of digits is around 10 (since &lt;code&gt;2^31 - 1&lt;/code&gt; is roughly &lt;code&gt;2 * 10^9&lt;/code&gt;). So, even for the largest possible &lt;code&gt;x&lt;/code&gt;, the loop runs a very small, constant number of times. It's incredibly efficient!&lt;/p&gt;

&lt;h3&gt;
  
  
  Space Complexity: O(1)
&lt;/h3&gt;

&lt;p&gt;We are only using a few extra variables (&lt;code&gt;reversed_num&lt;/code&gt;, &lt;code&gt;digit&lt;/code&gt;, etc.) whose memory usage does not change with the input size &lt;code&gt;x&lt;/code&gt;. Therefore, the space complexity is constant.&lt;/p&gt;

&lt;h2&gt;
  
  
  🎯 Key Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Digit Manipulation Power Duo&lt;/strong&gt;: Remember &lt;code&gt;num % 10&lt;/code&gt; to get the last digit and &lt;code&gt;num / 10&lt;/code&gt; to remove it. They are fundamental for many integer-based problems.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;The Dreaded Overflow&lt;/strong&gt;: Always be mindful of integer limits, especially in problems specifying fixed-size types (like 32-bit integers).&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Proactive Overflow Checks&lt;/strong&gt;: The golden rule is to check for potential overflow &lt;em&gt;before&lt;/em&gt; performing the operation that might cause it. Don't wait for your program to crash!&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Building Numbers&lt;/strong&gt;: The pattern &lt;code&gt;result = result * 10 + digit&lt;/code&gt; is a common and powerful technique for constructing numbers from their digits.&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Edge Cases Matter&lt;/strong&gt;: Think about negative numbers and numbers ending in zero (like &lt;code&gt;120&lt;/code&gt; becoming &lt;code&gt;21&lt;/code&gt;). Our solution handles these gracefully!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This problem is a fantastic way to solidify your understanding of basic arithmetic operations and introduce you to the critical concept of overflow handling in programming. Keep practicing, and you'll be a LeetCode master in no time!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Author:&lt;/strong&gt; Vansh2710&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Published:&lt;/strong&gt; 2026-04-24 00:33:03&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>LeetCode Solution: 7. Reverse Integer</title>
      <dc:creator>Vansh Aggarwal</dc:creator>
      <pubDate>Thu, 23 Apr 2026 18:54:40 +0000</pubDate>
      <link>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-12en</link>
      <guid>https://dev.to/vansh_aggarwal_5fb2fff667/leetcode-solution-7-reverse-integer-12en</guid>
      <description>&lt;h1&gt;
  
  
  Reversing Integers: Tackling LeetCode Problem 7 with Confidence!
&lt;/h1&gt;

&lt;p&gt;Hey there, future coding rockstars! 👋 Vansh here, ready to demystify another classic LeetCode problem that might seem simple on the surface but hides a clever trick: &lt;strong&gt;Problem 7: Reverse Integer&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Don't let the "easy" tag fool you; this problem is a fantastic way to sharpen your understanding of integer manipulation and, more importantly, &lt;strong&gt;handle those pesky edge cases like a pro!&lt;/strong&gt; Let's dive in!&lt;/p&gt;




&lt;h2&gt;
  
  
  The Challenge: What's the Goal?
&lt;/h2&gt;

&lt;p&gt;Imagine you have a number, say &lt;code&gt;123&lt;/code&gt;. Your mission, should you choose to accept it, is to reverse its digits to get &lt;code&gt;321&lt;/code&gt;. Sounds straightforward, right? But there's a catch (or two!):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Signed 32-bit integer:&lt;/strong&gt; We're dealing with numbers that can be positive or negative, and they live within a specific computer memory limit: &lt;code&gt;[-2^31, 2^31 - 1]&lt;/code&gt;.

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Minimum:&lt;/strong&gt; -2,147,483,648&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Maximum:&lt;/strong&gt; 2,147,483,647&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Overflow Protection:&lt;/strong&gt; If reversing the number makes it &lt;em&gt;too big&lt;/em&gt; (or &lt;em&gt;too small&lt;/em&gt;) to fit within this 32-bit range, we &lt;em&gt;must&lt;/em&gt; return &lt;code&gt;0&lt;/code&gt;. This is the sneaky part!&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;No 64-bit integers:&lt;/strong&gt; We can't just convert to a larger data type to avoid overflow during intermediate steps. We have to be smart with our 32-bit integers throughout.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's look at a few examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;Example 1:&lt;/strong&gt; &lt;code&gt;x = 123&lt;/code&gt; -&amp;gt; &lt;code&gt;Output: 321&lt;/code&gt; (Simple positive)&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Example 2:&lt;/strong&gt; &lt;code&gt;x = -123&lt;/code&gt; -&amp;gt; &lt;code&gt;Output: -321&lt;/code&gt; (Simple negative, sign should be preserved)&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Example 3:&lt;/strong&gt; &lt;code&gt;x = 120&lt;/code&gt; -&amp;gt; &lt;code&gt;Output: 21&lt;/code&gt; (Trailing zeros disappear in the reversal)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;See? It's not just flipping digits; it's about handling signs and staying within bounds!&lt;/p&gt;




&lt;h2&gt;
  
  
  The "Aha!" Moment: How Do We Even Reverse Digits?
&lt;/h2&gt;

&lt;p&gt;Before we jump to the overflow puzzle, let's figure out how to reverse digits of an integer. Think about how you'd do it manually:&lt;/p&gt;

&lt;p&gt;To get the &lt;em&gt;last digit&lt;/em&gt; of a number, we can use the &lt;strong&gt;modulo operator (&lt;code&gt;%&lt;/code&gt;)&lt;/strong&gt; with &lt;code&gt;10&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;123 % 10&lt;/code&gt; gives &lt;code&gt;3&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;12 % 10&lt;/code&gt; gives &lt;code&gt;2&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;1 % 10&lt;/code&gt; gives &lt;code&gt;1&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To &lt;em&gt;remove the last digit&lt;/em&gt; from a number, we can use &lt;strong&gt;integer division (&lt;code&gt;/&lt;/code&gt;)&lt;/strong&gt; by &lt;code&gt;10&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;123 / 10&lt;/code&gt; gives &lt;code&gt;12&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;12 / 10&lt;/code&gt; gives &lt;code&gt;1&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;1 / 10&lt;/code&gt; gives &lt;code&gt;0&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, how do we &lt;em&gt;build&lt;/em&gt; the reversed number? We start with &lt;code&gt;0&lt;/code&gt; and, for each digit we extract, we:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Multiply our current &lt;code&gt;reversed_number&lt;/code&gt; by &lt;code&gt;10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; Add the new &lt;code&gt;digit&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's trace &lt;code&gt;x = 123&lt;/code&gt;:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Step&lt;/th&gt;
&lt;th&gt;
&lt;code&gt;x&lt;/code&gt; (original)&lt;/th&gt;
&lt;th&gt;
&lt;code&gt;digit&lt;/code&gt; (&lt;code&gt;x % 10&lt;/code&gt;)&lt;/th&gt;
&lt;th&gt;
&lt;code&gt;reversedNum&lt;/code&gt; (&lt;code&gt;reversedNum * 10 + digit&lt;/code&gt;)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Start&lt;/td&gt;
&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;-&lt;/td&gt;
&lt;td&gt;&lt;code&gt;0&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;3&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;0 * 10 + 3 = 3&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;&lt;code&gt;12&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;2&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;3 * 10 + 2 = 32&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;&lt;code&gt;1&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;1&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;32 * 10 + 1 = 321&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;End&lt;/td&gt;
&lt;td&gt;&lt;code&gt;0&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;-&lt;/td&gt;
&lt;td&gt;&lt;code&gt;321&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;This iterative process, using modulo and division within a &lt;code&gt;while&lt;/code&gt; loop (which continues as long as &lt;code&gt;x&lt;/code&gt; is not &lt;code&gt;0&lt;/code&gt;), is the core intuition!&lt;/p&gt;




&lt;h2&gt;
  
  
  The Smart Approach: Handling Overflow!
&lt;/h2&gt;

&lt;p&gt;The simple digit-reversal logic works perfectly until we hit the 32-bit integer limits. The trick is to check for potential overflow &lt;em&gt;before&lt;/em&gt; we perform the operation that might cause it.&lt;/p&gt;

&lt;p&gt;Imagine &lt;code&gt;reversedNum&lt;/code&gt; is currently &lt;code&gt;214748364&lt;/code&gt;. If the next &lt;code&gt;digit&lt;/code&gt; is &lt;code&gt;7&lt;/code&gt;, &lt;code&gt;214748364 * 10 + 7&lt;/code&gt; would be &lt;code&gt;2147483647&lt;/code&gt;, which is exactly &lt;code&gt;INT_MAX&lt;/code&gt; (the maximum 32-bit integer). Perfect!&lt;/p&gt;

&lt;p&gt;But what if the next &lt;code&gt;digit&lt;/code&gt; was &lt;code&gt;8&lt;/code&gt;? &lt;code&gt;214748364 * 10 + 8&lt;/code&gt; would be &lt;code&gt;2147483648&lt;/code&gt;, which is &lt;code&gt;INT_MAX + 1&lt;/code&gt;! This is an overflow!&lt;/p&gt;

&lt;p&gt;So, we need a check:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;For Positive Overflow:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;reversedNum&lt;/code&gt; is already greater than &lt;code&gt;INT_MAX / 10&lt;/code&gt;, multiplying it by &lt;code&gt;10&lt;/code&gt; will &lt;em&gt;definitely&lt;/em&gt; overflow.&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;reversedNum&lt;/code&gt; is &lt;em&gt;equal&lt;/em&gt; to &lt;code&gt;INT_MAX / 10&lt;/code&gt;, we need to check the &lt;code&gt;digit&lt;/code&gt;. If &lt;code&gt;digit&lt;/code&gt; is greater than &lt;code&gt;7&lt;/code&gt;, it will cause an overflow. (Since &lt;code&gt;INT_MAX&lt;/code&gt; ends in 7: &lt;code&gt;2,147,483,647&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;For Negative Overflow:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  If &lt;code&gt;reversedNum&lt;/code&gt; is already less than &lt;code&gt;INT_MIN / 10&lt;/code&gt;, multiplying it by &lt;code&gt;10&lt;/code&gt; will &lt;em&gt;definitely&lt;/em&gt; overflow (become too negative).&lt;/li&gt;
&lt;li&gt;  If &lt;code&gt;reversedNum&lt;/code&gt; is &lt;em&gt;equal&lt;/em&gt; to &lt;code&gt;INT_MIN / 10&lt;/code&gt;, we need to check the &lt;code&gt;digit&lt;/code&gt;. If &lt;code&gt;digit&lt;/code&gt; is less than &lt;code&gt;-8&lt;/code&gt;, it will cause an overflow. (Since &lt;code&gt;INT_MIN&lt;/code&gt; ends in 8: &lt;code&gt;-2,147,483,648&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;These checks &lt;em&gt;must&lt;/em&gt; happen &lt;em&gt;before&lt;/em&gt; the line &lt;code&gt;reversedNum = reversedNum * 10 + digit;&lt;/code&gt;. If an overflow is detected, we immediately return &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Code (C++)
&lt;/h2&gt;

&lt;p&gt;Let's put it all together into a clean, working solution. We'll use &lt;code&gt;INT_MAX&lt;/code&gt; and &lt;code&gt;INT_MIN&lt;/code&gt; constants available in &lt;code&gt;&amp;lt;limits.h&amp;gt;&lt;/code&gt; for the maximum and minimum values of a 32-bit integer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;limits.h&amp;gt;&lt;/span&gt;&lt;span class="c1"&gt; // Required for INT_MAX and INT_MIN&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Solution&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// This will store our reversed number&lt;/span&gt;

        &lt;span class="c1"&gt;// Loop continues as long as there are digits left in x&lt;/span&gt;
        &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Step 1: Extract the last digit of x&lt;/span&gt;
            &lt;span class="c1"&gt;// For positive x, x % 10 gives the last digit (e.g., 123 % 10 = 3)&lt;/span&gt;
            &lt;span class="c1"&gt;// For negative x, x % 10 gives the last digit (e.g., -123 % 10 = -3)&lt;/span&gt;
            &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Step 2: Critical Overflow Check BEFORE updating reversedNum&lt;/span&gt;
            &lt;span class="c1"&gt;// Check for potential positive overflow&lt;/span&gt;
            &lt;span class="c1"&gt;// If reversedNum is already too large (e.g., &amp;gt; INT_MAX / 10)&lt;/span&gt;
            &lt;span class="c1"&gt;// OR if reversedNum is exactly INT_MAX / 10 AND the next digit would push it over (digit &amp;gt; 7 for INT_MAX = ...7)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;INT_MAX&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Overflow detected, return 0 as per problem statement&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// Check for potential negative overflow&lt;/span&gt;
            &lt;span class="c1"&gt;// If reversedNum is already too small (e.g., &amp;lt; INT_MIN / 10)&lt;/span&gt;
            &lt;span class="c1"&gt;// OR if reversedNum is exactly INT_MIN / 10 AND the next digit would push it over (digit &amp;lt; -8 for INT_MIN = ...8)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;INT_MIN&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// Overflow detected, return 0&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="c1"&gt;// Step 3: Build the reversed number&lt;/span&gt;
            &lt;span class="c1"&gt;// Multiply current reversedNum by 10 to shift digits left, then add the new digit&lt;/span&gt;
            &lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;reversedNum&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;digit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="c1"&gt;// Step 4: Remove the last digit from x&lt;/span&gt;
            &lt;span class="c1"&gt;// Integer division by 10 truncates the last digit&lt;/span&gt;
            &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;/=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="c1"&gt;// Once x becomes 0, all digits have been processed, return the final reversed number&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;reversedNum&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Time and Space Complexity Analysis
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Time Complexity: O(log |x|)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The number of iterations in our &lt;code&gt;while&lt;/code&gt; loop is proportional to the number of digits in the input integer &lt;code&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  Since &lt;code&gt;x&lt;/code&gt; is a 32-bit integer, it has at most 10 digits (e.g., &lt;code&gt;2,147,483,647&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  Each iteration involves a constant number of operations (modulo, division, multiplication, addition, comparisons).&lt;/li&gt;
&lt;li&gt;  Therefore, the time complexity is logarithmic with respect to the absolute value of &lt;code&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Space Complexity: O(1)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  We are only using a few fixed-size integer variables (&lt;code&gt;x&lt;/code&gt;, &lt;code&gt;reversedNum&lt;/code&gt;, &lt;code&gt;digit&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;  The amount of memory used does not grow with the input size.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;




&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Digit Manipulation:&lt;/strong&gt; The core pattern of &lt;code&gt;num % 10&lt;/code&gt; for getting the last digit and &lt;code&gt;num / 10&lt;/code&gt; for removing it is fundamental for many integer-based problems.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Overflow Awareness:&lt;/strong&gt; This problem is a prime example of why you need to be mindful of integer limits. Don't assume numbers will always fit!&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Pre-computation Checks:&lt;/strong&gt; The crucial lesson here is to check for overflow &lt;em&gt;before&lt;/em&gt; performing the operation that might cause it. This often involves checking against &lt;code&gt;INT_MAX / 10&lt;/code&gt; or &lt;code&gt;INT_MIN / 10&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt; &lt;strong&gt;Edge Cases:&lt;/strong&gt; Remember to consider &lt;code&gt;0&lt;/code&gt;, single-digit numbers, and the maximum/minimum possible integer values as test cases.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This problem is a fantastic stepping stone in your LeetCode journey. It teaches you practical skills for dealing with data types and their limitations. Keep practicing, and you'll be solving even tougher challenges in no time! Happy coding!&lt;/p&gt;




&lt;p&gt;Authored by Vansh2710 | Published: 2026-04-24 00:24:13&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>dsa</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
