<?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: Subhradeep Saha</title>
    <description>The latest articles on DEV Community by Subhradeep Saha (@subhradeep__saha).</description>
    <link>https://dev.to/subhradeep__saha</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%2F1467751%2F00738ee5-828f-4060-b44e-492491bc2415.png</url>
      <title>DEV Community: Subhradeep Saha</title>
      <link>https://dev.to/subhradeep__saha</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/subhradeep__saha"/>
    <language>en</language>
    <item>
      <title>Solving a Leetcode problem daily — Day 12 | 347. Top K frequent elements</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Sun, 19 May 2024 04:21:39 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-12-347-top-k-frequent-elements-2i7h</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-12-347-top-k-frequent-elements-2i7h</guid>
      <description>&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-12-347-top-k-frequent-elements-63afa6f681f3" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://res.cloudinary.com/practicaldev/image/fetch/s--Va-0SR2A--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/resize:fit:640/1%2ANkaZKw1Cc_4quLqoyfAcnw.jpeg" height="427" class="m-0" width="640"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-12-347-top-k-frequent-elements-63afa6f681f3" rel="noopener noreferrer" class="c-link"&gt;
          Solving a Leetcode problem daily — Day 12 | 347. Top K frequent elements | by Subhradeep Saha | May, 2024 | Dev Genius
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          A detailed blog on how to use min heap for solving Leetcode’s 347 Top K frequent elements problem.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://res.cloudinary.com/practicaldev/image/fetch/s--607eFk1m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/resize:fill:256:256/1%2ACvejhRq3NYsivxILYXEdfA.jpeg" width="128" height="128"&gt;
        blog.devgenius.io
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;





&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Here is the Leetcode problem link —&lt;/em&gt; &lt;a href="https://leetcode.com/problems/top-k-frequent-elements/"&gt;&lt;em&gt;347. Top K frequent elements&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h1&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Given an integer array &lt;code&gt;nums&lt;/code&gt; and an integer &lt;code&gt;k&lt;/code&gt;, return &lt;em&gt;the&lt;/em&gt; &lt;code&gt;k&lt;/code&gt; &lt;em&gt;most frequent elements&lt;/em&gt;. You may return the answer in &lt;strong&gt;any order&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&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="nl"&gt;Input:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&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;1&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;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&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="n"&gt;k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&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;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example 2:&lt;/strong&gt;&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="nl"&gt;Input:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&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="n"&gt;k&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;Output&lt;/span&gt;&lt;span class="o"&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;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Constraints:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;1 &amp;lt;= nums.length &amp;lt;= 10^5&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;-10^4 &amp;lt;= nums[i] &amp;lt;= 10^4&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;k&lt;/code&gt; is in the range &lt;code&gt;[1, the number of unique elements in the array]&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is &lt;strong&gt;guaranteed&lt;/strong&gt; that the answer is &lt;strong&gt;unique&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;High Level Approach&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;The goal is to determine the frequency of each element in the input array and return the top k elements with the highest frequencies.&lt;/p&gt;

&lt;p&gt;First, we store the frequency of each element in a map. Next, we use a min-heap to store the &lt;code&gt;{frequency, element}&lt;/code&gt; pairs from the map. We then iterate over each entry in the map:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If the heap size is less than k, we create a &lt;code&gt;{frequency, element}&lt;/code&gt; pair and push it to the heap.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the heap size is ≥ k, and the frequency of the element at the top of the heap is less than the current element’s frequency, we remove the lower frequency element and insert the higher frequency element into the heap.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The top of the min-heap will always contain the element with the lowest frequency among those in the heap, making it safe to remove when a higher frequency element is encountered. This ensures that, in the end, the heap contains the top k elements with the highest frequencies, which can then be returned as the answer.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Code Implementation in C++&lt;/strong&gt;
&lt;/h1&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="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;&lt;/span&gt; &lt;span class="n"&gt;topKFrequent&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="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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;unordered_map&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="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;count&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="o"&gt;&amp;amp;&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;nums&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;]&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="n"&gt;priority_queue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;pair&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="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&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;pair&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="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
&lt;span class="n"&gt;greater&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;pair&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="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;pq&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="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&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;pq&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;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;it&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="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="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;top&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="n"&gt;first&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
                    &lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;it&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="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;}&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="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;ans&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;top&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="n"&gt;second&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;pq&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pop&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;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;h1&gt;
  
  
  &lt;strong&gt;Detailed Code Breakdown:&lt;/strong&gt;
&lt;/h1&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Frequency Counting:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We create an unordered_map named &lt;code&gt;count&lt;/code&gt;. This map will store each element in the array &lt;code&gt;nums&lt;/code&gt; as the key and its frequency (the number of times it appears) as the value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We iterate through the &lt;code&gt;nums&lt;/code&gt; array using a range-based for loop, incrementing the corresponding element's count in the &lt;code&gt;count&lt;/code&gt; map.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Priority Queue with Custom Comparison:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We declare a &lt;code&gt;priority_queue&lt;/code&gt; named &lt;code&gt;pq&lt;/code&gt;. This queue will hold pairs of &lt;code&gt;(frequency, element)&lt;/code&gt; values.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;greater&amp;lt;pair&amp;lt;int, int&amp;gt;&amp;gt;&lt;/code&gt; comparison function ensures the priority queue prioritizes elements with &lt;strong&gt;lower&lt;/strong&gt; frequencies which is being stored as the first element of the pair (lower frequency value will be at the top of the queue).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Populating the Priority Queue:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We iterate through the &lt;code&gt;count&lt;/code&gt; map using a range-based for loop.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the &lt;code&gt;pq&lt;/code&gt; size is less than &lt;code&gt;k&lt;/code&gt; (we haven't reached the desired number of elements yet), we directly add the &lt;code&gt;(frequency, element)&lt;/code&gt; pair to the queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the &lt;code&gt;pq&lt;/code&gt; is already full and the current element's frequency is higher than the lowest frequency element in the queue:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;=&amp;gt; We remove the element with the lowest frequency using &lt;code&gt;pq.pop()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;=&amp;gt; We add the current element with its higher frequency to the queue using &lt;code&gt;pq.push()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Extracting Frequent Elements:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We create a vector named &lt;code&gt;ans&lt;/code&gt; to store the final result (the &lt;code&gt;k&lt;/code&gt; most frequent elements).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We iterate through the &lt;code&gt;pq&lt;/code&gt; while it's not empty. For each iteration:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;=&amp;gt; We extract the element (the second value in the pair) from the priority queue using &lt;code&gt;pq.top().second&lt;/code&gt; and add it to the &lt;code&gt;ans&lt;/code&gt; vector.&lt;/p&gt;

&lt;p&gt;=&amp;gt; We remove the top from the queue using &lt;code&gt;pq.pop()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Returning the Result:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The function returns the &lt;code&gt;ans&lt;/code&gt; vector, which contains the &lt;code&gt;k&lt;/code&gt; most frequent elements in the array.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Code Dry Run with Test Case:&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Let’s consider the test case &lt;code&gt;nums = [1,1,1,2,2,3], k = 2&lt;/code&gt;:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Frequency Counting:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The counter map is built as: &lt;code&gt;count = {1: 3, 2: 2, 3: 1}&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Priority Queue Population:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Iteration 1: Adding (3, 1)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkco0iykrofgdw7mxovl9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkco0iykrofgdw7mxovl9.png" alt="Image description" width="192" height="237"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Element: 1 (frequency: 3)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since the heap is initially empty (&lt;code&gt;pq.size() = 0 &amp;lt; k&lt;/code&gt; is true where k = 2), we directly add the &lt;code&gt;(frequency, element)&lt;/code&gt; pair, which is &lt;code&gt;(3, 1)&lt;/code&gt;, to the priority queue.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyuwd63gt9qs7z6m2engm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyuwd63gt9qs7z6m2engm.png" alt="Image description" width="283" height="341"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 2: Adding (2, 2)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd82a98lpqoj1ozsadyvi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd82a98lpqoj1ozsadyvi.png" alt="Image description" width="192" height="237"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Element: 2 (frequency: 2)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The queue now has one element, and we need to consider two elements (&lt;code&gt;pq.size() &amp;lt; k&lt;/code&gt; is still true).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The new element (2) has a frequency of 2, which is &lt;strong&gt;higher&lt;/strong&gt; than the current lowest frequency (3) in the queue. This means element 2 appears less frequently than element 1.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since the priority queue prioritizes lower frequencies, the new element (2, 2) is added directly to the heap.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Heap State:&lt;/strong&gt; The heap now becomes &lt;code&gt;[(2, 2), (3, 1)]&lt;/code&gt;. The element (2, 2) remains at the root because it has the lowest frequency(2)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmbn3l8b3d27ydjhask19.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmbn3l8b3d27ydjhask19.png" alt="Image description" width="283" height="341"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 3: Adding (1, 3)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgvivsoto04fh158hfooa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgvivsoto04fh158hfooa.png" alt="Image description" width="192" height="237"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Element: 3 (frequency: 1)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The queue now has two elements, and &lt;code&gt;k&lt;/code&gt; is still 2.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The new element (3) has a frequency of 1, which is not greater than the frequency(2) of the heap’s top element(2).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;So we don't modify the queue and continue, ending the iteration over the counter map.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Heap State:&lt;/strong&gt; The heap remains unchanged: &lt;code&gt;[(2, 2), (3, 1)]&lt;/code&gt;. The element (3, 1) stays at the root as it maintains the lowest frequency.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Extracting Frequent Elements:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwo7shrv0eq1qi5ai3nj0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwo7shrv0eq1qi5ai3nj0.png" alt="Image description" width="192" height="237"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Heap state: &lt;code&gt;[(2, 2), (3, 1)]&lt;/code&gt; — so we first push 2 to the ans vector&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;pop (&lt;code&gt;2, 2)&lt;/code&gt; from the heap&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft4xwfxd5w0dhecjogms4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft4xwfxd5w0dhecjogms4.png" alt="Image description" width="192" height="284"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;3. get the heap’s top element which is 1 and push it to the ans vector.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkoa1vgb86w3w0cg5ggos.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkoa1vgb86w3w0cg5ggos.png" alt="Image description" width="192" height="237"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;4. pop the top element from the heap&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjqtp3ir4uxsjgdl7evf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjqtp3ir4uxsjgdl7evf.png" alt="Image description" width="192" height="281"&gt;&lt;/a&gt;&lt;br&gt;
5. since the heap is empty now:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5r96fgldnfvx0s4jjht4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5r96fgldnfvx0s4jjht4.png" alt="Image description" width="192" height="237"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;the while loop is terminated and &lt;code&gt;ans = {2, 1}&lt;/code&gt; is returned as the final output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: the order of elements in the output doesn’t matter as mentioned in the problem.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Time and Space Complexity Analysis&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;The time and space complexity of the provided solution for finding the k most frequent elements can be analyzed as follows:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Time Complexity:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;O(n log k):&lt;/strong&gt; This is the dominant factor in the overall time complexity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterating through the array:&lt;/strong&gt; We iterate through the input array &lt;code&gt;nums&lt;/code&gt; using a for loop. In the worst case, this loop iterates &lt;code&gt;n&lt;/code&gt; times (where &lt;code&gt;n&lt;/code&gt; is the number of elements in the array).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Priority Queue Operations:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Adding elements to the priority queue (&lt;code&gt;pq.push()&lt;/code&gt;): The time complexity of adding an element to a min-heap is typically logarithmic, around O(log k) in most implementations. In our case, we potentially add elements up to &lt;code&gt;k&lt;/code&gt; times (depending on the number of unique elements and their frequencies).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Removing elements from the priority queue (&lt;code&gt;pq.pop()&lt;/code&gt;): Similar to adding, removing an element from a min-heap is also O(log k). We might perform this operation up to &lt;code&gt;k&lt;/code&gt; times during the population stage.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since the priority queue operations (&lt;code&gt;push&lt;/code&gt; and &lt;code&gt;pop&lt;/code&gt;) involve logarithmic time complexity and are potentially repeated up to &lt;code&gt;k&lt;/code&gt; times, the overall time complexity is dominated by O(n log k).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;&lt;strong&gt;O(n):&lt;/strong&gt; This is primarily due to the usage of the hash map &lt;code&gt;count&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The hash map &lt;code&gt;count&lt;/code&gt; stores each element in the array as the key and its frequency as the value. In the worst case, the hash map can potentially store all unique elements from the input array, leading to a space complexity of O(n).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The priority queue &lt;code&gt;pq&lt;/code&gt; itself stores a maximum of &lt;code&gt;k&lt;/code&gt; elements (the &lt;code&gt;k&lt;/code&gt; most frequent elements). While this contributes to space usage, it's typically considered negligible compared to the potentially larger &lt;code&gt;count&lt;/code&gt; hash map, especially when &lt;code&gt;k&lt;/code&gt; is a relatively small value compared to &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Customer Analysis and Recommendation Systems:&lt;/strong&gt; Online retail stores analyze customer purchase history to identify frequently bought items together. This information helps recommend complementary products, personalize promotions, and optimize product placement for better sales (e.g., suggesting frequently purchased groceries alongside main dishes).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Social Media and Trending Topics:&lt;/strong&gt; Social media platforms like Twitter utilize algorithms to identify trending topics and hashtags in real-time. By analyzing the frequency of mentions and retweets, they can surface trending conversations and keep users engaged with the latest discussions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Network Security and Intrusion Detection Systems (IDS):&lt;/strong&gt; Network security systems monitor network traffic for suspicious activity. Identifying frequently occurring IP addresses attempting to access unauthorized resources or ports can be a red flag for potential attacks. By finding these frequent occurrences, security systems can trigger alerts and take preventive measures.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;By employing a hash map for frequency counting and a priority queue with a custom comparison function, we efficiently identified the &lt;code&gt;k&lt;/code&gt; most frequent elements in an array. This approach highlights the power of data structures for solving common data analysis problems in C++.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;References&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Cover photo by &lt;a href="https://unsplash.com/@waldemarbrandt67w?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Waldemar&lt;/a&gt; on &lt;a href="https://unsplash.com/photos/red-1-to-20-numbered-lockers-zty84NY_FOY?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.ibm.com/docs/SSNN4U_1.0.0/c_fan_rpt_customer_behavior_db.html"&gt;https://www.ibm.com/docs/SSNN4U_1.0.0/c_fan_rpt_customer_behavior_db.html&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.technologyreview.com/author/mit-technology-review-insights/"&gt;https://www.technologyreview.com/author/mit-technology-review-insights/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.fortinet.com/resources/cyberglossary/intrusion-detection-system"&gt;https://www.fortinet.com/resources/cyberglossary/intrusion-detection-system&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Diagrams are made using Canva&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Thank you for reading throughout! If you found this post insightful, please show your appreciation by liking this post and sharing it. Don’t forget to follow me for more engaging content like this. Your feedback is valuable, so please feel free to comment or reach out to me with any thoughts or suggestions.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>topkfrequentelements</category>
      <category>heap</category>
      <category>347</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 11 | Find Minimum in Rotated Sorted Array</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Wed, 15 May 2024 03:50:13 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-11-find-minimum-in-rotated-sorted-array-3f7g</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-11-find-minimum-in-rotated-sorted-array-3f7g</guid>
      <description>&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-11-find-minimum-in-rotated-sorted-array-86cea074a138" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://res.cloudinary.com/practicaldev/image/fetch/s--yhT72vqk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/resize:fit:640/1%2Ab1U1YSMYHzBFyK4ypjZdrg.jpeg" height="426" class="m-0" width="640"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-11-find-minimum-in-rotated-sorted-array-86cea074a138" rel="noopener noreferrer" class="c-link"&gt;
          Solving a Leetcode problem daily — Day 11 | Find Minimum in Rotated Sorted Array | by Subhradeep Saha | May, 2024 | Dev Genius
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          A detailed guide on how to solve Leetcode’s 153. Find minimum element in rotated sorted array problem using binary search.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://res.cloudinary.com/practicaldev/image/fetch/s--607eFk1m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/resize:fill:256:256/1%2ACvejhRq3NYsivxILYXEdfA.jpeg" width="128" height="128"&gt;
        blog.devgenius.io
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;





&lt;p&gt;&lt;em&gt;Here is the Leetcode problem —&lt;/em&gt;&lt;a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/"&gt;&lt;em&gt;153. Find Minimum in Rotated Sorted Array&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h1&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Suppose an array of length &lt;code&gt;n&lt;/code&gt; sorted in ascending order is &lt;strong&gt;rotated&lt;/strong&gt; between &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;n&lt;/code&gt; times. For example, the array &lt;code&gt;nums = [0,1,2,4,5,6,7]&lt;/code&gt; might become:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;[4,5,6,7,0,1,2]&lt;/code&gt; if it was rotated &lt;code&gt;4&lt;/code&gt; times.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;[0,1,2,4,5,6,7]&lt;/code&gt; if it was rotated &lt;code&gt;7&lt;/code&gt; times.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Notice that &lt;strong&gt;rotating&lt;/strong&gt; an array &lt;code&gt;[a[0], a[1], a[2], ..., a[n-1]]&lt;/code&gt; 1 time results in the array &lt;code&gt;[a[n-1], a[0], a[1], a[2], ..., a[n-2]]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Given the sorted rotated array &lt;code&gt;nums&lt;/code&gt; of &lt;strong&gt;unique&lt;/strong&gt; elements, return &lt;em&gt;the minimum element of this array&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;You must write an algorithm that runs in &lt;code&gt;O(log n)&lt;/code&gt;time.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Constraints:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;n == nums.length&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;1 &amp;lt;= n &amp;lt;= 5000&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;-5000 &amp;lt;= nums[i] &amp;lt;= 5000&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;All the integers of &lt;code&gt;nums&lt;/code&gt; are &lt;strong&gt;unique&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;nums&lt;/code&gt; is sorted and rotated between &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;n&lt;/code&gt; times.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&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="n"&gt;Example&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;Input&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&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;4&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;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;Output&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;Explanation&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;The&lt;/span&gt; &lt;span class="n"&gt;original&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt; &lt;span class="n"&gt;was&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;2&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;4&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="n"&gt;rotated&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="n"&gt;times&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;

