<?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"><channel><title><![CDATA[leetcode]]></title><description><![CDATA[leetcode]]></description><link>https://dsawithleetcode.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 01 Sep 2026 08:31:08 GMT</lastBuildDate><atom:link href="https://dsawithleetcode.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[271. Encode and Decode Strings]]></title><description><![CDATA[Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
I have a very simple outlook on this ]]></description><link>https://dsawithleetcode.hashnode.dev/271-encode-and-decode-strings</link><guid isPermaLink="true">https://dsawithleetcode.hashnode.dev/271-encode-and-decode-strings</guid><dc:creator><![CDATA[Manubhav Sharma]]></dc:creator><pubDate>Mon, 18 May 2026 15:45:43 GMT</pubDate><content:encoded><![CDATA[<p>Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.</p>
<p>I have a very simple outlook on this question- let the strings be ["something", "that", "is", "the", "string"].</p>
<p>During transmission after encoding, the string will be "somethingthatisthestring" lets say.</p>
<p>We just have to keep track of the end of every word here. We could use something like index tracking, even the idea of <strong>"something that is the string"</strong> does not look bad to me because the decoder can just check for spaces and separate words.</p>
<p>But even more concrete way is to record the length of each string and later search for the indices in the decoder.</p>
<pre><code class="language-plaintext">class Solution:

    def encode(self, strs: List[str]) -&gt; str:
        if not strs:
            return ""
        sizes, res = [],""
        for s in strs:
            sizes.append(len(s))
        for sz in sizes:
            res += str(sz)
            res += ','
        res += '#'
        for s in strs:
            res += s
        return res

    def decode(self, s: str) -&gt; List[str]:
        if not s:
            return ""
        sizes, res, i = [], [] ,0
        while s[i] != '#':
            cur = ""
            while s[i] != ',':
                cur += s[i]
                i += 1
            sizes.append(int(cur))
            i += 1
        i += 1
        for sz in sizes:
            res.append(s[i:i + sz])
            i += sz
        return res
</code></pre>
<p>Here, we take the given strings, note their lengths at the start of the encoded string, then we out a # in between for separation. Now, we write all the string in the given list respectively.</p>
]]></content:encoded></item><item><title><![CDATA[347. Top K Frequent Elements]]></title><description><![CDATA[Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input:]]></description><link>https://dsawithleetcode.hashnode.dev/347-top-k-frequent-elements</link><guid isPermaLink="true">https://dsawithleetcode.hashnode.dev/347-top-k-frequent-elements</guid><dc:creator><![CDATA[Manubhav Sharma]]></dc:creator><pubDate>Tue, 12 May 2026 18:57:51 GMT</pubDate><content:encoded><![CDATA[<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> nums = [1,1,1,2,2,3], k = 2</p>
<p><strong>Output:</strong> [1,2]</p>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> nums = [1], k = 1</p>
<p><strong>Output:</strong> [1]</p>
<p><strong>Example 3:</strong></p>
<p><strong>Input:</strong> nums = [1,2,1,2,1,2,3,1,3,2], k = 2</p>
<p><strong>Output:</strong> [1,2]</p>
<p>The solution i could think of while solving this problem was using hashmaps, sorting.</p>
<p>To find the <code>k</code> most frequent elements, we first need to know how often each number appears.<br />Once we count the frequencies, we can sort the unique numbers based on how many times they occur.<br />After sorting, the numbers with the highest frequencies will naturally appear at the end of the list.<br />By taking the last <code>k</code> entries, we get the <code>k</code> most frequent elements.</p>
<p>This approach is easy to reason about:<br />count the frequencies → sort by frequency → take the top <code>k</code>.</p>
<p>But as i looked at more optimized and better solutions, we have two more approaches.<br /><strong>Min heap</strong> and <strong>Bucket sort</strong>, the min heap solution is something which was easily understood as it was just the sorting method enhanced by min heap structure, but the bucket list logic is a copletely different approach. So even though the best result of O(n) is achieved by bucket list, i stick with min heap for personal satisfaction as this approach was more or less what i thought of myself.  </p>
<p>After counting how often each number appears, we want to efficiently keep track of only the <code>k</code> most frequent elements.<br />A min-heap is perfect for this because it always keeps the smallest element at the top.<br />By pushing <code>(frequency, value)</code> pairs into the heap and removing the smallest whenever the heap grows beyond size <code>k</code>, we ensure that the heap always contains the top <code>k</code> most frequent elements.<br />In the end, the heap holds exactly the <code>k</code> values with the highest frequencies.  </p>
<h3>Implementation</h3>
<pre><code class="language-plaintext">class Solution:
    def topKFrequent(self, nums: List[int], k: int) -&gt; List[int]:
        count = {}
        for num in nums:
            count[num] = 1 + count.get(num, 0)

        heap = []
        for num in count.keys():
            heapq.heappush(heap, (count[num], num))
            if len(heap) &gt; k:
                heapq.heappop(heap)

        res = []
        for i in range(k):
            res.append(heapq.heappop(heap)[1])
        return res
