<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kajol on Medium]]></title>
        <description><![CDATA[Stories by Kajol on Medium]]></description>
        <link>https://medium.com/@kajolmurmu29?source=rss-6bec78016e3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AN8LAW4_WFPvZ2---jUjYw.png</url>
            <title>Stories by Kajol on Medium</title>
            <link>https://medium.com/@kajolmurmu29?source=rss-6bec78016e3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:55:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kajolmurmu29/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LeetCode 238: product of Array Except self]]></title>
            <link>https://medium.com/@kajolmurmu29/leetcode-238-product-of-array-except-self-86b038785c27?source=rss-6bec78016e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b038785c27</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[suffix-sum]]></category>
            <category><![CDATA[prefix-sum]]></category>
            <dc:creator><![CDATA[Kajol]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 15:49:04 GMT</pubDate>
            <atom:updated>2025-11-24T15:49:04.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B--hBLnqAwTNzvdtNML75Q.png" /></figure><p>Given an integer array nums, return <em>an array</em> answer <em>such that</em> answer[i] <em>is equal to the product of all the elements of</em> nums <em>except</em> nums[i].</p><p>The product of any prefix or suffix of nums is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p><p>You must write an algorithm that runs in O(n) time and without using the division operation.</p><p><strong>Example 1:</strong></p><pre>Input: nums = [1,2,3,4]<br>Output: [24,12,8,6]</pre><h3>Brute Force:</h3><pre> class Solution {<br>     public int leftProduct(int idx, int nums[]){<br>         int left=1;<br>         for(int i=idx-1;i&gt;=0;i--){<br>             left*=nums[i];<br>         }<br>         return left;<br>     }<br><br>     public int rightProduct(int idx, int nums[]){<br>         int right=1;<br>         for(int i=idx+1;i&lt;nums.length;i++){<br>             right*=nums[i];<br>         }<br>         return right;<br>     }<br><br>     public int[] productExceptSelf(int[] nums) {<br>         int n=nums.length;<br>         int answer[]=new int[n];<br><br>         if(n==1) return nums;<br><br>         for(int i=0;i&lt;n;i++){<br>             int left=leftProduct(i,nums);<br>             int right=rightProduct(i,nums);<br>             int product=left*right;<br>             answer[i]=product;<br>         }<br>         return answer;<br>     }<br> }</pre><p>This solution works but it’s <strong>O(n²)</strong> because for every index i, you recompute the full left and right products using loops.</p><h3>Optimal Solution:</h3><p>For each position, the result is the product of all elements to the left <em>multiplied by</em> the product of all elements to the right.<br> Instead of recomputing these for each index, I build two running products: a prefix and a suffix.</p><p>In the first pass, I create an array where answer[i] stores the product of all numbers to the left of i. This is done with a single running multiplication that I update as I move forward</p><p>Then I do a second pass from right to left and maintain a running suffix product. As I move, I multiply the current suffix product with the prefix product already stored in answer[i].</p><p>This gives the final product except self.</p><pre>class Solution {<br>    public int[] productExceptSelf(int[] nums) {<br>        int n = nums.length;<br>        int[] answer = new int[n];<br><br>        // 1. Left product pass<br>        answer[0] = 1; <br>        for (int i = 1; i &lt; n; i++) {<br>            answer[i] = answer[i - 1] * nums[i - 1];<br>        }<br><br>        // 2. Right product pass<br>        int right = 1;<br>        for (int i = n - 1; i &gt;= 0; i--) {<br>            answer[i] = answer[i] * right;<br>            right *= nums[i];<br>        }<br><br>        return answer;<br>    }<br>}</pre><p>Till Then, Happ Coding :{ )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b038785c27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 1768: Merge Strings Alternatively]]></title>
            <link>https://medium.com/@kajolmurmu29/leetcode-1768-merge-strings-alternatively-a6c33a73e0da?source=rss-6bec78016e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6c33a73e0da</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[merge]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Kajol]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 09:18:04 GMT</pubDate>
            <atom:updated>2025-11-22T09:18:04.961Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8XoRpH4VTqVlaMGC0gYHw.png" /></figure><p>You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.</p><p>Return <em>the merged string.</em></p><p><strong>Example 1:</strong></p><pre>Input: word1 = &quot;abc&quot;, word2 = &quot;pqr&quot;<br>Output: &quot;apbqcr&quot;<br>Explanation: The merged string will be merged as so:<br>word1:  a   b   c<br>word2:    p   q   r<br>merged: a p b q c r</pre><h3>Approach</h3><p>The key idea is simple:</p><ul><li>Move through both strings simultaneously.</li><li>At each index i, append the character from word1 if available.</li><li>Then append the character from word2 if available.</li><li>Use a loop that continues until we’ve processed both strings completely.</li></ul><p>This makes the problem an ideal candidate for a <strong>while loop</strong>, since we continue iterating as long as either string has characters left.</p><h3>Java Solution:</h3><pre>class Solution {<br>    public String mergeAlternately(String word1, String word2) {<br>        StringBuilder result = new StringBuilder();<br>        int i = 0;<br><br>        // Loop while characters remain in either string<br>        while (i &lt; word1.length() || i &lt; word2.length()) {<br><br>            if (i &lt; word1.length()) {<br>                result.append(word1.charAt(i));<br>            }<br><br>            if (i &lt; word2.length()) {<br>                result.append(word2.charAt(i));<br>            }<br><br>            i++;<br>        }<br><br>        return result.toString();<br>    }<br>}</pre><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6c33a73e0da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Stop MediaStream Camera on Page Change in Single Page Applications (Reactjs, Nextjs)]]></title>
            <link>https://medium.com/@kajolmurmu29/how-to-stop-mediastream-camera-on-page-change-in-single-page-applications-reactjs-nextjs-2d8c88a39250?source=rss-6bec78016e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8c88a39250</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[getusermedia]]></category>
            <dc:creator><![CDATA[Kajol]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 08:19:40 GMT</pubDate>
            <atom:updated>2025-11-21T08:22:06.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>Camera stayed on when navigating backward in my React SPA. Solution: Use global state management (Zustand) to centralize camera stream control with setStream() and stopStream(). Stop managing streams locally in components—let a global store handle cleanup consistently across all page transitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0mxZPqGlFUM5K0LZPozTg.png" /></figure><h3>The Situation</h3><p>I was building a fun Photobooth app that used the device camera on the CapturePhoto page. Initially, everything seemed fine , I could take photos and navigate to the next page to decorate them, and the camera would turn off as expected.</p><p>However, I discovered a frustrating bug: when I navigated backward from the CapturePhoto page to the SelectLayout page, the camera remained on. The camera indicator light stayed lit, and I couldn’t tell if it was just a visual glitch or if the camera was actually still running. After investigating, I confirmed that sometimes the camera was genuinely still active, not just showing a false indicator.</p><h3>My Page Flow</h3><pre>SelectLayout page → CapturePhoto page → DecoratePhoto page</pre><p>The problem specifically occurred when navigating backward from CapturePhoto to SelectLayout using the browser’s back button or a custom “previous page” navigation.</p><h3>The Solution Hunt</h3><p>I scoured the internet and consulted various AI assistants, and they all suggested the same thing: use track.stop(). But here&#39;s the thing—I was already using it! That&#39;s Camera API 101. You call track.stop() to release the camera stream. So why wasn&#39;t it working?</p><h3>How I Actually Solved It</h3><p>The breakthrough came when I implemented <strong>global state management</strong> to handle the camera stream centrally. Instead of managing the stream within individual components, I created a Zustand store with a single stream state and two key actions:</p><h3>State</h3><p><strong>stream</strong>: Holds the current MediaStream object, or null when no camera is active.</p><h3>Actions</h3><p><strong>1. </strong><strong>setStream(stream)</strong></p><p>This function implements intelligent stream replacement. Before accepting a new stream, it checks whether one already exists. If it finds an existing stream with a different ID, it stops all tracks in the old stream before replacing it.</p><p>The ID comparison is critical — it prevents the function from unnecessarily stopping and restarting the same stream, which would cause a jarring flicker in your camera preview.</p><p><strong>2. </strong><strong>stopStream()</strong></p><p>This function stops all tracks in the current stream, releasing the camera hardware. It then clears the stream from state and logs whether it successfully stopped a stream or if there was nothing to stop.</p><h3>The Code</h3><p>Here’s the Zustand store implementation:</p><pre>import { create } from &quot;zustand&quot;;<br><br>interface CameraStore {<br>  stream: MediaStream | null;<br>  setStream: (stream: MediaStream | null) =&gt; void;<br>  stopStream: () =&gt; void;<br>}<br>export const useCameraStore = create&lt;CameraStore&gt;((set, get) =&gt; ({<br>  stream: null,<br>  setStream: (stream) =&gt; {<br>    // Stop any existing stream first before replacing it<br>    const current = get().stream;<br>    if (current &amp;&amp; current.id !== stream?.id) {<br>      current.getTracks().forEach((track) =&gt; track.stop());<br>    }<br>    set({ stream });<br>  },<br>  stopStream: () =&gt; {<br>    const currentStream = get().stream;<br>    // Stops all tracks in the current stream<br>    if (currentStream) {<br>      currentStream.getTracks().forEach((track) =&gt; track.stop());<br>      set({ stream: null });<br>      console.log(&quot;Global camera stream stopped successfully&quot;);<br>    } else {<br>      console.log(&quot;No global stream to stop&quot;);<br>    }<br>  },<br>}));</pre><h3>How I used it in CapturePhoto page</h3><pre>async function startCamera() {<br>      try {<br>        const mediaStream = await navigator.mediaDevices.getUserMedia({<br>          video: { facingMode: &quot;user&quot; },<br>          audio: false,<br>        });<br><br>        if (!mounted) {<br>          // If component unmounted before stream arrived, stop it immediately<br>          mediaStream.getTracks().forEach((track) =&gt; track.stop());<br>          return;<br>        }<br><br>        // ✅ Store in global state only<br>        setStream(mediaStream);<br><br>        if (videoRef.current) {<br>          videoRef.current.srcObject = mediaStream;<br>          await videoRef.current.play().catch((err) =&gt; {<br>            if (err.name !== &quot;AbortError&quot;) console.error(err);<br>          });<br>        }<br>      } catch (err) {<br>        setPermissionError(err instanceof Error ? err.message : String(err));<br>      }<br>    }<br><br>    startCamera();<br><br> <br>    return () =&gt; {<br>      mounted = false;<br>      stopStream(); // Using Zustand store cleanup<br>      if (videoRef.current) videoRef.current.srcObject = null;<br>      if (animationFrameRef.current) {<br>        cancelAnimationFrame(animationFrameRef.current);<br>        animationFrameRef.current = null;<br>      }<br>    };<br>  }, [pathname, setStream, stopStream]);</pre><h3>How I used it in SelectLayout page</h3><pre>const { stopStream } = useCameraStore();<br>  useEffect(() =&gt; {<br>    // Stop any active camera stream when landing on this page<br>    stopStream();<br>  }, [stopStream]);</pre><h3>Conclusion</h3><p>Managing camera streams in Single Page Applications can be tricky, especially when dealing with navigation and component lifecycle. The key to solving persistent camera issues is <strong>centralized state management</strong>. By using a global Zustand store to track and control your MediaStream, you ensure that:</p><ul><li>Only one camera instance runs at a time</li><li>Cleanup happens reliably during navigation</li><li>The camera indicator accurately reflects the hardware state</li><li>Your app doesn’t drain battery or cause privacy concerns</li></ul><p>The pattern we’ve explored — combining setStream() for initialization and stopStream() for cleanup—provides a clean, predictable way to handle camera resources across your entire application.</p><h3>Let’s Learn Together</h3><p>If you’ve encountered similar camera-related issues or have found a better approach to stopping MediaStream on page changes, I’d love to hear about it! Drop your solutions, suggestions, or alternative patterns in the comments below.</p><p>Sometimes the best solutions come from the community’s collective experience. Your insights could help other developers facing the same challenge!</p><p>Happy Coding ! Do Follow me :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8c88a39250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 51: N-Queen Problem (Backtracking)]]></title>
            <link>https://medium.com/@kajolmurmu29/leetcode-51-n-queen-problem-backtracking-a996c5928a39?source=rss-6bec78016e3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a996c5928a39</guid>
            <category><![CDATA[n-queens-problem]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <dc:creator><![CDATA[Kajol]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 18:35:40 GMT</pubDate>
            <atom:updated>2025-11-21T08:53:37.360Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>PROBLEM</strong>: The <strong>n-queens</strong> puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.</p><p>Given an integer n, return <em>all distinct solutions to the </em><strong><em>n-queens puzzle</em></strong>. You may return the answer in <strong>any order</strong>.</p><p>Each solution contains a distinct board configuration of the n-queens’ placement, where &#39;Q&#39; and &#39;.&#39; both indicate a queen and an empty space, respectively.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*cIlK77ykvaVKArnX.jpg" /><figcaption>n-queen problem example</figcaption></figure><pre>Input: n = 4<br>Output: [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]]<br>Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above</pre><h3>How Do We Approach This Problem?</h3><p>The N-Queens puzzle is solved using a technique called <strong>backtracking</strong>.</p><p>Backtracking is like exploring every possibility but going back whenever you hit a dead end.</p><p>You can think of it like this:</p><ol><li>Start with the first row.</li><li>Try placing a queen in each column.</li><li>If the position is safe, move to the next row.</li><li>If not safe, move the queen to the next column.</li><li>If the entire row has no safe position, go back to the previous row and move that queen.</li><li>Continue this until all queens are placed or all possibilities are checked.</li></ol><p>This step-by-step checking ensures we don’t miss any valid arrangement.</p><h3>How Do We Check If a Position Is Safe?</h3><p>A position (row, col) is safe if:</p><ol><li>No queen exists <strong>in the same column</strong></li><li>No queen exists <strong>in the upper-left diagonal</strong></li><li>No queen exists <strong>in the upper-right diagonal</strong></li></ol><p>We only check the <em>upper</em> rows because we place queens one row at a time.</p><h3>How We Represent the Board</h3><p>We use a 2D character array where:</p><ul><li>&#39;Q&#39; means a queen is placed.</li><li>&#39;.&#39; means the square is empty.</li></ul><h3>Solving the N-Queens Problem in Java</h3><pre>class Solution {<br>    public List&lt;List&lt;String&gt;&gt; solveNQueens(int n) {<br>        List&lt;List&lt;String&gt;&gt; resultBoard=new ArrayList&lt;&gt;();<br>        char board[][]=new char[n][n];<br><br>        for(int i=0;i&lt;n;i++){<br>            Arrays.fill(board[i],&#39;.&#39;);<br>        }<br><br>        placeQueens(board,resultBoard,0);<br><br>        return resultBoard;<br>    }<br><br>    public void placeQueens(char[][] board, List&lt;List&lt;String&gt;&gt; resultBoard,int row){<br>        if(row==board.length){<br>            saveQueens(board,resultBoard);<br>        }<br><br>        for(int col=0;col&lt;board.length;col++){<br>            if(isSafe(board,row,col)){<br>                board[row][col]=&#39;Q&#39;;   //placing queen<br>                placeQueens(board,resultBoard,row+1);<br>                board[row][col]=&#39;.&#39;;   //backtracking<br>            }<br>        }<br>    }<br><br>    public boolean isSafe(char[][] board,int row, int col){<br>        <br>        //check the columns<br>        for(int i=0;i&lt;row;i++){<br>            if(board[i][col]==&#39;Q&#39;){<br>                return false;<br>            }<br>        }<br>        //Only checking above the current row because lower rows are empty.<br><br>        //check upper-left diagonal<br>        for(int i=row,j=col; i&gt;=0 &amp;&amp; j&gt;=0;i--,j--){<br>            if(board[i][j]==&#39;Q&#39;){<br>                return false;<br>            }<br>        }<br><br>        //check upper-right diagonal<br>        for(int i=row,j=col;i&gt;=0 &amp;&amp; j&lt;board.length;i--,j++){<br>            if(board[i][j]==&#39;Q&#39;){<br>                return false;<br>            }<br>        }<br><br>        return true;<br><br>    }<br><br>    public void saveQueens(char[][] board,List&lt;List&lt;String&gt;&gt; resultBoard){<br>        List&lt;String&gt; res=new ArrayList&lt;&gt;();<br>        for(int i=0;i&lt;board.length;i++){<br>            res.add(new String(board[i]));<br>        }<br>        resultBoard.add(res);<br>    }<br>}</pre><p><strong>Claude Visualizer: </strong><a href="https://claude.ai/public/artifacts/fbd54b17-b1b7-461b-89c0-36060b5a7353"><strong>Link</strong></a></p><h3><strong>Conclusion:</strong></h3><p>The N-Queens problem perfectly demonstrates how powerful backtracking can be. By placing queens step by step and reversing our choices when a conflict appears, we explore the board in a structured and logical way. This method ensures that every possible arrangement is checked without wasting time on invalid paths. Through this puzzle, we learn how backtracking helps us solve complex problems by trying, testing, and undoing moves until we reach all valid solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a996c5928a39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>