&lt;span class="n"&gt;Example&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;Input&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&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;6&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="mi"&gt;0&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;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;Output&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;Explanation&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;The&lt;/span&gt; &lt;span class="n"&gt;original&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt; &lt;span class="n"&gt;was&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="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;4&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;6&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="n"&gt;and&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt; &lt;span class="n"&gt;was&lt;/span&gt; &lt;span class="n"&gt;rotated&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="n"&gt;times&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;

&lt;span class="n"&gt;Example&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;Input&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&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;13&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;17&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;11&lt;/span&gt;
&lt;span class="n"&gt;Explanation&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;The&lt;/span&gt; &lt;span class="n"&gt;original&lt;/span&gt; &lt;span class="n"&gt;array&lt;/span&gt; &lt;span class="n"&gt;was&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;13&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;15&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;17&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;and&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt; &lt;span class="n"&gt;was&lt;/span&gt; &lt;span class="n"&gt;rotated&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="n"&gt;times&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;strong&gt;High-Level Approach&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;A direct method involves inspecting each element in the array to identify the minimum, but this would incur a time complexity of &lt;code&gt;O(n)&lt;/code&gt;. However, given that the input array exhibits a sorted-then-rotated characteristic, a more efficient approach could leverage binary search.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;How are we getting the min element?&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If somehow we get the index of the max element in the array, then the immediate next element will be the smallest item of the array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the maximum element is at the end of the array, the while loop won’t check the middle element from within. Hence, we return -1 in this case, signifying that the minimum element is at index &lt;code&gt;-1+1 = 0&lt;/code&gt;, which is the first element.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Now how to identity the max element?&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The rotation creates two distinct sorted halves, one with elements increasing from the start and another with elements decreasing towards the end.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The max value will be the one which is greater than its next number. So we divide the search space into half and check if the middle element is the max or not.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;if its greater than its next number then we return it as the max element&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To further optimize the search space in the next iteration, we can employ a strategy based on the comparison between the middle element and the array’s first element:&lt;/p&gt;

&lt;p&gt;=&amp;gt; if the middle element is greater than the first element, it implies that the maximum value cannot exist in the left half of the array. Therefore, we can update the lower index to be &lt;code&gt;m + 1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;=&amp;gt; conversely, if the middle element is less than the first element, it indicates that the maximum item lies in the lower half. Consequently, we can discard the right half and update the upper index to be &lt;code&gt;m&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;How are we updating the l, h and why?&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In the while loop with the condition &lt;code&gt;l &amp;lt; h&lt;/code&gt;, we’re ensuring that there are at least two items between &lt;code&gt;l&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt;. Given that the middle index, &lt;code&gt;m&lt;/code&gt; moves closer to the value of &lt;code&gt;l&lt;/code&gt; when we divide by 2, we can confidently include the condition &lt;code&gt;nums[m] &amp;gt; nums[m+1]&lt;/code&gt; without concerns about &lt;code&gt;m+1&lt;/code&gt; going beyond the array boundary. This adjustment streamlines the logic and simplifies the implementation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Why do we update &lt;code&gt;l&lt;/code&gt; to &lt;code&gt;m+1&lt;/code&gt; and not another value? It’s because when &lt;code&gt;nums[m] &amp;gt; nums[m+1]&lt;/code&gt;, it indicates that the maximum value is likely between indices &lt;code&gt;l&lt;/code&gt; and &lt;code&gt;m&lt;/code&gt; including both. We don’t set &lt;code&gt;l&lt;/code&gt; to &lt;code&gt;m&lt;/code&gt; because we’ve already evaluated &lt;code&gt;m&lt;/code&gt; and confirmed that it’s not the maximum value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Similarly, when &lt;code&gt;nums[m] &amp;lt; nums[0]&lt;/code&gt;, we ensure that m remains within the scope for the next iteration. This is because, if &lt;code&gt;nums[m-1]&lt;/code&gt; happens to be the maximum value, it will only be identified when compared with its subsequent item which is &lt;code&gt;nums[m]&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Code Implementation in C++&lt;/strong&gt;
&lt;/h1&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;findPeakIdx&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="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;l&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;h&lt;/span&gt; &lt;span class="o"&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;size&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="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;h&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;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;l&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="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;m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;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;m&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;return&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;;&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;nums&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;nums&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="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="k"&gt;return&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="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;findMin&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="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;peakIdx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;findPeakIdx&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="k"&gt;return&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;peakIdx&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;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;strong&gt;Detailed Breakdown of the Code:&lt;/strong&gt;
&lt;/h1&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;findPeakIdx()&lt;/code&gt;:
&lt;/h2&gt;

&lt;p&gt;This function takes a sorted rotated array &lt;code&gt;nums&lt;/code&gt; and returns the index of the element at the peak (the point where the decreasing half starts). It uses binary search to achieve this:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt; represent the left and right indices of the search space, respectively.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The loop continues until &lt;code&gt;l &amp;lt; h&lt;/code&gt; .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is calculated as the middle index.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;nums[m]&lt;/code&gt; is greater than &lt;code&gt;nums[m+1]&lt;/code&gt;, it signifies the peak is at &lt;code&gt;m&lt;/code&gt; (the decreasing half starts after this point).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Otherwise, we need to determine which half holds the minimum element.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;=&amp;gt; If &lt;code&gt;nums[m]&lt;/code&gt; is greater than &lt;code&gt;nums[0]&lt;/code&gt;, the minimum element is likely in the right half (&lt;code&gt;l = m+1&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;=&amp;gt; Else, the minimum element is likely in the left half (&lt;code&gt;h = m&lt;/code&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the while loop doesn’t return any value from within, it implies that the last element is the maximum value in the array. In this case, we return -1 as the peakIdx.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;findMin()&lt;/code&gt;:
&lt;/h2&gt;

&lt;p&gt;This main function calls &lt;code&gt;findPeakIdx&lt;/code&gt; to locate the peak index and then returns the element at the next index (&lt;code&gt;peakIdx+1&lt;/code&gt;).&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Dry Run with a Test Case&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Let’s consider the test case &lt;code&gt;nums = [11, 13, 15, 17]&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;findMin&lt;/code&gt; calls &lt;code&gt;findPeakIdx&lt;/code&gt; passing the input array&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Inside&lt;/strong&gt;&lt;code&gt;findPeakIdx()&lt;/code&gt; :
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Iteration 1(l &amp;lt; h):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;loop starts with &lt;code&gt;l = 0&lt;/code&gt; and &lt;code&gt;h = 3&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;m is calculated to be 1&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;nums[m] = 13&lt;/code&gt; is not &amp;gt; &lt;code&gt;nums[m+1] = 15&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;nums[m] = 13&lt;/code&gt; &amp;gt; &lt;code&gt;nums[0] = 11&lt;/code&gt; so l is updated to be m+1 = 2&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz8d046086qea5jd5ewed.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz8d046086qea5jd5ewed.png" alt="" width="319" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 2(l &amp;lt; h):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;l = 2, h = 3&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;m is calculated to be 2&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;nums[m] = 15 is not &amp;gt; nums[m+1] = 17&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;nums[m] = 15 &amp;gt; nums[0] = 11 so l is updated to be m+1 = 3&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frx780tnsd2nagbb6ec49.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frx780tnsd2nagbb6ec49.png" alt="" width="319" height="185"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 3(l == h):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;l = 3, h = 3&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;since l is not less than h, the while loop terminates and we return -1 from the &lt;code&gt;findPeakIdx()&lt;/code&gt; function&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzzu2np6la8vlxtrimc8h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzzu2np6la8vlxtrimc8h.png" alt="" width="319" height="143"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Inside&lt;/strong&gt;&lt;code&gt;findMin()&lt;/code&gt; :
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;nums[peakIdx + 1]&lt;/code&gt; = &lt;code&gt;nums[-1+1]&lt;/code&gt; = &lt;code&gt;nums[0]&lt;/code&gt; = &lt;code&gt;11&lt;/code&gt; is returned as the main output.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Time and Space Complexity Analysis&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; The &lt;code&gt;findPeakIdx&lt;/code&gt; function employs binary search, halving the search space in each iteration and resulting in a time complexity of &lt;code&gt;O(log n)&lt;/code&gt;, where n is the array’s size. &lt;code&gt;findMin&lt;/code&gt; calls &lt;code&gt;findPeakIdx&lt;/code&gt; once and then performs a constant-time operation to retrieve the minimum element, so the overall time complexity remains &lt;code&gt;O(log n)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; The code uses constant extra space for variables like &lt;code&gt;l&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, and &lt;code&gt;m&lt;/code&gt;. This space complexity is independent of the input size and is considered &lt;code&gt;O(1)&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Circular Buffers:&lt;/strong&gt; Circular buffers are used to store data where new elements are written at the end, and old ones are overwritten if the buffer is full. Finding the minimum element in a circular buffer with a sorted (but rotated) access pattern can be solved using this approach.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Log Analysis:&lt;/strong&gt; Rotated logs might occur when a log file reaches its maximum size and starts overwriting older entries. To identify the most recent log entry (which might be the minimum based on timestamps), this technique can be employed.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;The provided solution leverages binary search to efficiently find the minimum element in a sorted rotated array. This approach achieves a time complexity of &lt;code&gt;O(log n)&lt;/code&gt; while utilizing constant extra space. Understanding the concept of rotated sorted arrays and applying binary search principles allows for efficient solutions in various real-world applications where data exhibits similar characteristics.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;References&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.reddit.com/r/embedded/comments/1bg65qe/use_of_circular_buffer_in_embedded_systems/"&gt;https://www.reddit.com/r/embedded/comments/1bg65qe/use_of_circular_buffer_in_embedded_systems/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.digitalocean.com/community/tutorials/how-to-use-journalctl-to-view-and-manipulate-systemd-logs"&gt;https://www.digitalocean.com/community/tutorials/how-to-use-journalctl-to-view-and-manipulate-systemd-logs&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cover Photo by &lt;a href="https://unsplash.com/@miracleday?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Elena Mozhvilo&lt;/a&gt; on &lt;a href="https://unsplash.com/photos/pink-and-blue-plastic-bottle-on-brown-wooden-table-CwIOnANQW-A?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Diagrams are made using &lt;a href="https://www.canva.com/join/qsx-lqt-tpb"&gt;Canva&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;What next?&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;If you’re intrigued by binary search algorithms, do check out my other posts where I delve into fascinating use cases that are solved using binary search:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-8-sqrtx-4p8p"&gt;Leetcode — 69. Sqrt(x)&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-9-first-bad-version-2dk5"&gt;Leetcode — 278. First Bad Version&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-10-find-first-and-last-position-in-sorted-array-2n3b"&gt;Leetcode — 34. Find first and last position of element in sorted array&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Thank you for reading throughout! If you found this post insightful, please show your appreciation by liking this post and sharing it. Don’t forget to follow me for more engaging content like this. Your feedback is valuable, so please feel free to comment or reach out to me with any thoughts or suggestions.&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>binarysearch</category>
      <category>rotatedsortedarray</category>
      <category>cpp</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 10 | Find first and last position in sorted array</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Sat, 11 May 2024 03:17:37 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-10-find-first-and-last-position-in-sorted-array-2n3b</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-10-find-first-and-last-position-in-sorted-array-2n3b</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-10-find-first-and-last-position-in-sorted-array-0ca712b20f58" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c-2Ckuec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/da:true/resize:fill:88:88/0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-10-find-first-and-last-position-in-sorted-array-0ca712b20f58" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 10 | Find first and last position in sorted array | by Subhradeep Saha | May, 2024 | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 11, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YjpYcCMa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/medium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;p&gt;Here is the Leetcode problem link - &lt;a href="https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/"&gt;https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/&lt;/a&gt;&lt;/p&gt;




&lt;h1&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Given an array of integers &lt;code&gt;nums&lt;/code&gt; sorted in non-decreasing order, find the starting and ending position of a given &lt;code&gt;target&lt;/code&gt; value.&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;target&lt;/code&gt; is not found in the array, return &lt;code&gt;[-1, -1]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You must write an algorithm with &lt;code&gt;O(log n)&lt;/code&gt; runtime complexity.&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="n"&gt;Example&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;Input&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&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="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;8&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="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&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;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;Example&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;Input&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&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="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;8&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="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&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="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;Example&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
&lt;span class="n"&gt;Input&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[],&lt;/span&gt; &lt;span class="n"&gt;target&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;Output&lt;/span&gt;&lt;span class="o"&gt;:&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="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Constraints:&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;0 &amp;lt;= nums.length &amp;lt;= 10^5&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;-10^9 &amp;lt;= nums[i] &amp;lt;= 10^9&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;nums&lt;/code&gt; is a non-decreasing array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;-10^9 &amp;lt;= target &amp;lt;= 10^9&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;High-Level Approach&lt;/strong&gt;
&lt;/h1&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Binary search to the rescue&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The brute force solution entails iterating through each item in the input array to determine the first and last indices of the specified target.&lt;br&gt;&lt;br&gt;
However, since the input is in non-decreasing order, we can leverage binary search to take advantage of this characteristic and significantly reduce the time complexity to a logarithmic scale.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;How are we finding the indices?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The first index corresponds to either the beginning of the array or the position where the previous number is different from the target. Likewise, the last index corresponds to either the end of the array or the position where the next number is different from the target.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ckt6rp8460njylyandl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ckt6rp8460njylyandl.png" alt="Image description" width="800" height="112"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In cases where the &lt;code&gt;target&lt;/code&gt; is not present in the input array, both indices’ positions are returned as -1.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Code Implementation in C++&lt;/strong&gt;
&lt;/h1&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;findIdx&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="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="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="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;firstIdxSearch&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;l&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;h&lt;/span&gt; &lt;span class="o"&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;size&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="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;h&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;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;l&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="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;m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;&amp;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="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="nf"&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;m&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="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;firstIdxSearch&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="c1"&gt;// Find last occurrence&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;m&lt;/span&gt; &lt;span class="o"&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;size&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="o"&gt;||&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;m&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="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="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
          &lt;span class="p"&gt;}&lt;/span&gt;
          &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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;// Find first occurrence&lt;/span&gt;
          &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;||&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;m&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="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="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
          &lt;span class="p"&gt;}&lt;/span&gt;
          &lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&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="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;&lt;/span&gt; &lt;span class="n"&gt;searchRange&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="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="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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;firstIdx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;findIdx&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="nb"&gt;true&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;firstIdx&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="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="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="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;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;firstIdx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;findIdx&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="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;h1&gt;
  
  
  &lt;strong&gt;Breakdown of the Code&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;&lt;code&gt;findIdx&lt;/code&gt; &lt;strong&gt;Function:&lt;/strong&gt; This util function takes three arguments:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;nums&lt;/code&gt;: The sorted array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;target&lt;/code&gt;: The value to search for.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;firstIdxSearch&lt;/code&gt;: A boolean flag indicating whether to find the first or last occurrence of the target.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Binary Search Loop:&lt;/strong&gt; The core logic resides within a &lt;code&gt;while&lt;/code&gt; loop that continues as long as &lt;code&gt;l&lt;/code&gt; (lower bound) is less than or equal to &lt;code&gt;h&lt;/code&gt; (upper bound).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Inside the loop, &lt;code&gt;m&lt;/code&gt; (middle index) is calculated.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The comparison between &lt;code&gt;nums[m]&lt;/code&gt; and &lt;code&gt;target&lt;/code&gt; determines the search direction:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;=&amp;gt; If &lt;code&gt;nums[m] &amp;gt; target&lt;/code&gt;, the target is in the lower half, so we update &lt;code&gt;h&lt;/code&gt; to &lt;code&gt;m-1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;=&amp;gt; If &lt;code&gt;nums[m] &amp;lt; target&lt;/code&gt;, the target is in the upper half, so we update &lt;code&gt;l&lt;/code&gt; to &lt;code&gt;m+1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;=&amp;gt; If &lt;code&gt;nums[m] == target&lt;/code&gt;, we've found a potential occurrence. The logic then diverges based on the &lt;code&gt;firstIdx&lt;/code&gt; flag:&lt;/p&gt;