</code></pre>
]]></content:encoded></item><item><title><![CDATA[49. Group Anagrams]]></title><description><![CDATA[Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example-
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate",]]></description><link>https://dsawithleetcode.hashnode.dev/49-group-anagrams</link><guid isPermaLink="true">https://dsawithleetcode.hashnode.dev/49-group-anagrams</guid><dc:creator><![CDATA[Manubhav Sharma]]></dc:creator><pubDate>Sun, 10 May 2026 23:52:13 GMT</pubDate><content:encoded><![CDATA[<p>Given an array of strings <code>strs</code>, group the anagrams together. You can return the answer in <strong>any order</strong>.</p>
<p>Example-</p>
<p><strong>Input:</strong> strs = ["eat","tea","tan","ate","nat","bat"]</p>
<p><strong>Output:</strong> [["bat"],["nat","tan"],["ate","eat","tea"]]</p>
<p>definition- An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66096e456083ba84715fd663/f4e66236-e087-427a-b545-c3ec6c0b54c9.png" alt="" style="display:block;margin:0 auto" />

<p>can we find a pattern here? But on a closer look , do we need to find a pattern? Because the pattern is mentioned in the question itself- anagram. abt - bat, ant-nat,tan , aet- ate,eat,tea. So if we sort the letters alphabetically we can can make a group heading or identification check of the group, and if it doesnot exist already, we create a new group.<br />sets can be used here, because uniqueness is involved. Or even hashmap.</p>
<h3>Implementation</h3>
<pre><code class="language-plaintext">        res = defaultdict(list)
        for s in strs:
            sortedS = ''.join(sorted(s))
            res[sortedS].append(s)
        return list(res.values())
</code></pre>
]]></content:encoded></item><item><title><![CDATA[1. Two Sum]]></title><description><![CDATA[Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Reading this, the instinct is to run a double loop. testing each element with ]]></description><link>https://dsawithleetcode.hashnode.dev/1-two-sum</link><guid isPermaLink="true">https://dsawithleetcode.hashnode.dev/1-two-sum</guid><dc:creator><![CDATA[Manubhav Sharma]]></dc:creator><pubDate>Fri, 08 May 2026 22:24:12 GMT</pubDate><content:encoded><![CDATA[<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to</em> <code>target</code>.</p>
<p>Reading this, the instinct is to run a double loop. testing each element with all the others one by one. But there is more,</p>
<p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> element twice.</p>
<p>From the last questions we solved, only one remind me of a set. But the situation calls for returning index numbers which the data which set does not carry with it.<br />So what if we create a hashmap and then keep the key as the number an value as the index so when we have to retrieve the index of the number in the original array, we can do so with ease.</p>
<pre><code class="language-plaintext">target = number1 + number2
number2 = target - number1
</code></pre>
<p>Now if we can just find this compliment in the hashmap, we can find the number pair and their index in one iteration.</p>
<h3>Implementaion</h3>
<img src="https://cdn.hashnode.com/uploads/covers/66096e456083ba84715fd663/87bd2e4a-f878-40a0-bc67-699cf1425786.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[242. Valid Anagram]]></title><description><![CDATA[definition-An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.We have been given two strings t and s and we hav]]></description><link>https://dsawithleetcode.hashnode.dev/242-valid-anagram</link><guid isPermaLink="true">https://dsawithleetcode.hashnode.dev/242-valid-anagram</guid><dc:creator><![CDATA[Manubhav Sharma]]></dc:creator><pubDate>Fri, 08 May 2026 21:47:17 GMT</pubDate><content:encoded><![CDATA[<p>definition-An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.<br />We have been given two strings t and s and we have to check if t is an anagram or of s or not.</p>
<h3>Simple approach</h3>
<p>1:1 checking - or both the strings and then compare them. If they turn out to be equal, we have an anagram.</p>
<h3>Alphabet logging</h3>
<p>we create two arrays of size 26 , 1 for each alphabet. And keep a record of each alphabet when it comes in both of the strings.<br />The way i did it is by adding 1 when an alphabet comes in string s (at its corresponding address) and subtracting 1 when the alphabet is in string t. Now, if the resultant array is all 0's then we return true.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66096e456083ba84715fd663/e4796bf1-30ca-459f-b26d-0ecf5cfa38db.png" alt="" style="display:block;margin:0 auto" />

<p>But, in the top results in leetcode submissions i found a better optimized solution, specific to this particular problem.  </p>
<img src="https://cdn.hashnode.com/uploads/covers/66096e456083ba84715fd663/592b814a-18f4-400a-a735-a6cc0a5037b7.png" alt="" style="display:block;margin:0 auto" />

<p>There is a slight issue with the second approach, it can only work with alphabets. But it gets the current job done with high efficiency. Although i am not really sure why there is a flag variable when it is not being used.</p>
]]></content:encoded></item><item><title><![CDATA[217. Contains Duplicate]]></title><description><![CDATA[In this problem , we just have to check if the integer array contains duplicates. If it does , return true and if it does not contain any duplicates, return false.
For this, we can use a set.
Definiti]]></description><link>https://dsawithleetcode.hashnode.dev/217-contains-duplicate</link><guid isPermaLink="true">https://dsawithleetcode.hashnode.dev/217-contains-duplicate</guid><dc:creator><![CDATA[Manubhav Sharma]]></dc:creator><pubDate>Fri, 08 May 2026 21:26:35 GMT</pubDate><content:encoded><![CDATA[<p>In this problem , we just have to check if the integer array contains duplicates. If it does , return true and if it does not contain any duplicates, return false.</p>
<p>For this, we can use a set.</p>
<p>Definition -a <strong>set</strong> is a data structure that stores a <strong>collection of unique, unordered elements</strong>. Unlike lists or arrays, sets automatically prevent duplicate entries and typically use <strong>hashing</strong> for internal storage, which allows for <strong>O(1)</strong> average time complexity for membership checks, additions, and deletions.</p>
<p>We declare an empty set, run this array through a loop, adding the elements to the set one by one. Now, if the element cannot be added to the set, that means the array already had that same number before in the array and thus, we can break the loop and return true. And, if the loop gets completed we return false.</p>
<hr />
<h3><strong>Implementation-</strong></h3>
<img src="https://cdn.hashnode.com/uploads/covers/66096e456083ba84715fd663/7d9931fa-4a27-436d-a53f-4e37dca12665.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item></channel></rss>