&lt;p&gt;===&amp;gt; If &lt;code&gt;firstIdxSearch&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt; (finding first occurrence), we check if this is truly the first by looking at &lt;code&gt;nums[m-1]&lt;/code&gt; or is it at the beginning of the array. If not, we need to search in the left half (&lt;code&gt;h = m-1&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;===&amp;gt; Else, we check if this is the last by looking at &lt;code&gt;nums[m+1]&lt;/code&gt; or is it at the end of the array. If not, we need to search in the right half (&lt;code&gt;l = m+1&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Returning the Result:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If the loop completes without finding the target (&lt;code&gt;l&lt;/code&gt; becomes greater than &lt;code&gt;h&lt;/code&gt;), the function returns &lt;code&gt;-1&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Otherwise, the function returns the index (&lt;code&gt;m&lt;/code&gt;) of the found target occurrence, depending on whether it's the first or last based on the &lt;code&gt;firstIdxSearch&lt;/code&gt; flag.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Dry Run with a Test Case&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Let’s perform a dry run on the code using the example &lt;code&gt;nums = [5,7,7,8,8,10]&lt;/code&gt; and &lt;code&gt;target = 8&lt;/code&gt;:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Searching for First Occurrence (firstIdxSearch = true):&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi56pl28c2qs3qczq9dno.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi56pl28c2qs3qczq9dno.png" alt="Image description" width="316" height="168"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Iteration 1:&lt;/strong&gt; &lt;code&gt;l&lt;/code&gt; is set to 0, &lt;code&gt;h&lt;/code&gt; is set to 5, and &lt;code&gt;m&lt;/code&gt; is calculated as 2 (middle element):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgnc1sq6ec686694duhyt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgnc1sq6ec686694duhyt.png" alt="Image description" width="316" height="133"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;nums[m] &amp;lt; target&lt;/code&gt;, we update &lt;code&gt;l = m+1&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 2:&lt;/strong&gt; Updated &lt;code&gt;l = 3, h = 5&lt;/code&gt; and &lt;code&gt;m&lt;/code&gt; is calculated to be 4:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcvci6o1yijk150zgr54n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcvci6o1yijk150zgr54n.png" alt="Image description" width="316" height="133"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, &lt;code&gt;nums[m] == target&lt;/code&gt; and &lt;code&gt;nums[m-1] == target&lt;/code&gt;. So we update &lt;code&gt;h&lt;/code&gt; as &lt;code&gt;m — 1&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fab8n1xqsqd69c9bt29jv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fab8n1xqsqd69c9bt29jv.png" alt="Image description" width="316" height="189"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 3&lt;/strong&gt;: Updated &lt;code&gt;l = 3, h = 3&lt;/code&gt; and &lt;code&gt;m&lt;/code&gt; is calculated to be 3 as well:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fegv4jxi6qn62bvdux0pj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fegv4jxi6qn62bvdux0pj.png" alt="Image description" width="316" height="133"&gt;&lt;/a&gt;&lt;br&gt;
Now, &lt;code&gt;nums[m] == target&lt;/code&gt; and &lt;code&gt;nums[m-1] != target&lt;/code&gt;, so we return m as the &lt;code&gt;firstIdx&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Inside the main searchRange() function&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;After &lt;code&gt;firstIdx&lt;/code&gt; is calculated to be not equal to -1, we proceed to again use the same &lt;code&gt;findIdx()&lt;/code&gt; function to find the &lt;code&gt;lastIdx&lt;/code&gt; of the target.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Searching for Last Occurrence (&lt;/strong&gt;&lt;code&gt;firstIdxSearch&lt;/code&gt; &lt;strong&gt;= false):&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;We call &lt;code&gt;findIdx()&lt;/code&gt; again but now with the boolean &lt;code&gt;firstIdxSearch&lt;/code&gt; set to &lt;code&gt;false&lt;/code&gt; to find the last occurrence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 1&lt;/strong&gt;:&lt;code&gt;l&lt;/code&gt; is set to 0, &lt;code&gt;h&lt;/code&gt; is set to 5, and &lt;code&gt;m&lt;/code&gt; is calculated as 2 (middle element):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdpe0s1sb65qvchpas66t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdpe0s1sb65qvchpas66t.png" alt="Image description" width="316" height="133"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;nums[m] &amp;lt; target&lt;/code&gt;, we update &lt;code&gt;l = m+1&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjy8lk3k7xez3s2y4w7t5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjy8lk3k7xez3s2y4w7t5.png" alt="Image description" width="316" height="168"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 2&lt;/strong&gt;: Updated &lt;code&gt;l = 3, h = 5&lt;/code&gt; and &lt;code&gt;m&lt;/code&gt; is calculated to be 4:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjthcaze5vs5t72snb4rm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjthcaze5vs5t72snb4rm.png" alt="Image description" width="316" height="133"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, &lt;code&gt;nums[m] == target&lt;/code&gt; and &lt;code&gt;nums[m+1] != target&lt;/code&gt;, so we return m as the lastIdx of the target.&lt;/p&gt;

&lt;p&gt;Finally, we return &lt;code&gt;{firstIdx = 3, lastIdx = 4}&lt;/code&gt; from the main function as the answer.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Complexity Analysis&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; &lt;code&gt;O(log n)&lt;/code&gt;. The &lt;code&gt;findIdx()&lt;/code&gt; function divides the search space into half with every iteration leading to a logarithmic time complexity in terms of n(the size of the input array).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; &lt;code&gt;O(1)&lt;/code&gt;. The code utilizes a constant amount of extra space for variables like &lt;code&gt;l&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, and &lt;code&gt;m&lt;/code&gt;, regardless of the array size (&lt;code&gt;n&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Possible Improvements in the code&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;After the first &lt;code&gt;findIdx()&lt;/code&gt; call, we obtain the index where the &lt;code&gt;target&lt;/code&gt; is first found. Subsequently, for the second &lt;code&gt;findIdx()&lt;/code&gt; call aimed at locating the last occurrence of the &lt;code&gt;target&lt;/code&gt;, we can directly start the lower bound &lt;code&gt;l&lt;/code&gt; as the output of the first &lt;code&gt;findIdx()&lt;/code&gt; call instead of starting from 0. This is because we are certain that the target’s last occurrence cannot precede its first occurrence.&lt;/p&gt;

&lt;p&gt;In the above example, when we call the &lt;code&gt;findIdx()&lt;/code&gt; function to locate the last occurrence of the &lt;code&gt;target&lt;/code&gt; (in this case, 8), we can optimize by using the output of the first call. This allows us to start processing directly from &lt;code&gt;l = 3&lt;/code&gt; (instead of &lt;code&gt;l = 0&lt;/code&gt;) for the 2nd &lt;code&gt;findIdx()&lt;/code&gt; function, thereby reducing the number of iterations required in the while loop.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Log File Search and Analysis&lt;/strong&gt;: ystem logs often contain timestamped records of events or errors. These logs can be sorted chronologically. When troubleshooting issues or analyzing system behavior within a specific timeframe (e.g., identifying errors that occurred between 10:00 AM and 11:00 AM), binary search can be used to efficiently locate the relevant log entries within the sorted time range.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Financial Data Analysis and Trend Identification&lt;/strong&gt;: Financial analysts might analyze historical stock prices which are often sorted chronologically. To identify periods where stock prices remained within a specific range (e.g., identifying days when a stock price stayed between $100 and $105), binary search can be applied to efficiently locate the relevant date ranges within the sorted price data.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;This blog post delves into the problem of locating the initial and concluding positions of a target value within a sorted array. We explored the benefits of employing binary search for efficient searching, offer a comprehensive breakdown of the C++ code implementation, evaluated the time and space complexity, and investigated real-world applications of the given problem.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;References&lt;/strong&gt;
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://developers.cloudflare.com/logs/"&gt;https://developers.cloudflare.com/logs/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.quantconnect.com/learning/articles/introduction-to-financial-python"&gt;https://www.quantconnect.com/learning/articles/introduction-to-financial-python&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Diagrams are made using &lt;a href="https://www.canva.com/join/qsx-lqt-tpb"&gt;Canva&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cover Photo by &lt;a href="https://unsplash.com/@markuswinkler?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Markus Winkler&lt;/a&gt; on &lt;a href="https://unsplash.com/photos/round-grey-and-black-magnifying-glass-BvlxNyjnIzg?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  &lt;strong&gt;What next?&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;If you’re intrigued by binary search algorithms, do check out my other posts where I delve into fascinating use cases that are solved using binary search.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-9-first-bad-version-2dk5"&gt;First Bad Version&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-8-sqrtx-4p8p"&gt;Sqrt(x)&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Thank you for reading throughout! If you found this post insightful, please show your appreciation by liking this post and sharing it. Don’t forget to follow me for more engaging content like this. Your feedback is valuable, so please feel free to comment or reach out to me with any thoughts or suggestions.&lt;/p&gt;

&lt;p&gt;Happy reading and happy coding!&lt;/p&gt;

</description>
      <category>34</category>
      <category>binarysearch</category>
      <category>leetcode</category>
      <category>sort</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 9 | First Bad Version</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Thu, 09 May 2024 15:27:54 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-9-first-bad-version-2dk5</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-9-first-bad-version-2dk5</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-9-first-bad-version-e05171496f85" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c-2Ckuec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/da:true/resize:fill:88:88/0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-9-first-bad-version-e05171496f85" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 9 | First Bad Version | by Subhradeep Saha | May, 2024 | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 9, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YjpYcCMa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/medium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;p&gt;Here is the Leetcode problem link — &lt;a href="https://leetcode.com/problems/first-bad-version/description/"&gt;First Bad Version&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Imagine you’re a product manager leading a software development team. During quality checks, you discover a bad version in your product. Since each version builds upon the previous one, any versions released after the bad one will also be faulty.&lt;/p&gt;

&lt;p&gt;The challenge is to identify the first bad version as efficiently as possible. You’re given an array representing versions (&lt;code&gt;[1, 2, ..., n]&lt;/code&gt;) and an API function &lt;code&gt;isBadVersion(version)&lt;/code&gt; that returns &lt;code&gt;true&lt;/code&gt; if the version is bad and &lt;code&gt;false&lt;/code&gt; otherwise. The goal is to write a function that finds the index of the first bad version using the minimum number of API calls.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Input: &lt;code&gt;n = 5&lt;/code&gt;, bad version at index 4&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Output: 4&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;isBadVersion(3)&lt;/code&gt; returns &lt;code&gt;false&lt;/code&gt; (version 3 is good).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;isBadVersion(5)&lt;/code&gt; returns &lt;code&gt;true&lt;/code&gt; (version 5 is bad).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since version 4 is right before the first bad version (version 5), the answer is 4.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Input: &lt;code&gt;n = 1&lt;/code&gt;, bad version at index 0 (only one version)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Output: 1&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Explanation: The single version is bad, so the answer is 1.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Constraints:&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;1 &amp;lt;= bad &amp;lt;= n &amp;lt;= 2^31 - 1&lt;/code&gt; (n is within the range of a 32-bit integer)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;High-Level Approach&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The direct method entails iterating from version &lt;code&gt;1&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;. If a version is good and the subsequent version is bad, we designate the next version as the solution. However, this could lead to calling &lt;code&gt;isBadVersion()&lt;/code&gt; &lt;code&gt;2* (n-1)&lt;/code&gt;times(2 calls for each version from 2 to &lt;code&gt;n-1&lt;/code&gt;and 1 call each for versions 1, n) at worst, potentially becoming inefficient for large &lt;code&gt;n&lt;/code&gt;.&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="c1"&gt;// The API isBadVersion is defined for you.&lt;/span&gt;
&lt;span class="c1"&gt;// bool isBadVersion(int version);&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;firstBadVersion&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="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;x&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;x&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="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;x&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="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;isBadVersion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;isBadVersion&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;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;return&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;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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;n&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;h4&gt;
  
  
  Reduce calls by using some space?
&lt;/h4&gt;

&lt;p&gt;In the direct approach discussed above, it can be clearly seen that for every number from &lt;code&gt;2&lt;/code&gt; to &lt;code&gt;n-1&lt;/code&gt;, the call is made twice:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;x = 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92xw345ajtotom14g83v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92xw345ajtotom14g83v.png" alt="" width="487" height="389"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;x = 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8wwie7f6smrv410ldhht.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8wwie7f6smrv410ldhht.png" alt="" width="487" height="385"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As seen above, there are redundant calls to &lt;code&gt;isBadVersion(2)&lt;/code&gt;. Perhaps we can optimize this by storing the calculated value during the initial run and then utilize the stored value for subsequent calls. This approach reduces the number of calls to just one for each number from &lt;code&gt;1&lt;/code&gt; to &lt;code&gt;n&lt;/code&gt;. However, the total no of calls still remains relatively high if &lt;code&gt;n&lt;/code&gt; is very large.&lt;/p&gt;

&lt;h4&gt;
  
  
  Hint for Binary Search?
&lt;/h4&gt;

&lt;p&gt;Since versions are ordered (1, 2, 3, …), bad versions will always cluster after the first bad version. Binary search allows us to exploit this ordering by repeatedly dividing the search space in half. We strategically pick a ‘middle’ version and use &lt;code&gt;isBadVersion()&lt;/code&gt; for it and its next number. Based on the result, we can efficiently narrow down the search space to locate the first bad version.&lt;/p&gt;

&lt;p&gt;Since with every iteration, we are dividing the search space by half, the number of calls to &lt;code&gt;isBadVersion()&lt;/code&gt; drastically reduces to a complexity of &lt;code&gt;O(log(n))&lt;/code&gt; from the earlier complexity of &lt;code&gt;O(n)&lt;/code&gt; .&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Binary search is definitely a strategy to consider when dealing with sorted data. However, it’s worth noting that while binary search is effective for many such cases, it may not always be a perfect solution. Nevertheless, it remains a valuable option whenever we detect data sorted in some order.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Code Implementation(in C++)&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="c1"&gt;// The API isBadVersion is defined for you.&lt;/span&gt;
&lt;span class="c1"&gt;// bool isBadVersion(int version);&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;firstBadVersion&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="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;l&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;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&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;l&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;h&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;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;l&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;isBadVersion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;isBadVersion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&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;return&lt;/span&gt; &lt;span class="n"&gt;m&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;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;isBadVersion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;l&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;
  
  
  &lt;strong&gt;Breakdown of the Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Binary Search Initialization:&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l&lt;/code&gt; (lower bound) is set to 1 (represents the first version).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;h&lt;/code&gt; (upper bound) is set to &lt;code&gt;n&lt;/code&gt; (represents the last version).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; (middle index) will be calculated during the search loop.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Binary Search Loop:&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;while&lt;/code&gt; loop continues as long as &lt;code&gt;l&lt;/code&gt; is less than &lt;code&gt;h&lt;/code&gt;. This ensures the search space keeps narrowing down.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Inside the loop:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is calculated as the middle index between &lt;code&gt;l&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The key logic relies on two &lt;code&gt;isBadVersion&lt;/code&gt; calls:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The first check is &lt;code&gt;!isBadVersion(m) &amp;amp;&amp;amp; isBadVersion(m + 1)&lt;/code&gt;. This condition is true only if the middle version (&lt;code&gt;m&lt;/code&gt;) is good (not bad) and the next version (&lt;code&gt;m + 1&lt;/code&gt;) is bad. In this case, we've found the first bad version at index &lt;code&gt;m + 1&lt;/code&gt;, and the loop terminates, returning this value.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Binary Search Refinement:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If the condition &lt;code&gt;!isBadVersion(m) &amp;amp;&amp;amp; isBadVersion(m + 1)&lt;/code&gt; isn't met, we need to refine the search space further.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;isBadVersion(m)&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt; (meaning &lt;code&gt;m&lt;/code&gt; is bad), it signifies the first bad version could be within the lower half of the search space including m. We update &lt;code&gt;h&lt;/code&gt; to &lt;code&gt;m&lt;/code&gt; (excluding the upper half).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Conversely, if &lt;code&gt;isBadVersion(m)&lt;/code&gt; is &lt;code&gt;false&lt;/code&gt; (meaning &lt;code&gt;m&lt;/code&gt; is good), the first bad version must lie in the upper half. We update &lt;code&gt;l&lt;/code&gt; to &lt;code&gt;m&lt;/code&gt;(excluding the lower half)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;why updating &lt;code&gt;l&lt;/code&gt; to &lt;code&gt;m&lt;/code&gt; and not &lt;code&gt;m+1&lt;/code&gt;? since in the while loop we check for the middle number to be good - that’s why we need to keep atleast 1 good version for the next iteration.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Returning the Result:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;When the loop terminates (either by finding the first bad version or reaching the boundaries), the value of &lt;code&gt;l&lt;/code&gt; is returned. Since the loop stops when &lt;code&gt;l ≥ h&lt;/code&gt;, &lt;code&gt;l&lt;/code&gt; will always point to the first bad version after the loop completes.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If the input &lt;code&gt;n&lt;/code&gt;is 1, it means there’s only one version under consideration, which is then designated as the bad version. The code accommodates this scenario as well.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Further improvements in the code
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;One clear point of improvement is we can store the value of &lt;code&gt;isBadVersion(m)&lt;/code&gt; in a boolean variable and reused instead of making one more call during the same iteration.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Another area for improvement involves storing the values of &lt;code&gt;isBadVersion(m)&lt;/code&gt; and &lt;code&gt;isBadVersion(m+1)&lt;/code&gt;. This strategy helps us to reuse the previously checked version outputs, leading to a reduction in overall calls to the &lt;code&gt;isBadVersion(version)&lt;/code&gt; function. However, it’s worth noting that Leetcode seems to be imposing space restrictions for larger values of n in this problem.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Dry Run with a Test Case&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let’s perform a dry run on the code using the example &lt;code&gt;n = 5&lt;/code&gt; and the first bad version as &lt;code&gt;3&lt;/code&gt;:&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l&lt;/code&gt; is set to 1.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;h&lt;/code&gt; is set to 5.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is not yet calculated.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj4o3f4m956lh88s3gh73.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj4o3f4m956lh88s3gh73.png" alt="Image description" width="608" height="349"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 1:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is calculated as 3.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;isBadVersion(m)&lt;/code&gt; (checking version 3) returns &lt;code&gt;true&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;isBadVersion(m+1)&lt;/code&gt; (checking version 4) returns &lt;code&gt;true&lt;/code&gt; .&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since m is bad, we update &lt;code&gt;h = m&lt;/code&gt; .&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc8j9u40j1pgjb09wkz89.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc8j9u40j1pgjb09wkz89.png" alt="Image description" width="608" height="515"&gt;&lt;/a&gt;&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l = 1&lt;/code&gt;, &lt;code&gt;h = 3&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;m is calculated to be 2&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;isBadVersion(m)&lt;/code&gt; (checking version 2) returns &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;isBadVersion(m+1)&lt;/code&gt; (checking version 3) returns &lt;code&gt;true&lt;/code&gt; thereby returning &lt;code&gt;m+1 = 3&lt;/code&gt; as the first bad version&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu9v1p0cc5356cibde7kf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu9v1p0cc5356cibde7kf.png" alt="Image description" width="608" height="518"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Time and Space Complexity Analysis&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt; O(log n). The binary search approach significantly reduces the number of API calls needed to locate the first bad version. With each iteration, the search space is halved, leading to a logarithmic time complexity in terms of &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Space Complexity:&lt;/strong&gt; O(1). The code utilizes a constant amount of extra space for variables like &lt;code&gt;l&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt;, and &lt;code&gt;m&lt;/code&gt;, regardless of the input size &lt;code&gt;n&lt;/code&gt;. This makes the solution memory-efficient.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This blog post explored how Binary search can be used to solve Leetcode’s First Bad Version problem. We delved into the details of the problem statement and found out how Binary search can be thought of as an option whenever the problem contains some data ordered in a predictable way. Time complexity get reduced to a much smaller logarithmic scale thereby improving the solution’s efficiency by a whole margin.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Cover photo by &lt;a href="https://unsplash.com/@olloweb?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Agence Olloweb&lt;/a&gt; on &lt;a href="https://unsplash.com/photos/magnifying-glass-near-gray-laptop-computer-d9ILr-dbEdg?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Diagrams in the Dry run section are created using &lt;a href="https://www.canva.com/join/qsx-lqt-tpb"&gt;Canva&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;If you liked this post, do applaude by clicking on the clap hands icon and follow me &lt;a href="https://medium.com/@subhradeep_saha"&gt;&lt;em&gt;https://medium.com/@subhradeep_saha&lt;/em&gt;&lt;/a&gt; for such posts.&lt;/p&gt;

&lt;p&gt;If you want to follow on with binary search problems, do consider reading this post &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-8-sqrt-x-5e2521ef6fbe"&gt;https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-8-sqrt-x-5e2521ef6fbe&lt;/a&gt; where I explained how binary search can be used to efficiently find the square root of a number — there is 1 Math hack as well described in the post about square roots so dont forget to checkout and applaude that post. Thanks!!&lt;/p&gt;

</description>
      <category>binarysearch</category>
      <category>leetcode278</category>
      <category>firstbadversiom</category>
      <category>cpp</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 8 | Sqrt(x)</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Tue, 07 May 2024 13:25:38 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-8-sqrtx-4p8p</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-8-sqrtx-4p8p</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-8-sqrt-x-5e2521ef6fbe" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c-2Ckuec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/da:true/resize:fill:88:88/0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-8-sqrt-x-5e2521ef6fbe" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 8 | Sqrt(x) | by Subhradeep Saha | May, 2024 | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 7, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YjpYcCMa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/medium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;blockquote&gt;
&lt;p&gt;Here is the Leetcode problem link — &lt;a href="https://leetcode.com/explore/learn/card/binary-search/125/template-i/950/"&gt;Sqrt(x) &lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;LeetCode presents a challenge where you’re given a non-negative integer &lt;code&gt;x&lt;/code&gt; and the task is to write a function that returns the integer square root of &lt;code&gt;x&lt;/code&gt; rounded down to the nearest whole number.&lt;/p&gt;

&lt;p&gt;This calculation must be performed without relying on built-in functions like &lt;code&gt;pow(x, 0.5)&lt;/code&gt; (C++) or &lt;code&gt;x ** 0.5&lt;/code&gt; (Python).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&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="nl"&gt;Input:&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;8&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;span class="n"&gt;Explanation&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;The&lt;/span&gt; &lt;span class="n"&gt;square&lt;/span&gt; &lt;span class="n"&gt;root&lt;/span&gt; &lt;span class="n"&gt;of&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt; &lt;span class="n"&gt;is&lt;/span&gt; &lt;span class="mf"&gt;2.82842&lt;/span&gt;&lt;span class="p"&gt;...,&lt;/span&gt; &lt;span class="n"&gt;and&lt;/span&gt; &lt;span class="n"&gt;since&lt;/span&gt; &lt;span class="n"&gt;we&lt;/span&gt; &lt;span class="n"&gt;round&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt; &lt;span class="n"&gt;down&lt;/span&gt; 
&lt;span class="n"&gt;to&lt;/span&gt; &lt;span class="n"&gt;the&lt;/span&gt; &lt;span class="n"&gt;nearest&lt;/span&gt; &lt;span class="n"&gt;integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;is&lt;/span&gt; &lt;span class="n"&gt;returned&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;&lt;code&gt;x&lt;/code&gt; can range from 0 to the maximum possible value for an integer data type (2^31 - 1).&lt;/p&gt;

&lt;h3&gt;
  
  
  High Level Approach
&lt;/h3&gt;

&lt;p&gt;At first, the instinctive approach to solving the problem involves using a language’s built-in function to find the square root. However, this method does not align with the problem definition. The second apparent approach that comes to mind is finding the square root by iterating through every number from 1 to &lt;code&gt;x&lt;/code&gt;. However, the most optimal solution, which we will discuss in this blog offers a more efficient approach.&lt;/p&gt;

&lt;p&gt;The high-level concept of the optimal approach is as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;For any number &lt;code&gt;x&lt;/code&gt;, the square root of &lt;code&gt;x&lt;/code&gt; is always ≤ &lt;code&gt;x/2&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;By employing binary search within the range of 1 to &lt;code&gt;x/2&lt;/code&gt;, we check whether the middle number is the square root or not. If not, we narrow down the search space for the next iteration by comparing the square of the middle number with the input &lt;code&gt;x&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Code Implementation&lt;/strong&gt;
&lt;/h3&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&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="n"&gt;x&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;return&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;l&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;h&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;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;;&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;l&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 
      &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;l&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="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;prod&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;m&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;prod&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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;;&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;prod&lt;/span&gt; &lt;span class="o"&gt;&amp;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="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="n"&gt;l&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;h&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;
  
  
  &lt;strong&gt;Breakdown of the Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This code defines a class &lt;code&gt;Solution&lt;/code&gt; with a function &lt;code&gt;mySqrt&lt;/code&gt; that takes the integer &lt;code&gt;x&lt;/code&gt; as input and returns the integer square root rounded down.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Edge Case Handling:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;The code first checks for edge cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;x&lt;/code&gt; is 0, it returns 0 (square root of 0 is 0).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;x&lt;/code&gt; is 1, it returns 1 (square root of 1 is 1).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Binary Search Initialization:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;Three integer variables are declared:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l&lt;/code&gt; (lower bound) initialized to 1.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;h&lt;/code&gt; (upper bound) initialized to &lt;code&gt;x / 2&lt;/code&gt; (considering the largest possible square root for the given &lt;code&gt;x&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; (middle index) will be used during the search.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Binary Search Loop:&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;while&lt;/code&gt; loop iterates as long as &lt;code&gt;l&lt;/code&gt; is less than or equal to &lt;code&gt;h&lt;/code&gt;. This ensures the search space keeps narrowing down.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Inside the loop:&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is calculated as the middle index between &lt;code&gt;l&lt;/code&gt; and &lt;code&gt;h&lt;/code&gt; — m is calculated indirectly to prevent integer overflow due to &lt;code&gt;l + h&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;prod&lt;/code&gt; is calculated by squaring the &lt;code&gt;m&lt;/code&gt; value, but using &lt;code&gt;long&lt;/code&gt; to prevent integer overflow for larger values of &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;prod&lt;/code&gt; is equal to &lt;code&gt;x&lt;/code&gt;, it means we've found the exact square root, and the loop terminates, returning &lt;code&gt;m&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Value Comparison and Search Refinement:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;prod&lt;/code&gt; is greater than &lt;code&gt;x&lt;/code&gt;, it indicates the middle value (&lt;code&gt;m&lt;/code&gt;) is too high. The upper bound (&lt;code&gt;h&lt;/code&gt;) is updated to &lt;code&gt;m - 1&lt;/code&gt; to focus the search on the lower half of the range.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;prod&lt;/code&gt; is less than &lt;code&gt;x&lt;/code&gt;, it indicates the middle value (&lt;code&gt;m&lt;/code&gt;) is too low. The lower bound (&lt;code&gt;l&lt;/code&gt;) is updated to &lt;code&gt;m + 1&lt;/code&gt; to search the upper half of the range.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Returning the Result:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;We encounter two scenarios for returning the result:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The first occurs when we find the exact square root inside the while loop, leading to an immediate return.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the second case, if we do not find the exact square root, the while loop terminates, and the value of &lt;code&gt;h&lt;/code&gt; is returned.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Now, why do we specifically return &lt;code&gt;h&lt;/code&gt;and not &lt;code&gt;l&lt;/code&gt;, &lt;code&gt;m&lt;/code&gt;, or any other number?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The loop halts when &lt;code&gt;l&lt;/code&gt; exceeds &lt;code&gt;h&lt;/code&gt;, guaranteeing that &lt;code&gt;h&lt;/code&gt;is always one less than a number whose square root is greater than &lt;code&gt;x&lt;/code&gt;. This ensures that we return the integer rounded down, as specified in the problem statement.&lt;/p&gt;

&lt;p&gt;=&amp;gt; If the problem were to require returning the closest possible square root rounded up, we would return &lt;code&gt;l&lt;/code&gt; instead of &lt;code&gt;h&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;=&amp;gt; Similarly, if the problem mandated returning -1 when an exact square root isn’t found, we would return &lt;code&gt;-1&lt;/code&gt;instead of &lt;code&gt;h&lt;/code&gt;.&lt;/p&gt;

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

&lt;h4&gt;
  
  
  &lt;strong&gt;Time Complexity&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;The time complexity of the binary search solution for finding the integer square root is &lt;code&gt;O(logn)&lt;/code&gt;, where n is the input number &lt;code&gt;x&lt;/code&gt;. Here's a breakdown of why:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Binary Search:&lt;/strong&gt; The algorithm employs binary search, which repeatedly halves the search space with each iteration. This process of dividing the space ensures significant reduction in the number of comparisons needed to locate the target value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Logarithmic Iterations:&lt;/strong&gt; The number of iterations required to traverse the search space using binary search is roughly proportional to the logarithm of the initial search space size (base 2). In this case, the initial space ranges from 1 to &lt;code&gt;x / 2&lt;/code&gt;, which is logarithmic in terms of &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Therefore, the time complexity grows logarithmically with the increase in the input value &lt;code&gt;x&lt;/code&gt;, making the solution efficient for handling larger numbers.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Space Complexity&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;The space complexity of the binary search solution is O(1), which is considered constant space complexity. Here’s why:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Limited Variables:&lt;/strong&gt; The algorithm utilizes a fixed number of variables to store essential data like loop counters, indices, and temporary values. These variables do not depend on the input size &lt;code&gt;x&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;No Additional Data Structures:&lt;/strong&gt; The solution doesn’t involve creating or manipulating any additional data structures like arrays or lists whose sizes would scale with the input.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Because the space complexity remains constant regardless of the input size, the solution is memory-efficient.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Dry Run with a Test Case&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let’s perform a dry run on the code using the example &lt;code&gt;x = 8&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Edge Case Check:&lt;/strong&gt; Since &lt;code&gt;x&lt;/code&gt; is not 0 or 1, the code proceeds.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l&lt;/code&gt; is set to 1.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;h&lt;/code&gt; is set to 4(half of 2).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is not yet calculated&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fommycn1b3edr2zsun5lb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fommycn1b3edr2zsun5lb.png" alt="" width="487" height="136"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Iteration 1:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is calculated as &lt;code&gt;1 + (4 — 1)/2 = 2&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;prod&lt;/code&gt; is calculated as &lt;code&gt;2 * 2 = 4&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since &lt;code&gt;prod&lt;/code&gt; is less than &lt;code&gt;x&lt;/code&gt;, &lt;code&gt;l&lt;/code&gt; is updated to &lt;code&gt;m + 1&lt;/code&gt; (which becomes 3).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz4rbtgwoq7kxe4aeutko.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz4rbtgwoq7kxe4aeutko.png" alt="" width="487" height="207"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Iteration 2:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;l&lt;/code&gt; = 3 is still less than &lt;code&gt;h&lt;/code&gt;= 4&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;m&lt;/code&gt; is calculated as &lt;code&gt;3 + (4 — 3)/2 = 3&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;prod&lt;/code&gt; is calculated as &lt;code&gt;3 * 3 = 9&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since &lt;code&gt;prod&lt;/code&gt; is greater &lt;code&gt;x&lt;/code&gt;, &lt;code&gt;h&lt;/code&gt; is updated to &lt;code&gt;m — 1&lt;/code&gt; = 2&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh4l6zge9zle1g0qov28a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh4l6zge9zle1g0qov28a.png" alt="" width="487" height="284"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Iteration 3:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;l&lt;/code&gt; = 3 is now greater than &lt;code&gt;h&lt;/code&gt; = 2, so the while loop terminates now&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9alrxo1eqxc93tc4q6tx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9alrxo1eqxc93tc4q6tx.png" alt="Image description" width="487" height="130"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Result:&lt;/strong&gt; The function returns &lt;code&gt;h&lt;/code&gt; (which is 2), representing the integer square root of 8 rounded down (as expected).&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Finding the integer square root without built-in functions has various real-world applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Game Development:&lt;/strong&gt; In video games, calculating distances, applying physics simulations, or generating random numbers can involve square root computations. Using an efficient custom implementation like this can be beneficial, especially for performance optimization in resource-constrained environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cryptography:&lt;/strong&gt; Some encryption algorithms rely on modular arithmetic operations, which might involve square root calculations. Implementing a custom square root function can provide more control over the algorithm’s behavior, potentially enhancing security.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Embedded Systems:&lt;/strong&gt; In microcontrollers or other embedded systems with limited processing power and memory, using a custom square root function can be more efficient than relying on bulky libraries with built-in math functions.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This blog post delved into essential concepts such as square root constraints and the application of the binary search algorithm to address problems where search spaces can be minimized for subsequent iterations, thereby reducing time complexities from &lt;code&gt;O(n)&lt;/code&gt; to &lt;code&gt;O(logn)&lt;/code&gt;. Grasping this approach can prove invaluable in scenarios demanding efficient square root calculations without dependence on external libraries.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Game Development with Physics: &lt;a href="https://www.new3jcn.com/simulation.html"&gt;https://www.new3jcn.com/simulation.html&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Introduction to Cryptography: &lt;a href="https://www.khanacademy.org/computing/computer-science/cryptography"&gt;https://www.khanacademy.org/computing/computer-science/cryptography&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Introduction to Embedded Systems: &lt;a href="https://www.amazon.com/Embedded-Systems-Architecture-Programming-Engineering/dp/007340456X"&gt;https://www.amazon.com/Embedded-Systems-Architecture-Programming-Engineering/dp/007340456X&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Diagrams in the Dry run section are created using &lt;a href="https://www.canva.com/join/qsx-lqt-tpb"&gt;Canva&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cover photo by &lt;a href="https://unsplash.com/@antoine1003?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Antoine Dautry&lt;/a&gt; on &lt;a href="https://unsplash.com/photos/black-retractable-pen-on-white-printer-paper-_zsL306fDck?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;If you liked this post, do applaude by clicking on the clap hands icon and follow me &lt;a href="https://medium.com/@subhradeep_saha"&gt;&lt;em&gt;https://medium.com/@subhradeep_saha&lt;/em&gt;&lt;/a&gt; for such posts. If you are a Maths + Coding enthusiast, then do checkout these Medium posts of mine solving other Leetcode problems related to Math and Arrays —&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-7-array-partition-i-2d915d787469"&gt;https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-7-array-partition-i-2d915d787469&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-4-add-binary-24a98c1df7c5"&gt;https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-4-add-binary-24a98c1df7c5&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-2-plus-one-a77a96759794"&gt;https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-2-plus-one-a77a96759794&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-b9ea47250985"&gt;https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-b9ea47250985&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>binarysearch</category>
      <category>cpp</category>
      <category>leetcode</category>
      <category>squareroot</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 6 | Longest Common Prefix</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Mon, 06 May 2024 02:33:10 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-6-longest-common-prefix-3d7f</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-6-longest-common-prefix-3d7f</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-6-longest-common-prefix-bc6a1152a00a" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c-2Ckuec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/da:true/resize:fill:88:88/0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-6-longest-common-prefix-bc6a1152a00a" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 6 | Longest Common Prefix | by Subhradeep Saha | May, 2024 | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 4, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YjpYcCMa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/medium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;
 


&lt;h3&gt;
  
  
  &lt;strong&gt;Conquering LeetCode: Finding the Longest Common Prefix&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This blog post tackles a classic LeetCode challenge: given an array of strings, write a function that finds the longest string which is a prefix (beginning) of all the strings in the array. We’ll delve into the problem statement, code implementation, step-by-step explanation, real-world applications, and conclude with some key takeaways.&lt;/p&gt;

&lt;p&gt;Here is the Leetcode problem link —&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="https://leetcode.com/explore/learn/card/array-and-string/203/introduction-to-string/1162/"&gt;https://leetcode.com/explore/learn/card/array-and-string/203/introduction-to-string/1162/&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;LeetCode presents a challenge where you’re given an array of strings (&lt;code&gt;strs&lt;/code&gt;). The task is to write a function that returns the longest common prefix shared by all strings in the array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&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="nl"&gt;Input:&lt;/span&gt; &lt;span class="n"&gt;strs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"flower"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"flow"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"flight"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="s"&gt;"fl"&lt;/span&gt;
&lt;span class="n"&gt;Explanation&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="n"&gt;Here&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"fl"&lt;/span&gt; &lt;span class="n"&gt;is&lt;/span&gt; &lt;span class="n"&gt;the&lt;/span&gt; &lt;span class="n"&gt;longest&lt;/span&gt; &lt;span class="n"&gt;prefix&lt;/span&gt; &lt;span class="n"&gt;that&lt;/span&gt; &lt;span class="n"&gt;appears&lt;/span&gt; &lt;span class="n"&gt;at&lt;/span&gt; &lt;span class="n"&gt;the&lt;/span&gt; &lt;span class="n"&gt;beginning&lt;/span&gt; 
&lt;span class="n"&gt;of&lt;/span&gt; &lt;span class="n"&gt;all&lt;/span&gt; &lt;span class="n"&gt;three&lt;/span&gt; &lt;span class="n"&gt;strings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="nl"&gt;Input:&lt;/span&gt; &lt;span class="n"&gt;strs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"dog"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"racecar"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="s"&gt;"car"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="s"&gt;""&lt;/span&gt;
&lt;span class="n"&gt;Explanation&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;There&lt;/span&gt; &lt;span class="n"&gt;is&lt;/span&gt; &lt;span class="n"&gt;no&lt;/span&gt; &lt;span class="n"&gt;common&lt;/span&gt; &lt;span class="n"&gt;prefix&lt;/span&gt; &lt;span class="n"&gt;among&lt;/span&gt; &lt;span class="n"&gt;the&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="n"&gt;strings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The number of strings (&lt;code&gt;strs.length&lt;/code&gt;) can range from 1 to 200.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The length of each individual string (&lt;code&gt;strs[i].length&lt;/code&gt;) can range from 0 to 200.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;All characters in the strings are lowercase English letters.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Code Implementation&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Here’s the C++ code that solves this challenge:&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="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;longestCommonPrefix&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;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;strs&lt;/span&gt;&lt;span class="p"&gt;)&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;strs&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="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;return&lt;/span&gt; &lt;span class="n"&gt;strs&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="p"&gt;}&lt;/span&gt;

      &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;pref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&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;currIdx&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;while&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="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;char&lt;/span&gt; &lt;span class="n"&gt;ch&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;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;strs&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="n"&gt;i&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="n"&gt;string&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;strs&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;currIdx&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&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;pref&lt;/span&gt;&lt;span class="p"&gt;;&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;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="p"&gt;{&lt;/span&gt; 
            &lt;span class="n"&gt;ch&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="n"&gt;currIdx&lt;/span&gt;&lt;span class="p"&gt;];&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;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;currIdx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;ch&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;pref&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="n"&gt;pref&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;strs&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;currIdx&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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;pref&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;
  
  
  &lt;strong&gt;Breakdown of the Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This code defines a class &lt;code&gt;Solution&lt;/code&gt; with a function &lt;code&gt;longestCommonPrefix&lt;/code&gt; that takes the array of strings (&lt;code&gt;strs&lt;/code&gt;) as input and returns the longest common prefix.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Edge Case:&lt;/strong&gt; The code first checks if there’s only one string (&lt;code&gt;strs.size() == 1&lt;/code&gt;) in the input array. In that case, the single string itself is the longest common prefix, so it's returning that(&lt;code&gt;return strs[0]&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;pref&lt;/code&gt; (empty string) stores the growing common prefix.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;currIdx&lt;/code&gt; (integer) keeps track of the current index (position) within the strings being compared.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3. &lt;strong&gt;Looping and Comparison:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An infinite &lt;code&gt;while(1)&lt;/code&gt; loop continues until the common prefix is found or there's a mismatch.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Inside the loop:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A character variable &lt;code&gt;ch&lt;/code&gt; is declared to hold the character to be compared across all strings.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A &lt;code&gt;for&lt;/code&gt; loop iterates through each string (&lt;code&gt;strs[i]&lt;/code&gt;) in the array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;currIdx&lt;/code&gt; reaches the end of the current string (&lt;code&gt;currIdx &amp;gt;= s.length()&lt;/code&gt;), it means there's no more prefix to compare, so the current &lt;code&gt;pref&lt;/code&gt; is returned.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the first iteration (&lt;code&gt;i == 0&lt;/code&gt;), the character at &lt;code&gt;currIdx&lt;/code&gt; from the first string (&lt;code&gt;strs[0]&lt;/code&gt;) is assigned to &lt;code&gt;ch&lt;/code&gt; as the reference point for comparison.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the character at &lt;code&gt;currIdx&lt;/code&gt; in the current string (&lt;code&gt;s[currIdx]&lt;/code&gt;) doesn't match the reference character &lt;code&gt;ch&lt;/code&gt;, it indicates a mismatch, and the loop terminates, returning the current &lt;code&gt;pref&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4. &lt;strong&gt;Building the Prefix:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If all characters at &lt;code&gt;currIdx&lt;/code&gt; across all strings match, the character from &lt;code&gt;strs[0]&lt;/code&gt; at &lt;code&gt;currIdx&lt;/code&gt; is appended to the &lt;code&gt;pref&lt;/code&gt; string and simultaneously the &lt;code&gt;currIdx&lt;/code&gt; is also incremented to move to the next character position for the next iteration. (&lt;code&gt;pref += strs[0][currIdx++]&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;5. &lt;strong&gt;Return Value:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The loop eventually breaks when a mismatch is found between the strings character at &lt;code&gt;currIdx&lt;/code&gt; or we reached the end of any of the string. The final &lt;code&gt;pref&lt;/code&gt; string containing the longest common prefix is returned.&lt;/p&gt;

&lt;p&gt;Lets verify the code with a dry run of a testcase in the next section&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Code Dry Run with a Test Case&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let’s use the provided example:&lt;/p&gt;

&lt;p&gt;Input: strs = ["flower", "flow", "flight"]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Edge Case Check (Skipped)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are more than one string, so the code proceeds to the main logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Initialization&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;pref&lt;/code&gt; = "" (empty string)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;currIdx&lt;/code&gt; = 0&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Loop Iteration 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Character Comparison:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;ch&lt;/code&gt; is assigned the first character from the first string (&lt;code&gt;ch = 'f'&lt;/code&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;All three strings have ‘f’ at index 0, so the loop continues.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffr7r2nd13y3m9ywyxkz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fffr7r2nd13y3m9ywyxkz.png" alt="Image description" width="656" height="264"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building the Prefix:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;‘f’ is appended to &lt;code&gt;pref&lt;/code&gt;: &lt;code&gt;pref = "f"&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;currIdx&lt;/code&gt; is incremented to 1 (&lt;code&gt;currIdx = 1&lt;/code&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Loop Iteration 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Character Comparison:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All three strings have ‘l’ at index 1, so the loop continues.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuqbrql5crnpw1lripofu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuqbrql5crnpw1lripofu.png" alt="Image description" width="656" height="264"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Building the Prefix:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;‘l’ is appended to &lt;code&gt;pref&lt;/code&gt;: &lt;code&gt;pref = "fl"&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;currIdx&lt;/code&gt; is incremented to 2 (&lt;code&gt;currIdx = 2&lt;/code&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Loop Termination (Mismatch)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Character Comparison:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The third string (“flight”) has ‘i’ at index 2, while the first two strings have ‘o’. There’s a mismatch.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firi914e25tdixihbdgjo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firi914e25tdixihbdgjo.png" alt="Image description" width="656" height="264"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The loop terminates at this point.&lt;/p&gt;

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

&lt;p&gt;The final value of &lt;code&gt;pref&lt;/code&gt; is "fl", which is the longest common prefix for all three strings. The function returns &lt;code&gt;"fl"&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Finding the longest common prefix has various applications in real-world scenarios:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;File Compression:&lt;/strong&gt; In data compression techniques like Lempel-Ziv coding, the longest common prefix between repeated strings can be identified and replaced with a reference, reducing file size.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Autocompletion:&lt;/strong&gt; Search engines and text editors often use the longest common prefix to suggest completions for partially typed words, improving user experience.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Natural Language Processing (NLP):&lt;/strong&gt; NLP tasks like text classification or stemming (reducing words to their base forms) can utilize common prefixes to group related words or identify word stems.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This blog post explored the LeetCode challenge of finding the longest common prefix using a C++ code. We broke down the problem statement, presented the code with detailed step-by-step explanations, performed a dry run with a test case and discussed real-world applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;File Compression (Lempel-Ziv Coding):&lt;/strong&gt;&lt;a href="https://ethw.org/Milestones:Lempel-Ziv_Data_Compression_Algorithm,_1977"&gt;https://ethw.org/Milestones:Lempel-Ziv_Data_Compression_Algorithm,_1977&lt;/a&gt; by Wikipedia: This article provides an overview of Lempel-Ziv (LZ) coding, a family of data compression algorithms. It mentions that LZ77, a specific variant, uses the concept of finding repeating phrases and replacing them with references to a dictionary, effectively using longest common prefixes for compression.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Autocompletion:&lt;/strong&gt;&lt;a href="https://searchengineland.com/how-google-autocomplete-works-390257"&gt;https://searchengineland.com/how-google-autocomplete-works-390257&lt;/a&gt; by Google Research: This blog post discusses various techniques used in search query autocomplete. It mentions that a prefix tree data structure can be employed to efficiently identify prefixes of words stored in the system, enabling suggestions based on the common prefix typed by the user.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Natural Language Processing (NLP):&lt;/strong&gt;&lt;a href="https://en.wikipedia.org/wiki/Stemming"&gt;https://en.wikipedia.org/wiki/Stemming&lt;/a&gt; by Wikipedia: This article describes stemming algorithms, a technique in NLP used to reduce words to their base forms. Some stemming algorithms, like the Porter Stemmer, rely on identifying common prefixes among words to achieve stemming.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The diagrams in the Dry run section are created using &lt;a href="https://www.canva.com/join/qsx-lqt-tpb"&gt;Canva&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you liked this blog, do applaude by clicking on the clap hands icon and drop down any feedback you have in the comments.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;You can follow me &lt;a href="https://medium.com/@subhradeep_saha"&gt;&lt;em&gt;https://medium.com/@subhradeep_saha&lt;/em&gt;&lt;/a&gt; and check out my other posts as well where I explained the solutions of few other interesting Leetcode problems:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-b9ea47250985"&gt;Pascal’s triangle&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-2-plus-one-a77a96759794"&gt;Plus one&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-3-spiral-matrix-e225fa1f15a9"&gt;Spiral Matrix&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-4-add-binary-24a98c1df7c5"&gt;Add binary&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-5-diagonal-traverse-17b173927e95"&gt;Diagonal traverse&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>string</category>
      <category>prefix</category>
      <category>leetcode</category>
      <category>longestcommonprefix</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 5 | Diagonal Traverse</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Mon, 06 May 2024 02:32:51 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-5-diagonal-traverse-1ckj</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-5-diagonal-traverse-1ckj</guid>
      <description>&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-5-diagonal-traverse-17b173927e95" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://res.cloudinary.com/practicaldev/image/fetch/s--Y-rNiEDC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/resize:fit:640/1%2AYuS_L5je9sZmSrz61CJOLQ.jpeg" height="729" class="m-0" width="640"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://blog.devgenius.io/solving-a-leetcode-problem-daily-day-5-diagonal-traverse-17b173927e95" rel="noopener noreferrer" class="c-link"&gt;
          Solving a Leetcode problem daily — Day 5 | Diagonal Traverse | by Subhradeep Saha | May, 2024 | Dev Genius
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;p class="truncate-at-3"&gt;
          Slay Leetcode’s Diagonal Traversal problem with this detailed C++ guide - code breakdown, dry run with diagrams, &amp;amp; real-world applications.
        &lt;/p&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://res.cloudinary.com/practicaldev/image/fetch/s--607eFk1m--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/resize:fill:256:256/1%2ACvejhRq3NYsivxILYXEdfA.jpeg" width="128" height="128"&gt;
        blog.devgenius.io
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;





&lt;p&gt;Here is the Leetcode problem:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;a href="https://leetcode.com/explore/learn/card/array-and-string/202/introduction-to-2d-array/1167/"&gt;https://leetcode.com/explore/learn/card/array-and-string/202/introduction-to-2d-array/1167/&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Given a matrix (&lt;code&gt;mat&lt;/code&gt;) with dimensions &lt;code&gt;m x n&lt;/code&gt; (rows and columns) the task is to write a function that returns a one-dimensional array containing all the elements of the matrix in a diagonal order.&lt;/p&gt;

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

&lt;p&gt;Input: mat = [[1,2,3],[4,5,6],[7,8,9]]&lt;br&gt;&lt;br&gt;
Output: [1,2,4,7,5,3,6,8,9]&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff5kg6tetj7mjrnsv2ugv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff5kg6tetj7mjrnsv2ugv.png" alt="Image description" width="334" height="334"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, the elements are traversed diagonally, starting from the top-left corner and moving towards the bottom-right corner (direction is &lt;strong&gt;↘&lt;/strong&gt;), zig-zagging between upward and downward diagonals.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The number of rows (&lt;code&gt;m&lt;/code&gt;) is equal to the length of the inner arrays (&lt;code&gt;mat.length&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The number of columns (&lt;code&gt;n&lt;/code&gt;) is equal to the length of each inner array (&lt;code&gt;mat[i].length&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Both &lt;code&gt;m&lt;/code&gt; and &lt;code&gt;n&lt;/code&gt; can range from 1 to 10^4 (10,000).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The total number of elements (&lt;code&gt;m * n&lt;/code&gt;) can also range from 1 to 10^4.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Individual elements in the matrix (&lt;code&gt;mat[i][j]&lt;/code&gt;) can have values between -10^5 and 10^5 (inclusive).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Code Implementation&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Here’s the C++ code that solves this challenge:&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="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;&lt;/span&gt; &lt;span class="n"&gt;findDiagonalOrder&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;mat&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;left_r&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;left_c&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;right_r&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;right_c&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;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mat&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="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mat&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="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;traverseRight&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;true&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="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&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;left_c&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;left_r&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;right_c&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;right_r&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;traverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;traverseRight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;left_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;left_c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right_r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;right_c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&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;left_r&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;left_r&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="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;left_c&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="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;right_c&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="n"&gt;right_c&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="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="n"&gt;right_r&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="n"&gt;traverseRight&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;traverseRight&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;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;
  &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;traverse&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;mat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="n"&gt;traverseRight&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;left_r&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;left_c&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;right_r&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;right_c&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="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&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;traverseRight&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&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;left_r&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;right_r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mat&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;left_r&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;left_c&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="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&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;left_r&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;right_r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mat&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;right_r&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_c&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;h3&gt;
  
  
  &lt;strong&gt;Breakdown of the Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This code defines a class &lt;code&gt;Solution&lt;/code&gt; with two functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;findDiagonalOrder&lt;/code&gt;: This is the main function that takes the matrix (&lt;code&gt;mat&lt;/code&gt;) as input and returns the diagonal order array (&lt;code&gt;res&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;traverse&lt;/code&gt;: This is a helper function that performs the diagonal traversal based on a direction flag (&lt;code&gt;traverseRight&lt;/code&gt;) and boundary indices (&lt;code&gt;left_r&lt;/code&gt;, &lt;code&gt;left_c&lt;/code&gt;, &lt;code&gt;right_r&lt;/code&gt;, &lt;code&gt;right_c&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;[&lt;code&gt;left_r&lt;/code&gt;, &lt;code&gt;left_c&lt;/code&gt;] and [&lt;code&gt;right_r&lt;/code&gt;, &lt;code&gt;right_c&lt;/code&gt;] are the 2 boundary items on a diagonal between which we need to traverse. The first one is the boundary item on the left of the diagonal and the other is on the right boundary.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;r&lt;/code&gt; stores the number of rows (&lt;code&gt;mat.size()&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;c&lt;/code&gt; stores the number of columns (&lt;code&gt;mat[0].size()&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;traverseRight&lt;/code&gt; Flag**:** This boolean variable controls the direction of traversal.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;true&lt;/code&gt;: Indicates right-upward diagonal traversal ([&lt;code&gt;left_r&lt;/code&gt;, &lt;code&gt;left_c&lt;/code&gt;] to [&lt;code&gt;right_r&lt;/code&gt;, &lt;code&gt;right_c&lt;/code&gt;])&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fakg3sqq1qmo493z7w0wr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fakg3sqq1qmo493z7w0wr.png" alt="Image description" width="448" height="191"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;false&lt;/code&gt;: Indicates left-downward diagonal traversal ([&lt;code&gt;right_r&lt;/code&gt;, &lt;code&gt;right_c&lt;/code&gt;] to [&lt;code&gt;left_r&lt;/code&gt;, &lt;code&gt;left_c&lt;/code&gt;]).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhbw32x01ogfnl8wua25.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqhbw32x01ogfnl8wua25.png" alt="Image description" width="448" height="191"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;res&lt;/code&gt;&lt;strong&gt;:&lt;/strong&gt; This vector stores the elements of the matrix in diagonal order as they are traversed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;while&lt;/code&gt; loop: The core logic resides within this loop, which continues until all elements are processed. It checks if any of the indices (&lt;code&gt;left_c&lt;/code&gt;, &lt;code&gt;left_r&lt;/code&gt;, &lt;code&gt;right_c&lt;/code&gt;, &lt;code&gt;right_r&lt;/code&gt;) reach their respective matrix boundaries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;traverse&lt;/code&gt; function: Inside the loop, the &lt;code&gt;traverse&lt;/code&gt; helper function is called based on the current &lt;code&gt;traverseRight&lt;/code&gt; flag. This function handles the actual diagonal element addition to the &lt;code&gt;res&lt;/code&gt; vector based on the &lt;code&gt;traverseRight&lt;/code&gt; flag.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Updating Indices:&lt;/strong&gt; After each iteration of the &lt;code&gt;traverse&lt;/code&gt; function:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;a) If there are still more elements in the current row (&lt;code&gt;left_r + 1 &amp;lt; r&lt;/code&gt;), &lt;code&gt;left_r&lt;/code&gt; is incremented (moving down).&lt;/p&gt;

&lt;p&gt;b) Otherwise, &lt;code&gt;left_c&lt;/code&gt; is incremented (moving right to the next column).&lt;/p&gt;

&lt;p&gt;c) If there are items in the current column(&lt;code&gt;right_c + 1 &amp;lt; c&lt;/code&gt;), we got to next column &lt;code&gt;right_c++&lt;/code&gt; else we go 1 row down(&lt;code&gt;right_r++&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;d) &lt;strong&gt;Toggling Direction:&lt;/strong&gt; Finally, the &lt;code&gt;traverseRight&lt;/code&gt; flag is flipped (&lt;code&gt;!traverseRight&lt;/code&gt;) to indicate a change in direction for the next iteration.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feqiqm9vevxhswzmnjppy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feqiqm9vevxhswzmnjppy.png" alt="Image description" width="568" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;traverse&lt;/code&gt;&lt;strong&gt;Function:&lt;/strong&gt; This helper function takes several arguments:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;mat&lt;/code&gt;: The reference to the original matrix.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;traverseRight&lt;/code&gt;: The direction flag.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Boundary indices (&lt;code&gt;left_r&lt;/code&gt;, &lt;code&gt;left_c&lt;/code&gt;, &lt;code&gt;right_r&lt;/code&gt;, &lt;code&gt;right_c&lt;/code&gt;): Define the starting and ending points for the current diagonal traversal.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;res&lt;/code&gt;: The reference to the result vector.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inside the &lt;code&gt;traverse&lt;/code&gt; function, a &lt;code&gt;while&lt;/code&gt; loop continues as long as all the items in the diagonal are pushed to the res vector.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Based on the &lt;code&gt;traverseRight&lt;/code&gt; flag:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;=&amp;gt; If &lt;code&gt;true&lt;/code&gt; (upward diagonal): elements from &lt;code&gt;mat[left_r][left_r]&lt;/code&gt; are added to &lt;code&gt;res&lt;/code&gt; ; &lt;code&gt;left_r&lt;/code&gt; is decremented and &lt;code&gt;left_c&lt;/code&gt; is incremented to indicate a diagonally right-upward movement&lt;/p&gt;

&lt;p&gt;=&amp;gt; If &lt;code&gt;false&lt;/code&gt; (downward diagonal): elements from &lt;code&gt;mat[right_r][right_c]&lt;/code&gt; are added to &lt;code&gt;res&lt;/code&gt; ; &lt;code&gt;right_r&lt;/code&gt; is incremented and &lt;code&gt;right_c&lt;/code&gt; is decremented implying a diagonally left-downward movement.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Return Value:&lt;/strong&gt; The &lt;code&gt;findDiagonalOrder&lt;/code&gt; function returns the final &lt;code&gt;res&lt;/code&gt; vector containing all the matrix elements in diagonal order.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Dry Run with a Test Case&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let’s use the provided example matrix:&lt;/p&gt;

&lt;p&gt;Input: mat = [[1,2,3],[4,5,6],[7,8,9]]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Initialization&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;left_r = 0&lt;/code&gt;, &lt;code&gt;left_c = 0&lt;/code&gt; (left side of a diagonal)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;right_r = 0&lt;/code&gt;, &lt;code&gt;right_c = 0&lt;/code&gt; (right side of the diagonal)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;r = 3&lt;/code&gt; (number of rows)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;c = 3&lt;/code&gt; (number of columns)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;traverseRight = true&lt;/code&gt; (initial upward diagonal)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;res = []&lt;/code&gt; (empty result vector)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3rb1muaa2srowtud009o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3rb1muaa2srowtud009o.png" alt="Image description" width="550" height="407"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: First Iteration (Upward Diagonal)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We call the &lt;code&gt;traverse&lt;/code&gt; function with &lt;code&gt;traverseRight = true&lt;/code&gt;. It starts processing elements from &lt;code&gt;mat[0][0]&lt;/code&gt; (1) and moves diagonally up until it reaches the boundary (&lt;code&gt;left_r &amp;lt; right_r&lt;/code&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;res = [1]&lt;/code&gt; (1 added to &lt;code&gt;res&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4zhfxsivcx8qcegv884c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4zhfxsivcx8qcegv884c.png" alt="Image description" width="549" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Updating Indices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since there are more elements in the first row (&lt;code&gt;left_r + 1 &amp;lt; r&lt;/code&gt;), we increment &lt;code&gt;left_r&lt;/code&gt; to 1. Similarly we increment right_c to 1. Hence our next diagonal boundaries are ready:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;left_r = 1&lt;/code&gt;, &lt;code&gt;left_c = 0&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;right_r = 0&lt;/code&gt;, &lt;code&gt;right_c = 1&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;traverseRight&lt;/code&gt; flag is now reversed to false indicating a left-downward diagonal movement&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiivg39wkfvwp6r8h68ix.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiivg39wkfvwp6r8h68ix.png" alt="Image description" width="550" height="407"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Second Iteration (Left-Downward Diagonal)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We call &lt;code&gt;traverse&lt;/code&gt; again. This time, it moves diagonally left-down.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;res = [1, 2, 4]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3e874g69uidtmbi6zgd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw3e874g69uidtmbi6zgd.png" alt="Image description" width="549" height="229"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Updating Indices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Same logic as Step 3&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;left_r = 2&lt;/code&gt;, &lt;code&gt;left_c = 0&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;right_r = 0&lt;/code&gt;, &lt;code&gt;right_c = 2&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;traverseRight&lt;/code&gt; flag is now reversed to true indicating a right-upward diagonal movement.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65597u341pyo8gnps4lc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F65597u341pyo8gnps4lc.png" alt="Image description" width="550" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Third Iteration (Right-Upward Diagonal)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;res = [1, 2, 4, 7, 5, 3]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg51sgm4r9zho01bntf7w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg51sgm4r9zho01bntf7w.png" alt="Image description" width="550" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 7: Updating Indices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For right boundary, there are no more elements in the current column (&lt;code&gt;right_c + 1 &amp;gt; c&lt;/code&gt;), so we increment &lt;code&gt;right_r&lt;/code&gt; to move down. Similarly for left boundary, there are no more items in the current row, so we move right by incrementing &lt;code&gt;left_c&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;left_r = 2&lt;/code&gt;, &lt;code&gt;left_c = 1&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;right_r = 1&lt;/code&gt;, &lt;code&gt;right_c = 2&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsg4n8f5unvzws9gjemxr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsg4n8f5unvzws9gjemxr.png" alt="Image description" width="550" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 8: Fourth Iteration (Left-Downward Diagonal)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9402de2e89zo92bsy96r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9402de2e89zo92bsy96r.png" alt="Image description" width="550" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;res = [1, 2, 4, 7, 5, 3, 6, 8]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 9: Updating Indices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Same as step 7&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;left_r = 2&lt;/code&gt;, &lt;code&gt;left_c = 2&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;right_r = 2&lt;/code&gt;, &lt;code&gt;right_c = 2&lt;/code&gt; (reaches the end of the last row)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6m1sw8w7mpo0hqyuga6f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6m1sw8w7mpo0hqyuga6f.png" alt="Image description" width="550" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 10: Fifth Iteration (Upward Diagonal)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzr8av07nofnm9ilmuyz5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzr8av07nofnm9ilmuyz5.png" alt="Image description" width="550" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;res = [1, 2, 4, 7, 5, 3, 6, 8, 9]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 11: Updating Indices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Same as step 7&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;left_r = 2&lt;/code&gt;, &lt;code&gt;left_c = 3&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;right_r = 3&lt;/code&gt;, &lt;code&gt;right_c = 2&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr0d1ei9iab0x9x3io0u7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr0d1ei9iab0x9x3io0u7.png" alt="Image description" width="550" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 12: Loop Termination&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The diagonal boundary is getting out of the actual input matrix dimensions so the while loop gets terminated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Final Result:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;res&lt;/code&gt; vector now contains all the elements of the matrix in diagonal order: &lt;code&gt;[1, 2, 4, 7, 5, 3, 6, 8, 9]&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This diagonal order traversal technique can be applied to various real-world scenarios:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Image Processing:&lt;/strong&gt; When processing images, diagonal filtering techniques can be used for noise reduction or edge detection. By iterating over pixels in a diagonal order, filters can analyze neighboring pixels along diagonal patterns for specific effects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Game Development:&lt;/strong&gt; In certain game genres like strategy games, pathfinding algorithms might consider diagonal movement for characters. Traversing the game map diagonally can help identify potential paths or obstacles.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Machine Learning:&lt;/strong&gt; In some machine learning algorithms, diagonal traversal can be used to access and process data stored in matrices. This can be relevant for tasks like image recognition or natural language processing.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This blog explored the LeetCode challenge of traversing the diagonals of a matrix in C++. We tackled the problem statement, presented the code with explanations, performed a dry run with a test case and discussed few real-world applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;“Bilateral Filtering for Noise Reduction in Digital Images”&lt;/strong&gt;&lt;a href="https://people.csail.mit.edu/fredo/PUBLI/Siggraph2002/DurandBilateral.pdf"&gt;https://people.csail.mit.edu/fredo/PUBLI/Siggraph2002/DurandBilateral.pdf&lt;/a&gt; by Sylvain Paris and Pierre Kornprobst: This paper explores bilateral filtering, a technique used for noise reduction in images. It mentions that bilateral filters can be applied along different directions, including diagonals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;“Pathfinding with Grids”&lt;/strong&gt;&lt;a href="https://brianlovin.com/hn/34594547"&gt;https://brianlovin.com/hn/34594547&lt;/a&gt; by Christer Eklund on Gamasutra: This article discusses various pathfinding techniques for grid-based game worlds. It mentions that diagonal movement can be an important factor for characters to navigate efficiently within the game environment.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;“Convolutional Neural Networks for Visual Recognition”&lt;/strong&gt;&lt;a href="https://cs231n.github.io/"&gt;https://cs231n.github.io/&lt;/a&gt; by Andrej Karpathy et al.: CNNs heavily rely on matrix operations, and diagonal traversal can be a relevant concept for accessing and processing data within these matrices.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Matrix diagrams are created using &lt;a href="https://www.canva.com/join/qsx-lqt-tpb"&gt;Canva&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you liked this blog, do applaude the post by clicking on the clap hands icon. You can follow me &lt;a href="https://medium.com/@subhradeep_saha"&gt;https://medium.com/@subhradeep_saha&lt;/a&gt; and check out my other posts as well. In case you are interested more on traversals, do checkout this post — &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-3-spiral-matrix-e225fa1f15a9"&gt;Spiral Matrix Traversal&lt;/a&gt;, where I explained the spiral traversal of a matrix. Thanks!&lt;/p&gt;

</description>
      <category>diagonal</category>
      <category>traversal</category>
      <category>cpp</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 4 | Add Binary</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Mon, 06 May 2024 02:32:24 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-4-add-binary-24d7</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-4-add-binary-24d7</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-4-add-binary-24a98c1df7c5" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fda%3Atrue%2Fresize%3Afill%3A88%3A88%2F0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-4-add-binary-24a98c1df7c5" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 4 | Add Binary | by Subhradeep Saha | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;Apr 30, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fmedium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;blockquote&gt;
&lt;p&gt;Here is the leetcode problem link — &lt;a href="https://leetcode.com/explore/learn/card/array-and-string/203/introduction-to-string/1160/" rel="noopener noreferrer"&gt;https://leetcode.com/explore/learn/card/array-and-string/203/introduction-to-string/1160/&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h3&gt;
  
  
  1. Problem Statement, Constraints, and Test Case
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem:&lt;/strong&gt; Write a function that takes two binary strings (&lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;) as input and returns their sum, also represented as a binary string.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The length of each string (&lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;) can range from 1 to 10^4 (10,000) characters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Both strings consist only of ‘0’ or ‘1’ characters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;There are no leading zeros (except for the single digit “0” itself).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Test Case:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Input: &lt;code&gt;a = "11"&lt;/code&gt;, &lt;code&gt;b = "1"&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Expected Output: “100” (Equivalent to 4 in decimal)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. Code
&lt;/h3&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;binToInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;char&lt;/span&gt; &lt;span class="n"&gt;a&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;a&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sc"&gt;'1'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;calculateSumCarryRes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;carry&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;arrSum&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;res&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;sum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arrSum&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;carry&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;carry&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;to_string&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sum&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="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="nf"&gt;addBinary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&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;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&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="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;length&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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;carry&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;while&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;gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;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="n"&gt;calculateSumCarryRes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;carry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;binToInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&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="n"&gt;binToInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&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;res&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="p"&gt;;&lt;/span&gt;
      &lt;span class="n"&gt;j&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="k"&gt;while&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;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="n"&gt;calculateSumCarryRes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;carry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;binToInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&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;res&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="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&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;j&lt;/span&gt; &lt;span class="o"&gt;&amp;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="n"&gt;calculateSumCarryRes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;carry&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;binToInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&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;res&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;--&lt;/span&gt;&lt;span class="p"&gt;;&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;carry&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;to_string&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;carry&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;res&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;res&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;""&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="s"&gt;"0"&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;res&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;
  
  
  3. Logic Behind Solving the Problem
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Overflow errors will come in case we try to convert the binary strings to decimal numbers =&amp;gt; add those =&amp;gt; convert the sum to a binary string and return it&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We solve this problem by simulating the manual addition process used for decimal numbers. However, since we’re dealing with binary (only 0s and 1s), the process is slightly different. Here’s the core logic:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Convert characters to numbers:&lt;/strong&gt; We need to convert the binary characters (‘0’ or ‘1’) to their corresponding numerical values (0 or 1).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Add corresponding digits:&lt;/strong&gt; Add the current digits from both strings and handle carry-over.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Carry-over logic:&lt;/strong&gt; If the sum of two digits is greater than or equal to 2, there’s a carry-over of 1 to the next digit. In binary, any value greater than 1 results in a carry-over.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Build the result string:&lt;/strong&gt; Append the remainder of the sum (either 0 or 1) to the beginning of the result string. Since we’re adding digits in reverse order (starting from the least significant bit), this builds the result correctly.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4. Detailed Explanation of the Code (Line by Line)
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;a. Helper Functions:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;binToInt(char a)&lt;/code&gt;&lt;strong&gt;:&lt;/strong&gt; This function takes a character (&lt;code&gt;a&lt;/code&gt;) as input and returns 1 if it's '1', otherwise it returns 0. It simply converts the binary character to its numerical value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;calculateSumCarryRes(int&amp;amp; carry, int arrSum, string&amp;amp; res)&lt;/code&gt;&lt;strong&gt;:&lt;/strong&gt; This function calculates the sum, carry, and result digit for a single addition step.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;i) It takes three arguments by reference: &lt;code&gt;carry&lt;/code&gt; (integer to store carry-over), &lt;code&gt;arrSum&lt;/code&gt; (the sum of current digit values), and &lt;code&gt;res&lt;/code&gt; (string to store the result).&lt;/p&gt;

&lt;p&gt;ii) It calculates the total sum by adding &lt;code&gt;carry&lt;/code&gt; and &lt;code&gt;arrSum&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;iii) It updates the &lt;code&gt;carry&lt;/code&gt; value by dividing the &lt;code&gt;sum&lt;/code&gt; by 2 (since we're in binary).&lt;/p&gt;

&lt;p&gt;iv) It appends the remainder of the &lt;code&gt;sum&lt;/code&gt; divided by 2 (which will be 0 or 1) to the beginning of the &lt;code&gt;res&lt;/code&gt; string using &lt;code&gt;to_string&lt;/code&gt; and the &lt;code&gt;+&lt;/code&gt; operator.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;b. Main Function:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;addBinary(string a, string b)&lt;/code&gt;&lt;strong&gt;:&lt;/strong&gt; This is the main function that handles the entire binary addition process.&lt;/p&gt;

&lt;p&gt;Initialization:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Initializes an empty string &lt;code&gt;res&lt;/code&gt; to store the final result.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Creates variables &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt; as pointers to iterate through the last characters (indices) of strings &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;, respectively.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Initializes &lt;code&gt;carry&lt;/code&gt; to 0 to handle potential carry-over from the addition process.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Main While loop:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Uses a &lt;code&gt;while&lt;/code&gt; loop that iterates as long as both &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt; are within the valid range of their respective strings (i.e., not negative):&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Calls the &lt;code&gt;calculateSumCarryRes&lt;/code&gt; function to calculate the sum, carry, and append the result digit to &lt;code&gt;res&lt;/code&gt;. This essentially adds the corresponding digits from both strings and handles carry-over.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Decrements &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt; to move on to the next characters in the strings.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Additional while loops for input strings of different sizes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The first loop iterates through the remaining characters of &lt;code&gt;a&lt;/code&gt; (if &lt;code&gt;i&lt;/code&gt; is still positive) using the same logic as the main loop (calling &lt;code&gt;calculateSumCarryRes&lt;/code&gt;). This adds any remaining digits from the longer string &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The second loop iterates through the remaining characters of &lt;code&gt;b&lt;/code&gt; (if &lt;code&gt;j&lt;/code&gt; is still positive) using the same logic (calling &lt;code&gt;calculateSumCarryRes&lt;/code&gt;). This adds any remaining digits from the longer string &lt;code&gt;b&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Handling carry over:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If there’s a carry-over left after processing all the digits (&lt;code&gt;carry&lt;/code&gt; is not 0), it's appended to the beginning of &lt;code&gt;res&lt;/code&gt; using &lt;code&gt;to_string&lt;/code&gt; and the &lt;code&gt;+&lt;/code&gt; operator.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Edge case handling:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;At the end lies a ternary operator that checks if &lt;code&gt;res&lt;/code&gt; is empty (meaning both input strings were "0"). If so, it returns "0" to ensure a valid output (empty string is not be the expected output behaviour).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5. Walkthrough of the Code for a Test Case
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Input:&lt;/strong&gt;&lt;code&gt;a = "11"&lt;/code&gt;, &lt;code&gt;b = "1"&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step-by-Step Breakdown:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initialization:&lt;/strong&gt;&lt;code&gt;res&lt;/code&gt; is empty, &lt;code&gt;i = 1&lt;/code&gt; (pointing to the last character of "11"), &lt;code&gt;j = 0&lt;/code&gt; (pointing to the last character of "1"), &lt;code&gt;carry = 0&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Main Loop:&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Iteration 1:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Add &lt;code&gt;binToInt(a[i])&lt;/code&gt; (1) and &lt;code&gt;binToInt(b[j])&lt;/code&gt; (1), resulting in a sum of 2.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since the sum is greater than or equal to 2, there’s a carry-over of 1 (&lt;code&gt;carry&lt;/code&gt; is updated to 1).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The remainder of the sum divided by 2 (which is 0) is appended to &lt;code&gt;res&lt;/code&gt; (initially empty, becomes "0").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Decrement &lt;code&gt;i&lt;/code&gt; and &lt;code&gt;j&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Remaining Digits of&lt;/strong&gt;&lt;code&gt;a&lt;/code&gt;&lt;strong&gt;:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Add &lt;code&gt;binToInt(a[i])&lt;/code&gt; (1) and &lt;code&gt;carry&lt;/code&gt; (1), resulting in a sum of 2.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Similar to the previous iteration, carry-over is 1 and the remainder (0) is appended to &lt;code&gt;res&lt;/code&gt; (becomes "00").&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Decrement &lt;code&gt;i&lt;/code&gt;. Since &lt;code&gt;j&lt;/code&gt; is already -1 (out of bounds), the second while loop for remaining digits of &lt;code&gt;b&lt;/code&gt; is skipped.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Carry-Over Handling:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Since &lt;code&gt;carry&lt;/code&gt; is still 1 after processing all digits, it's appended to the beginning of &lt;code&gt;res&lt;/code&gt; resulting in the final output: &lt;code&gt;res = "100"&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt; “100” (Equivalent to 4 in decimal)&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Real-Life Applications of this Problem
&lt;/h3&gt;

&lt;p&gt;While adding binary strings might seem like a theoretical exercise, it has several practical applications in the world of computers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Computer Arithmetic:&lt;/strong&gt; Binary addition forms the core of arithmetic operations in computers. CPUs use binary addition circuits to perform calculations like addition, subtraction, multiplication, and division on binary numbers representing data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Error Detection and Correction:&lt;/strong&gt; Communication protocols often employ techniques like checksums or parity bits to detect errors during data transmission. These techniques rely on binary addition to create a redundant value that can be compared to the received data to identify inconsistencies.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Computer Graphics:&lt;/strong&gt; Binary addition plays a role in various aspects of computer graphics, such as color representation and image manipulation. Algorithms for blending colors or manipulating pixel values often involve binary addition operations.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By understanding binary addition, we gain a deeper insight into how computers perform calculations, handle data, and implement various functionalities. It’s a foundational concept in computer science and essential for anyone interested in how computers work at the core level.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Conclusion
&lt;/h3&gt;

&lt;p&gt;This blog post has explored the challenge of adding binary strings in C++. I have broken down the problem statement, code, logic, and real-world applications. Feel free to experiment with different test cases and challenge yourself further!&lt;/p&gt;

&lt;p&gt;If you liked this post, do applaude this story by clicking on the clap hands button and follow me &lt;a href="https://medium.com/@subhradeep_saha" rel="noopener noreferrer"&gt;https://medium.com/@subhradeep_saha&lt;/a&gt;. You can checkout my other Leetcode problem explanation posts in my profile page.&lt;/p&gt;

&lt;p&gt;Do let me know in the comments in case of any feedback you have for the article. Thanks!&lt;/p&gt;

</description>
      <category>binary</category>
      <category>leetcode</category>
      <category>string</category>
      <category>maths</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily - Day 7 | Array Partition I</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Mon, 06 May 2024 02:30:00 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-7-array-partition-i-2n11</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-7-array-partition-i-2n11</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-7-array-partition-i-2d915d787469" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fda%3Atrue%2Fresize%3Afill%3A88%3A88%2F0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-7-array-partition-i-2d915d787469" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 7 | Array Partition I | by Subhradeep Saha | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 6, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fmedium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;p&gt;Here is the Leetcode problem link — &lt;a href="https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1154/" rel="noopener noreferrer"&gt;Array Partition I&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  &lt;strong&gt;Problem Statement&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;LeetCode presents a challenge where you’re given an integer array &lt;code&gt;nums&lt;/code&gt; containing &lt;code&gt;2n&lt;/code&gt; elements. The objective is to group these elements into &lt;code&gt;n&lt;/code&gt; pairs, where &lt;code&gt;n&lt;/code&gt; is half the array size. Each pair consists of two elements (&lt;code&gt;(a_i, b_i)&lt;/code&gt;) from the array. The goal is to maximize the sum obtained by adding the minimum value (&lt;code&gt;min(a_i, b_i)&lt;/code&gt;) within each pair.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&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="nl"&gt;Input:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&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;4&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;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation: There are three possible pairings:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;(1, 4), (2, 3): Sum of minimums = 1 + 2 = 3&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;(1, 3), (2, 4): Sum of minimums = 1 + 2 = 3&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;(1, 2), (3, 4): Sum of minimums = 1 + 3 = 4&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The optimal pairing is (1, 2) and (3, 4), resulting in a maximum sum of 4.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Constraints:&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The number of pairs (&lt;code&gt;n&lt;/code&gt;) ranges from 1 to 10^4.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The array size (&lt;code&gt;nums.length&lt;/code&gt;) is always even (&lt;code&gt;2n&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Individual elements in the array (&lt;code&gt;nums[i]&lt;/code&gt;) can range from -10^4 to 10^4.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;High level approach&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The problem looks to be complex at first glance but if we analyse the pattern of the optimal pairs, for a pair — the larger number gets sacrificed for the smaller one. To maximize the sum, we need to have the least difference between the numbers of a pair — so that for a pair, we don’t sacrifice a much bigger number.&lt;/p&gt;

&lt;p&gt;Sorting helps us reduce the difference between the numbers of a pair and we ensure for every pair &lt;code&gt;(a_i, b_i)&lt;/code&gt; , &lt;code&gt;b_i&lt;/code&gt; is the least one that we sacrifice among all of the other numbers.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Code Implementation&lt;/strong&gt;
&lt;/h3&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;arrayPairSum&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="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="n"&gt;sort&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;begin&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;end&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;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="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="n"&gt;i&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="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;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="p"&gt;}&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;h3&gt;
  
  
  &lt;strong&gt;Breakdown of the Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Class and Function definition:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The code defines a class &lt;code&gt;Solution&lt;/code&gt; with a function &lt;code&gt;arrayPairSum&lt;/code&gt; that takes the integer array &lt;code&gt;nums&lt;/code&gt; as input and returns the maximized sum of minimum values in pairs.&lt;/p&gt;

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

&lt;p&gt;The &lt;code&gt;sort&lt;/code&gt; function is used to arrange all elements in the &lt;code&gt;nums&lt;/code&gt; array in ascending order. This step is crucial because we want to pair the smallest elements with the next larger elements to maximize the minimum value within each pair.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterating and Adding:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;An integer variable &lt;code&gt;ans&lt;/code&gt; is initialized to 0 to store the accumulated sum.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A &lt;code&gt;for&lt;/code&gt; loop iterates through the sorted array &lt;code&gt;nums&lt;/code&gt; with a step size of 2 (&lt;code&gt;i += 2&lt;/code&gt;). This step size ensures we only consider the first element (minimum value) from each pair.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inside the loop, the value at the current index &lt;code&gt;i&lt;/code&gt; (the minimum value in the current pair) is added to the &lt;code&gt;ans&lt;/code&gt; variable.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Returning the Sum:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;After iterating through all pairs, the final value of &lt;code&gt;ans&lt;/code&gt; represents the maximized sum of minimum values, which is returned by the function.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Dry Run with a Test Case&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let’s use the provided example:&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="nl"&gt;Input:&lt;/span&gt; &lt;span class="n"&gt;nums&lt;/span&gt; &lt;span class="o"&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;4&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;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sorting:&lt;/strong&gt; First, the array is sorted: &lt;code&gt;[1, 2, 3, 4]&lt;/code&gt;.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Loop starts at &lt;code&gt;i = 0&lt;/code&gt; (index of the first element, which is 1).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;ans&lt;/code&gt; is incremented by &lt;code&gt;nums[i]&lt;/code&gt; (1).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Loop continues to &lt;code&gt;i = 2&lt;/code&gt; (index of the third element, which is 3).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;ans&lt;/code&gt; is again incremented by &lt;code&gt;nums[i]&lt;/code&gt; (3).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The loop terminates as it has considered all pairs (first and third elements).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Result:&lt;/strong&gt; The final value of &lt;code&gt;ans&lt;/code&gt; is 4 (1 + 3) — 1 from the first pair and 3 from the second pair. This matches the expected output for the given test case.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Real-World Applications&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This concept of maximizing the minimum value in pairings can be applied in various real-world scenarios:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resource Allocation:&lt;/strong&gt; When assigning resources (like budget, personnel, or materials) to multiple tasks or projects, this approach can help ensure that even the least-resourced projects receive enough to function at a base level, maximizing overall efficiency.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Inventory Management:&lt;/strong&gt; In managing inventory, prioritizing the sale of items with the lowest profit margin alongside items with higher margins can help clear out slow-moving stock while still generating some revenue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Network Optimization:&lt;/strong&gt; In network routing algorithms, this strategy can be used to ensure that even the least efficient connections (with lower bandwidth) are paired with connections with higher bandwidth, optimizing overall network traffic flow.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This blog post explored the LeetCode challenge of maximizing the sum of minimum values in pairs. We tackled the problem statement by getting to understand how sorting helps in solving the problem, presented and explained the C++ code, performed a dry run with a test case and discussed a few real-world applications of this problem.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resource Allocation:&lt;/strong&gt; &lt;a href="https://www.pmi.org/learning/library/resource-allocation-5304" rel="noopener noreferrer"&gt;https://www.pmi.org/learning/library/resource-allocation-5304&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Inventory Management:&lt;/strong&gt; &lt;a href="https://www.investopedia.com/bullwhip-effect-definition-5499228" rel="noopener noreferrer"&gt;https://www.investopedia.com/bullwhip-effect-definition-5499228&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Network Optimization:&lt;/strong&gt; &lt;a href="https://en.wikipedia.org/wiki/Category:Routing_algorithms" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Category:Routing_algorithms&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cover Photo by &lt;a href="https://unsplash.com/@nhillier?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash" rel="noopener noreferrer"&gt;Nick Hillier&lt;/a&gt; &lt;a href="https://unsplash.com/@nhillier?utm_content=creditCopyText&amp;amp;utm_medium=referral&amp;amp;utm_source=unsplash" rel="noopener noreferrer"&gt;on Unsplash&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;If you liked this post, do applaude the post by clicking on the clap hands icon and follow me &lt;a href="https://medium.com/@subhradeep_saha" rel="noopener noreferrer"&gt;https://medium.com/@subhradeep_saha&lt;/a&gt; as well. Do checkout my other posts in my profile and let me know if you have any feedback. Thanks!&lt;/p&gt;

</description>
      <category>array</category>
      <category>cpp</category>
      <category>leetcode</category>
      <category>sort</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 3: Spiral Matrix</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Sun, 05 May 2024 18:30:00 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-3-spiral-matrix-11kp</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-3-spiral-matrix-11kp</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-3-spiral-matrix-e225fa1f15a9" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c-2Ckuec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/da:true/resize:fill:88:88/0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-3-spiral-matrix-e225fa1f15a9" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 3: Spiral Matrix | by Subhradeep Saha | Apr, 2024 | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;Apr 28, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YjpYcCMa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/medium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;p&gt;Here is the Leetcode problem - &lt;a href="https://leetcode.com/explore/learn/card/array-and-string/202/introduction-to-2d-array/1168/"&gt;Spiral Matrix&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Problem Statement
&lt;/h2&gt;

&lt;p&gt;Given a two-dimensional matrix (matrix), where each element represents a number, the task is to write a function that returns a new list containing all the elements of the matrix traversed in a spiral order.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz1ps3hlcd3lfvzcdec4w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz1ps3hlcd3lfvzcdec4w.png" alt="Example 1" width="242" height="242"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



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

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Funnydsjqh19akceewhnm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Funnydsjqh19akceewhnm.png" alt="Example 2" width="322" height="242"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Constraints:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;m == matrix.length&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n == matrix[i].length&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1 &amp;lt;= m, n &amp;lt;= 10&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;-100 &amp;lt;= matrix[i][j] &amp;lt;= 100&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What We Want to Achieve
&lt;/h2&gt;

&lt;p&gt;This problem aims to develop a function that iterates through a matrix in a specific pattern, ensuring:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Every element is visited once&lt;/strong&gt;: No number in the matrix is left untouched.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Spiral Path&lt;/strong&gt;: The traversal follows a clockwise spiral path, starting from the top-left corner and gradually moving inwards.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resultant List&lt;/strong&gt;: The function returns a new list containing all the elements of the matrix in the order they were visited during the spiral traversal.&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;Here’s the complete C++ code that tackles this challenge:&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;void&lt;/span&gt; &lt;span class="n"&gt;traverse&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="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;res&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;i&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="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;r&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;c&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;idx&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="n"&gt;idx&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="n"&gt;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;idx&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="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;abs&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;idx&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&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;idx&lt;/span&gt;&lt;span class="p"&gt;]);&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;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;101&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="n"&gt;idx&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;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;idx&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="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;abs&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;idx&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&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;idx&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]);&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;idx&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;101&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="n"&gt;idx&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;c&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;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;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;idx&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="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;abs&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;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&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;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]);&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;r&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;101&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="n"&gt;idx&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;r&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;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;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;idx&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="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;abs&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;idx&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="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;push_back&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;idx&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="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;idx&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="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;101&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="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;&lt;/span&gt; &lt;span class="n"&gt;spiralOrder&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="p"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;m&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="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="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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;m&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;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;n&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;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;j&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;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;&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;;&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;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&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;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;traverse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res&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;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;c&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="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;c&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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&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;
  
  
  Decoding the Code: Step-by-Step Breakdown
&lt;/h2&gt;

&lt;p&gt;The code is divided into two main functions:&lt;/p&gt;

&lt;p&gt;a) &lt;code&gt;spiralOrder&lt;/code&gt; (Public Function):&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;It retrieves the matrix dimensions (m for rows, n for columns).&lt;/li&gt;
&lt;li&gt;It initializes variables representing the boundaries &lt;code&gt;(i, j, r, c)&lt;/code&gt; for the entire matrix (top-left and bottom-right corners).&lt;/li&gt;
&lt;li&gt;It creates a result vector (&lt;code&gt;res&lt;/code&gt;) to store the elements in spiral order&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Looping Through Layers:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It employs a while loop that continues as long as both &lt;code&gt;i&lt;/code&gt; (top row) is less than or equal to &lt;code&gt;r&lt;/code&gt; (bottom row) and &lt;code&gt;j&lt;/code&gt; (leftmost column) is less than or equal to c (rightmost column). This ensures the loop iterates until all elements within the matrix boundaries are processed.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Traverse a Layer&lt;/u&gt;: Inside the loop, it calls the helper function traverse with the current boundaries (&lt;code&gt;i, j, r, c&lt;/code&gt;) and the result vector (&lt;code&gt;res&lt;/code&gt;). This call essentially processes a single layer of the spiral within the specified boundaries.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Update Boundaries&lt;/u&gt;: After traversing a layer, the loop updates the boundaries (&lt;code&gt;i, j, r, c&lt;/code&gt;) by incrementing i and &lt;code&gt;j&lt;/code&gt; (moving inwards) and decrementing &lt;code&gt;r&lt;/code&gt; and &lt;code&gt;c&lt;/code&gt; (shrinking the remaining area). This effectively prepares the boundaries for the next layer of the spiral.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;b) &lt;code&gt;traverse&lt;/code&gt; (Helper Function):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;u&gt;Logic for Traversing a Single Layer&lt;/u&gt;: It takes the matrix (&lt;code&gt;matrix&lt;/code&gt;), boundaries (&lt;code&gt;i, j, r, c&lt;/code&gt;) representing the current layer's top-left and bottom-right corners, and the result vector (&lt;code&gt;res&lt;/code&gt;) to store the elements in spiral order.(matrix[i][j] will be the starting element for 1 traverse)&lt;/li&gt;
&lt;li&gt;Looping Through Elements: It uses four for loops, each iterating through an index (&lt;code&gt;idx&lt;/code&gt;) to visit the elements in the current layer:&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;u&gt;Move Right (First Row)&lt;/u&gt;: The first loop iterates from &lt;code&gt;j&lt;/code&gt; (leftmost column) to &lt;code&gt;c&lt;/code&gt; (rightmost column) in the current row (i). It checks if the element &lt;code&gt;matrix[i][idx]&lt;/code&gt; is unvisited (absolute value less than or equal to 100) using &lt;code&gt;abs(matrix[i][idx]) &amp;lt;= 100&lt;/code&gt;. If unvisited, it adds the element to the res vector and marks it as visited by assigning a high value (101) to &lt;code&gt;matrix[i][idx]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Move Down (Last Column)&lt;/u&gt;: Similar to the first loop, this iteration goes from &lt;code&gt;i+1&lt;/code&gt; (the row below the first row) to r (bottommost row) in the current rightmost column (c). It follows the same logic of checking for unvisited elements and adding them to the result with a visit mark.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Move Left (Last Row)&lt;/u&gt;: This loop iterates from &lt;code&gt;c-1&lt;/code&gt; (one column before the last) to &lt;code&gt;j&lt;/code&gt; (leftmost column) in the bottom row (&lt;code&gt;r&lt;/code&gt;). It checks and adds unvisited elements.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Move Up (First Column)&lt;/u&gt;: The final loop iterates from &lt;code&gt;r-1&lt;/code&gt; (one row above the bottom row) to &lt;code&gt;i-1&lt;/code&gt; (1 row below the topmost row) in the current leftmost column (&lt;code&gt;j&lt;/code&gt;). It uses the same logic for checking, adding, and marking visited elements.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Key Points:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The traverse function ensures that elements are visited only once by checking if their absolute value is less than or equal to 100 (since in the constraints it is mentioned that items of the matrix are in the range [-100, 100]). Marking visited elements with a high value (101) prevents revisiting them.&lt;/li&gt;
&lt;li&gt;The spiralOrder function progressively shrinks the boundaries (&lt;code&gt;i, j, r, c&lt;/code&gt;) as it processes each layer, effectively spiralling inwards until all elements are captured.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Testing the Code
&lt;/h2&gt;

&lt;p&gt;Let’s delve into some test cases to solidify our understanding of how the provided C++ code accomplishes the spiral order traversal:&lt;/p&gt;

&lt;h3&gt;
  
  
  Test Case 1: Basic Spiral
&lt;/h3&gt;



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

Expected output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;ol&gt;
&lt;li&gt;
&lt;u&gt;Initialization&lt;/u&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;The code retrieves the matrix dimensions (3 rows, 3 columns).&lt;/li&gt;
&lt;li&gt;It sets boundaries (&lt;code&gt;i = 0, j = 0, r = 2, c = 2&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;An empty result vector (&lt;code&gt;res&lt;/code&gt;) is created.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;u&gt;Looping Through Layers&lt;/u&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The while loop starts (i &amp;lt;= r and j &amp;lt;= c are true).&lt;br&gt;
a) &lt;em&gt;First Layer Traversal&lt;/em&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The traverse function is called with boundaries (&lt;code&gt;i = 0, j = 0, r = 2, c = 2&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;It iterates through the first row (elements 1, 2, 3) from left to right, adding them to res and marking them visited.&lt;/li&gt;
&lt;li&gt;It moves down the rightmost column (element 6), adding it to res and marking it visited.&lt;/li&gt;
&lt;li&gt;It iterates through the last row (elements 9, 8) from right to left, adding them to res and marking them visited.&lt;/li&gt;
&lt;li&gt;It moves up the leftmost column (element 7), adding it to res and marking it visited.&lt;/li&gt;
&lt;li&gt;After traversing the first layer, &lt;code&gt;res&lt;/code&gt; becomes &lt;code&gt;[1, 2, 3, 6, 9, 8]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Boundaries are updated (&lt;code&gt;i = 1, j = 1, r = 1, c = 1&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;b) &lt;em&gt;Second Layer Traversal&lt;/em&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The loop iterates again (&lt;code&gt;i &amp;lt;= r&lt;/code&gt; and &lt;code&gt;j &amp;lt;= c&lt;/code&gt; are still &lt;code&gt;true&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;The traverse function is called with the updated boundaries.&lt;/li&gt;
&lt;li&gt;It tries to iterate through the top row (element 4) but finds it already visited.&lt;/li&gt;
&lt;li&gt;It moves down the rightmost column (no element present).&lt;/li&gt;
&lt;li&gt;It tries to iterate through the bottom row (element 5) but finds it already visited.&lt;/li&gt;
&lt;li&gt;It moves up the leftmost column (no element present).&lt;/li&gt;
&lt;li&gt;Since no new elements were found, this layer traversal effectively ends.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;c) &lt;u&gt;Loop Termination&lt;/u&gt;:&lt;/p&gt;

&lt;p&gt;After the second layer, &lt;code&gt;i&lt;/code&gt; (now 1) is greater than r (now 1), and the while loop terminates.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;u&gt;Return Result&lt;/u&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The function returns the final res vector containing the spiral order traversal: &lt;code&gt;[1, 2, 3, 6, 9, 8, 7, 4, 5]&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Test Case 2: Rectangular Matrix
&lt;/h3&gt;



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

&lt;/div&gt;



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

&lt;p&gt;This case follows similar logic to the first test case, but with fewer layers due to the rectangular shape. The code will traverse the elements in a spiral pattern, starting from the top-left corner and moving inwards until all elements are visited.&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-World Applications: Beyond the Classroom
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Image Processin&lt;/strong&gt;g: When dealing with digital images represented as matrices (pixels as elements), spiral order traversal can be used for efficient image compression techniques. By prioritizing central pixels that often contain crucial image information, this approach can achieve better compression ratios.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Mining&lt;/strong&gt;: When analyzing large datasets represented as matrices, spiral order traversal can be used to prioritize processing central elements that might hold more valuable or statistically significant information compared to the edges.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are just a few examples, and the specific applications can vary depending on the software and its purpose. However, the core concept of efficiently iterating through a matrix in a spiral pattern proves valuable in various real-world scenarios.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We’ve successfully navigated the challenge of finding the spiral order traversal in a matrix! This problem not only tested our understanding of matrix manipulation and loops but also introduced a valuable concept with practical applications. By combining clear explanations, code breakdown, and real-world examples, I have hopefully provided a comprehensive guide to tackling this spiral adventure.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Solving a Leetcode problem daily — Day 2: Plus One</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Sat, 04 May 2024 18:30:00 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-2-plus-one-2da2</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-2-plus-one-2da2</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-2-plus-one-a77a96759794" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fda%3Atrue%2Fresize%3Afill%3A88%3A88%2F0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-2-plus-one-a77a96759794" class="ltag__link__link" rel="noopener noreferrer"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 2: Plus One | by Subhradeep Saha | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 5, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fmedium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;p&gt;Here is the Leetcode problem - &lt;a href="https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1148/" rel="noopener noreferrer"&gt;Plus One&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Problem Statement
&lt;/h2&gt;

&lt;p&gt;Imagine you have a very large number stored as an array of digits, where each element in the array represents a single digit of the number. The digits are arranged in big-endian order, meaning the most significant digit (leftmost) is at index 0, and the least significant digit (rightmost) is at the last index. Additionally, there are no leading zeros in this number (according to the constraints).&lt;/p&gt;

&lt;p&gt;The challenge is to write a function that takes this array of digits representing a large integer and increments the number by 1. The function should then return a new vector containing the digits of the incremented number.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The input array (digits) will have a size between 1 and 100 (inclusive).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Each element (digits[i]) of the array will be a digit between 0 and 9 (inclusive).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;There will be no leading zeros in the input array.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Understanding the Solution
&lt;/h2&gt;

&lt;p&gt;Here’s a breakdown of the C++ code to solve this problem, explained line by line:&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="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;&lt;/span&gt; &lt;span class="n"&gt;plusOne&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="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digits&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;idx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;digits&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="mi"&gt;1&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;carry&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="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;carry&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;sum&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&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="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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;digits&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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="n"&gt;carry&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx&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="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;digits&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;carry&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;digits&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;p&gt;Breakdown of the Code:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Function Definition:&lt;/strong&gt;&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="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;&lt;/span&gt; &lt;span class="n"&gt;plusOne&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="kt"&gt;int&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;digits&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;This function takes a reference to a vector of integers (digits) representing the large integer and returns a new vector containing the digits of the incremented number.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Initialization:&lt;/strong&gt;&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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;idx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;digits&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="mi"&gt;1&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;carry&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;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We get the last index of the digits array and store it in idx. This will be used for iterating through the digits in reverse order.&lt;br&gt;
We initialize a variable carry to 1, representing the increment value we want to add.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Carry-Over Logic:&lt;/strong&gt;&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;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt; &lt;span class="o"&gt;&amp;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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;carry&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;sum&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&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="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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;digits&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
      &lt;span class="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;idx&lt;/span&gt;&lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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="n"&gt;carry&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sum&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;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;}&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;u&gt;Looping and Sum&lt;/u&gt;: We use a while loop to iterate through the digits array as long as idx is not negative (i.e., we haven't reached the beginning of the array). Inside the loop, we calculate the sum by adding the current digit (digits[idx]) and the carry.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Early Return (No Carry-Over)&lt;/u&gt;: If the sum is less than 10, it means there's no carry-over needed. We update the current digit (digits[idx]) with the sum and directly return the modified digits vector.&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Updating Digit and Carry-Over&lt;/u&gt;: If the sum is 10 or greater, it signifies a carry-over. We update the current digit (digits[idx]). We use the modulo operator (%) to extract the digit at the current position (sum % 10). This digit is placed back into the corresponding element of the digits array.&lt;/li&gt;
&lt;li&gt;We calculate the carry-over value (sum / 10) using integer division. This value is stored in the carry variable for the next iteration.&lt;/li&gt;
&lt;li&gt;We decrement idx to move to the previous digit in the next iteration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Overflow Case:&lt;/strong&gt;&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;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;idx&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="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="n"&gt;digits&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;digits&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;carry&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;digits&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;u&gt;Overflow Check&lt;/u&gt;: If the loop finishes iterating without returning (meaning idx becomes -1), it signifies an overflow case. This happens when the original number is so large that incrementing it by 1 requires an extra digit at the beginning (most significant position).&lt;/li&gt;
&lt;li&gt;
&lt;u&gt;Adding a New Digit&lt;/u&gt;: To handle this, we use the insert function of the vector class. We insert the carry value (which is 1 in this case) at the beginning (digits.begin()) of the digits vector. This effectively adds a new digit to the most significant position.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Test Cases&lt;br&gt;
Let’s see how the code works with different input scenarios:&lt;/p&gt;

&lt;p&gt;Test Case 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;digits = [1,2,3]
Expected Output: [1,2,4]
Explanation: Adding 1 to 123 results in 124. The code iterates through the digits, updates them accordingly, and no overflow occurs.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Test Case 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;digits = [9]
Expected Output: [1,0]
Explanation: Adding 1 to 9 results in 10. The code handles the carry-over, updates the digit to 0 in the original array, and no overflow occurs.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Test Case 3:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;digits = [9,9]
Expected Output: [1,0,0]
Explanation: Adding 1 to 99 results in 100. The code handles the carry-over twice, updating digits to 0 and adding a new digit (1) at the beginning to accommodate the overflow.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Real life applications of the problem
&lt;/h2&gt;

&lt;p&gt;The concept of incrementing large integers represented as arrays of digits has various applications in the software world, here are a few examples:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Financial Transactions:&lt;/strong&gt;&lt;br&gt;
In finance systems, large numbers representing money amounts are often stored as arrays of digits for efficiency. When processing transactions that involve adding or subtracting money, incrementing or decrementing these arrays becomes necessary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Counters and Statistics:&lt;/strong&gt;&lt;br&gt;
Many applications use counters to track various events or metrics. These counters can be represented as arrays of digits, especially when dealing with very large numbers. Incrementing these counters involves manipulating the digits in the array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Large Number Arithmetic:&lt;/strong&gt;&lt;br&gt;
Libraries or custom functions for performing arbitrary precision arithmetic (calculations with very large numbers) might use arrays of digits to represent the operands (numbers involved in the calculation). Incrementing a number in such a library would involve manipulating the digit array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Big Data Processing:&lt;/strong&gt;&lt;br&gt;
In big data processing, large datasets may contain numerical values like timestamps, user IDs, or counts. These values can be stored efficiently in arrays of digits. When iterating through such data and needing to update specific values (e.g., incrementing a count), the concept of incrementing digit arrays becomes relevant.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Cryptography:&lt;/strong&gt;&lt;br&gt;
Some cryptographic algorithms involve manipulating large integers. While not directly incrementing, these algorithms might require adding or subtracting large numbers, which could be implemented using digit array manipulation techniques similar to this problem.&lt;/p&gt;

&lt;p&gt;It’s important to note that in modern software development, libraries or frameworks often handle large number manipulation behind the scenes. However, understanding the underlying concepts, like incrementing digit arrays, can be valuable for low-level programming, performance optimizations, or simply for a deeper grasp of how computers handle large numbers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This C++ code efficiently increments a large integer represented as an array of digits by handling carry-over logic and potential overflow situations. By understanding the code and the test cases, you can now tackle similar problems that involve digit manipulation and array operations. Feel free to experiment with different input scenarios and challenge yourself further!&lt;/p&gt;

</description>
      <category>digits</category>
      <category>array</category>
      <category>cpp</category>
      <category>leetcode</category>
    </item>
    <item>
      <title>Solving a Leetcode problem daily - Day 1 | Pascal’s Triangle</title>
      <dc:creator>Subhradeep Saha</dc:creator>
      <pubDate>Sat, 04 May 2024 06:04:54 +0000</pubDate>
      <link>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-39d1</link>
      <guid>https://dev.to/subhradeep__saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-39d1</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;I have written this blog originally in Medium -&lt;/p&gt;
&lt;/blockquote&gt;


&lt;div class="ltag__link"&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-b9ea47250985" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c-2Ckuec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://miro.medium.com/v2/da:true/resize:fill:88:88/0%2AeHNmkooCR5yO6siP" alt="Subhradeep Saha"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://medium.com/@subhradeep_saha/solving-a-leetcode-problem-daily-day-1-pascals-triangle-b9ea47250985" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Solving a Leetcode problem daily — Day 1: Pascal’s Triangle | by Subhradeep Saha | Apr, 2024 | Medium&lt;/h2&gt;
      &lt;h3&gt;Subhradeep Saha ・ &lt;time&gt;May 3, 2024&lt;/time&gt; ・ 
      &lt;div class="ltag__link__servicename"&gt;
        &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YjpYcCMa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev.to/assets/medium-f709f79cf29704f9f4c2a83f950b2964e95007a3e311b77f686915c71574fef2.svg" alt="Medium Logo"&gt;
        Medium
      &lt;/div&gt;
    &lt;/h3&gt;
&lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;





&lt;p&gt;&lt;strong&gt;Here is the Leetcode problem&lt;/strong&gt; - &lt;a href="https://leetcode.com/explore/learn/card/array-and-string/202/introduction-to-2d-array/1170/"&gt;Pascal's Triangle&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  What is Pascal’s Triangle?
&lt;/h2&gt;

&lt;p&gt;Imagine a pyramid of numbers where each element is the sum of the two numbers directly above it. That’s Pascal’s Triangle! Here’s a look at the first few rows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzjizkupw3udi8wn7zwa5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzjizkupw3udi8wn7zwa5.png" alt="https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif" width="260" height="240"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As you can see, the first row always starts with a 1, and each subsequent row is built by adding the elements above it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The LeetCode Challenge
&lt;/h2&gt;

&lt;p&gt;The LeetCode challenge asks us to write a function that takes an integer numRows and returns the first numRows rows of Pascal's Triangle.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Solution
&lt;/h2&gt;

&lt;p&gt;Complete Code:&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="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;&lt;/span&gt; &lt;span class="n"&gt;generate&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;numRows&lt;/span&gt;&lt;span class="p"&gt;)&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;&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numRows&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;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;numRows&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="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="mi"&gt;0&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;i&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;++&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;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;i&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;res&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="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;-&lt;/span&gt; &lt;span class="mi"&gt;1&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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&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;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&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;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;res&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="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="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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sum&lt;/span&gt; &lt;span class="o"&gt;=&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="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&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="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;1&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="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;res&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;push_&lt;/span&gt; &lt;span class="n"&gt;back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sum&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="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&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;p&gt;Here’s a breakdown of the C++ code into sections:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Class and Function Definition:&lt;/strong&gt;&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="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;&lt;/span&gt; &lt;span class="n"&gt;generate&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;numRows&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;This code defines a class Solution with a public function named generate. This function takes an integer &lt;code&gt;numRows&lt;/code&gt; as input and is designed to return a 2D vector of integers representing Pascal's Triangle.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Result Initialization:&lt;/strong&gt;&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="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;&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;numRows&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Here, we create a 2D vector named &lt;code&gt;res&lt;/code&gt;. This vector will have numRows rows, and it will be used to store the generated Pascal's Triangle. We are not initializing the number of columns here since the items will be pushed dynamically inside of the loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Nested Loops for Iterating Through the Triangle:&lt;/strong&gt;&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;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;numRows&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="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="mi"&gt;0&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;i&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;++&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;We use two nested loops to iterate through each element of the resulting triangle. The outer loop (i) iterates through each row (0 to numRows-1). The inner loop (j) iterates through each element (0 to i) within the current row.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Explanation of the Loops:&lt;/u&gt;&lt;br&gt;
These loops ensure we visit each element in the 2D vector exactly once. The outer loop (i) progresses row by row, while the inner loop (j) fills the elements within each row. Since Pascal's Triangle has a specific structure where elements rely on previous rows, this nested loop approach is ideal for building it efficiently.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Next Steps:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;In the next section, we’ll delve into how the code calculates the value for each element in the triangle using these loops.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Calculating Element Values:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The core functionality of the code lies within the inner loop:&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="kt"&gt;int&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;i&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;j&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;res&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="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;-&lt;/span&gt; &lt;span class="mi"&gt;1&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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt; &lt;span class="o"&gt;=&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;gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&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;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;res&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="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="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="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sum&lt;/span&gt; &lt;span class="o"&gt;=&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="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&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="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;1&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="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;res&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;push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;u&gt;Understanding the Logic:&lt;/u&gt;&lt;br&gt;
&lt;code&gt;left&lt;/code&gt; and &lt;code&gt;right&lt;/code&gt; Variables:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;These variables represent the values needed to calculate the current element’s sum based on Pascal’s Triangle’s property.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;left: This stores the value from the element directly above and one position to the left. The ternary expression &lt;code&gt;(i &amp;gt;= 1 &amp;amp;&amp;amp; j &amp;gt;= 1) ? res[i - 1][j - 1] : 0)&lt;/code&gt; checks if we're not in the first row (i=0) or the first element (j=0) of any row. If valid, it accesses the element in the previous row using &lt;code&gt;res[i - 1][j - 1]&lt;/code&gt;. Otherwise, it sets left to 0 (since there's no element there).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;right: This stores the value from the element directly above. The ternary expression (&lt;code&gt;i &amp;gt;= 1 &amp;amp;&amp;amp; j &amp;lt; i&lt;/code&gt;) ensures we're not in the first row and j is within the current row's boundary (not the last element). If valid, it accesses the element above using &lt;code&gt;res[i - 1][j]&lt;/code&gt;. Otherwise, it sets right to 0.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;sum&lt;/code&gt; Calculation:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The sum variable holds the final value for the current element (i, j).&lt;/li&gt;
&lt;li&gt;The ternary expression &lt;code&gt;(left == 0 &amp;amp;&amp;amp; right == 0) ? 1 : left + right)&lt;/code&gt; calculates the sum. If both left and right are 0 (meaning we're at the first element of a row), we set sum to 1 (since the first element in each row is always 1). Otherwise, sum is calculated by adding left and right.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Adding the Value to the Result:&lt;/strong&gt;&lt;br&gt;
Finally, &lt;code&gt;res[i].push_back(sum)&lt;/code&gt; adds the calculated sum to the current row (&lt;code&gt;res[i]&lt;/code&gt;) of the result vector.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaway:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This logic leverages dynamic programming. By using previously calculated values (left and right from the previous row), the code efficiently builds the triangle element by element.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Next Steps:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;In the final section, we’ll see how this code works with different inputs and the complete solution.&lt;/p&gt;

&lt;p&gt;Now that we’ve explored the code’s building blocks, let’s see how it works with different inputs and how the pieces fit together to form the complete solution.&lt;/p&gt;

&lt;h2&gt;
  
  
  Test Cases and Explanation
&lt;/h2&gt;

&lt;p&gt;Let’s see the code in action with some test cases:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Test Case 1: &lt;code&gt;numRows = 1&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Output: [[1]]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Explanation:&lt;/u&gt; &lt;br&gt;
The first row of Pascal’s Triangle always has a single 1, and the code correctly handles this case using the logic for the first element (left and right become 0, so sum is set to 1).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Test Case 2: &lt;code&gt;numRows = 3&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Output: [[1], [1, 1], [1, 2, 1]]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Explanation:&lt;/u&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Row 1: We have only one element (1) as explained in Test Case 1.&lt;/li&gt;
&lt;li&gt;Row 2:
left for the first element (j=0) is 0 (since we're in the first column of row 2).
right (element directly above) is also 0 (since we're in row 2).
Therefore, sum becomes 1 (as both left and right are 0).
This process repeats for the second element (j=1) in row 2, where left becomes 1 (referring to the first element in row 1) and right is still 0. So, sum is 1 + 0 = 1.&lt;/li&gt;
&lt;li&gt;Row 3:
The calculation for the first element (j=0) follows the same logic as row 2, resulting in sum as 1.
For the second element (j=1), left is 1 (referring to the element above and to the left) and right is 1 (referring to the element directly above). So, sum is 1 + 1 = 2.
The calculation for the third element (j=2) uses left as 1 and right as 1, resulting in sum as 1 + 1 = 2.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This code effectively generates Pascal’s Triangle in C++ by leveraging dynamic programming and nested loops. By understanding the logic behind calculating element values and the role of each code section, you can now tackle this LeetCode problem and similar problems that involve building upon previously calculated results.&lt;/p&gt;

&lt;p&gt;Feel free to experiment with the code by changing the numRows value and observe how the triangle grows! Happy coding!&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>cpp</category>
      <category>leetcode</category>
      <category>pascaltriangle</category>
    </item>
  </channel>
</rss>
