<?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 Rajat on Medium]]></title>
        <description><![CDATA[Stories by Rajat on Medium]]></description>
        <link>https://medium.com/@varshneyrajat01?source=rss-35e7de8cbaae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EPQsOawJLB0hOrSw</url>
            <title>Stories by Rajat on Medium</title>
            <link>https://medium.com/@varshneyrajat01?source=rss-35e7de8cbaae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:48:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varshneyrajat01/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[The Ultimate NLP Roadmaps; From text Preprocessing to Word Embeddings.]]></title>
            <link>https://medium.com/@varshneyrajat01/the-ultimate-nlp-roadmaps-from-text-preprocessing-to-word-embeddings-cde9bdc4a678?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/cde9bdc4a678</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 10:57:28 GMT</pubDate>
            <atom:updated>2026-04-23T10:57:28.517Z</atom:updated>
            <content:encoded><![CDATA[<p>A hands-on guide to stemming, lemmatization, TF-IDF, and the Foundation of Word Vectorization using NLTK, Scikit-Learn.</p><h4>Roadmap of NLP:</h4><p><strong>Step1:</strong> One programming language:(python)</p><p><strong>Step2:</strong> Text Preprocessing (cleaning the input): Part-1</p><ul><li>Tokenization</li><li>Lemmatization</li><li>Stemming</li><li>Stop word.</li></ul><p><strong>Step 3:</strong> Text Preprocessing (input text-&gt; vectors): Part-2</p><ul><li>Beg of words</li><li>TFIDF</li><li>Unigrams</li><li>Bigrams</li></ul><p><strong>Step 4:</strong> Text preprocessing (input text-&gt;better): Part-3 (better way)</p><ul><li>Word2vec</li><li>Avgword2vec</li></ul><p><strong>Step5:</strong> Neural Network:</p><ul><li>RNN</li><li>LSTM RNN</li><li>GRU RNN</li></ul><p><strong>Step6: </strong>text preprocessing:</p><ul><li>Word Embedding.</li></ul><p><strong>Step7:</strong> Transformer</p><p><strong>Step8: </strong>BERT</p><p>first, we learn step2 to step4 (Machine learning) then Step5 to Step7 (deep learning part) we learn later.</p><p>for Machine learning part we use library such as NLTK and spaCy.</p><p>for Deep Learning part we use library such as TensorFlow / PyTorch.</p><h4>Let’s start of Learning NLP:</h4><p>Basic terminology need to understand:</p><ul><li>Corpus: whole Paragraph</li><li>Documents: sentences used in a paragraph</li><li>Vocabulary: Unique words</li><li>Words: all the words that present in the corpus</li></ul><h4><strong>Tokenization:</strong></h4><p>tokenization is a process to convert either a paragraph or a sentences into tokens.</p><pre># Tokenization-Example(Jupyter)<br>!pip install nltk<br>corpus= &quot;&quot;&quot; Hello Welcome, to Rajat NLP&#39;s tutorial , please do read the entire blog care fully.&quot;&quot;&quot;<br>print(corpus)<br><br>## tokenization: sentences-&gt; paragraph<br>from nltk.tokenize import sent_tokenize<br>documents=sent_tokenize(corpus)<br>type(documents)<br>for sentence in documents:<br>  print(sentence)</pre><pre>## tokenization: paragraph/sentences -&gt; words ( gives full single list of tokens)<br>from nltk.tokenize import word_tokenize<br>word_tokenize(corpus)</pre><pre># we want tokenization on sentences level--&gt; gives sentence based list wise tokens<br>for sentence in documents:<br>  print(word_tokenize(sentence))<br><br>&quot;&quot;&quot; same as word_tokenize. little difference is wordpunct_tokenize also create tokens for pantuation like in NLP&#39;s tokens are &#39;nlp&#39;,&quot; &#39; &quot;,&#39;s&#39; . &quot;&quot;&quot;<br>from nltk.tokenize import wordpunct_tokenize<br>wordpunct_tokenize(corpus) # <br><br>from nltk.tokenize import TreebankWordTokenizer # all same only diff is, it does&#39;t treated &#39;.&#39; as tokens other than last &#39;.&#39; <br>tokenizer = TreebankWordTokenizer()<br>tokens = tokenizer.tokenize(corpus)<br>print(tokens)</pre><h4><strong>Stemming:</strong></h4><p>stemming is the process of reducing a word to its word stem that affixes to suffixes and prefixes or to the roots of words known as a lemma.</p><pre>Example:<br>## let take classification Problem<br>find reviews on a product that is a positive review or negative review. so we  take review dataset and trained machine for this. our first step is text preprocessing.<br>for sentiment analysis we do not want full data to be trained if we have shorten data that have the same meanung as full data. we are good to go.<br><br>for shorting the data we have a technique called stemming it reduced the data by removing some extra part ex: like --&gt; [&#39;eating&#39;,&#39;eat&#39;,&#39;eaten&#39;]-&gt;eat,[&#39;going&#39;,&#39;gone&#39;,&#39;goes&#39;]-&gt; go<br>eat and go is lemma of words here. <br>it is used to shorten the corpus so that size of data reduced and avoid repeted no of times same word in diff form. </pre><pre>words=[&#39;eating&#39;,&#39;eats&#39;,&#39;eaten&#39;,&#39;writing&#39;, &#39;writes&#39;, &#39;programming&#39;,&#39;programs&#39;,&#39;history&#39;,&#39;finally&#39;,&#39;finalize&#39;]</pre><pre>## porterstemmer<br>from nltk.stem import PorterStemmer<br>stemming= PorterStemmer()<br>for word in words:<br>  print(word + &quot;--&gt;&quot; + stemming.stem(word))</pre><p><strong>Disadvantages of stemming:</strong></p><p>when stemming is basically applied, for some of the words, you may not get a correct exact meaning, the form of that specific word may change. So this is the major disadvantage with respect to stemming.</p><p>example:</p><ul><li>when we apply stemming on history it gives histori which does not make sense.</li><li>one more ex is word=’congratulation’ → after stemming congratul.</li></ul><p>solution is lemmatization.</p><h4>Regexpstemmer class</h4><p>nltk has Regexpstemmer class with the help of which we can easily implement <strong>regular expression</strong>.</p><pre>from nltk.stem import RegexpStemmer<br>reg_stemmer=RegexpStemmer(&#39;ing$|s$|e$|able$&#39;, min=4)<br>reg_stemmer.stem(&#39;eating&#39;) # -&gt; eat<br>reg_stemmer.stem(&#39;ingeating&#39;) # -&gt; ingeat<br></pre><p>Note: Snowball stemmer is better than other stemming method</p><h4>Wordnet Lemmatizer.</h4><p>Lemmatization technique is like stemming. the output we get after lemmatization is called ‘lemma’, which is root word rather than root stem.</p><p>after lemmatization, we will be getting a valid word that means the same thing.</p><pre>from nltk.stem import WordNetLemmatizer<br>lemmatizer= WordNetLemmatizer()<br>lemmatizer.lemmatize(&quot;going&quot;, pos=&#39;v&#39;) # --&gt; &#39;go&#39; <br>&#39;&#39;&#39; pos=&#39;v&#39; stands for going is the verb by defaault in lemmatization it would be noun.<br>in pos= ..... we can write &#39;v&#39;/&#39;n&#39;/&#39;a&#39;/&#39;r&#39; which means verb/noun/adjective/adverb respectively&#39;&#39;&#39;<br><br>words=[&#39;eating&#39;,&#39;eats&#39;,&#39;eaten&#39;,&#39;writing&#39;, &#39;writes&#39;, &#39;programming&#39;,&#39;programs&#39;,&#39;history&#39;,&#39;finally&#39;,&#39;finalize&#39;]<br>for word in words:<br>  print(word + &quot;--&gt;&quot; + lemmatizer.lemmatize(word,pos=&#39;v&#39;)) # --&gt; good ans</pre><p>Disadvantages of lemmatization-&gt; it takes much time than stemming.</p><p>so we use lemmatization only when sense(grammar) of word is important.</p><p>where to use lemmatization:</p><ul><li>Q&amp;A</li><li>Chatbots</li><li>text summarization</li></ul><p>where to use stemming:</p><ul><li>sentiment analysis</li><li>ham/spam classification.</li></ul><p>these are some useful examples where to use lemmatization or stemming.</p><h4>Text Preprocessing- StopWords:</h4><p>In NLP stop words are common words such as ‘the’, ‘is’, ‘and’ so on. stop words carry little or negligible semantic meaning to improve processing efficiency and model accuracy we remove these stop words.</p><pre>paragraph=&#39;&#39;&#39;Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on enabling computers to understand, interpret, and generate human language in a meaningful way. It combines linguistics, computer science, and machine learning to process both written and spoken language. NLP powers many applications we use daily, such as chatbots, virtual assistants, translation systems, sentiment analysis tools, and speech‑to‑text services. It works through techniques like tokenization, part‑of‑speech tagging, named entity recognition, and modern transformer-based models such as BERT and GPT. Overall, NLP helps bridge the gap between human communication and computer understanding, making interactions with technology more natural and intuitive.&#39;&#39;&#39;<br>from nltk.stem import PorterStemmer<br>from nltk.corpus import stopwords<br>import nltk<br>nltk.download(&#39;stopwords&#39;)<br>stopwords.words(&#39;english&#39;)</pre><pre># 1- using PorterStemmer<br><br>from nltk.stem import PorterStemmer<br>stemmer= PorterStemmer()<br>sentences= nltk.sent_tokenize(paragraph)<br><br>## apply stopwords and then apply stemming<br><br>for i in range (len(sentences)):<br>    words= nltk.word_tokenize(sentences[i])<br>    words= [stemmer.stem(word) for word in words if word not in set(stopwords.words(&#39;english&#39;))]<br>    sentences[i]=&#39; &#39;.join(words) # converting all the words back into sentences<br><br>print(sentences)</pre><pre>#2- using snowball stemmer<br><br>from nltk.stem import SnowballStemmer<br>SnowballsStemmer= SnowballStemmer(&#39;english&#39;)<br><br>for i in range (len(sentences)):<br>    words= nltk.word_tokenize(sentences[i])<br>    words= [SnowballsStemmer.stem(word) for word in words if word not in set(stopwords.words(&#39;english&#39;))]<br>    sentences[i]=&#39; &#39;.join(words) # converting all the words back into sentences<br><br>print(sentences)</pre><h4>One-Hot Encoding (Not much used in NLP):</h4><p><strong>One-Hot Encoding</strong> is a technique used in <strong>machine learning</strong> and <strong>data preprocessing</strong> to convert <strong>categorical variables</strong> into a numerical format that algorithms can understand.</p><p>Instead of assigning arbitrary numbers to categories (which could imply an unintended order), one-hot encoding creates <strong>binary columns</strong> for each category.</p><p><strong>Advantages and Disadvantages of OHE:</strong></p><p><strong>Advantages:</strong></p><ul><li>Easy to Implement with python [ sklearn library, pd.get_dummies()]</li></ul><p><strong>Disadvantages:</strong></p><ul><li>it creates Sparse matrix-&gt; which result in overfitting problem.</li><li>for Ml Algorithms we need Fixed size input but in OHE its not always happing.</li><li>No Semantic meaning is getting captured.</li></ul><h4>Bag of Words (BOW):</h4><p>The bag of words (BoW) model converts text into numerical data. It transforms a sentence, paragraph, or document into a collection of words and counts the frequency of each word, ignoring the order and grammar. The model focuses on word frequency within the text.</p><p>To apply the bag of words model:</p><ol><li>Convert all words in the sentences to lower case.</li><li>Remove stop words from the sentences.</li><li>Use a Python library to process the sentences.</li><li>Create a matrix that displays the sentences and the count of each word.</li></ol><p><strong>Advantages:</strong></p><p>1- Simple and Intuitive</p><p>2- Fixed Sized Input-&gt; For training dataset on ML algo.</p><p><strong>Disadvantages:</strong></p><p>1- Sparse matrix (overfitting) present.</p><h4>Implementation of Bag Of Words(BOW):</h4><p>Here for implementing bag of words, we use classic Ham-Spam Email Classification.</p><p>You can download the dataset from Kaggle.</p><pre>import pandas as pd<br># you need to dowload the dataset from kaggle.&quot;https://www.kaggle.com/datasets/uciml/sms-spam-collection-dataset&quot;<br>messages= pd.read_csv(&#39;SpamClassifier/SMSSpamcollection&#39;,sep=&#39;\t&#39;, names=[&quot;names&quot;,&quot;message&quot;]) # sep = seperator<br><br>messages<br><br>## Data Cleaning and Preprocessing<br>import re # --&gt; regular expression<br>import nltk<br>nltk.download(&#39;stopwords&#39;)<br><br>from nltk.corpus import stopwords<br>from nltk.stem.porter import PorterStemmer<br>ps= PorterStemmer()<br><br>corpus=[]<br>for i in range (0, len(messages)):<br>  review=re.sub(&#39;[^a-zA-Z]&#39;, &#39; &#39;, messages[&#39;message&#39;][i])<br>  review=review.lower()<br>  review=review.split()<br>  review=[ps.stem(word) for word in review if not word in stopwords.words(&#39;english&#39;)]<br>  review=&#39; &#39;.join(review)<br>  corpus.append(review)<br><br>corpus<br><br>## Apply BOW models<br><br>from sklearn.feature_extraction.text import CountVectorizer<br>cv= CountVectorizer( max_feature=120, binary=True)# for binary BOW enable binary=true.<br><br>X=cv.fit_transform(corpus).toarray() <br><br>X</pre><h4>N-Grams: (eg: bigrams, trigrams)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*-uhnmY87jnmnrkV-0ocY4A.png" /></figure><p>in Sklearn there is a method called n-grams which help to create combination of words. and create huge difference between two similar types of sentences.</p><p>Eg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*jHhTsYta20zZeHhYrHwweg.png" /></figure><h4>N-gram implementation using NLTK.</h4><pre><br>## Apply BOW models with N-Grams<br><br>from sklearn.feature_extraction.text import CountVectorizer<br>cv= CountVectorizer( max_feature=200, binary=True, ngram_range(1,2))<br><br>X=cv.fit_transform(corpus).toarray() <br>X<br><br>cv.vocabulary_</pre><p><strong>Note:</strong> always check accuracy then select ngram_range = (1,1)/ (1,2)/ (2,3)…. and also same check for max_feature=100/200/.. so on.</p><h4>TF-IDF [Term Frequency — Inverse Document Frequency]</h4><p>(efficient way to convert words into vectors)</p><ul><li><strong>Term Frequency (TF)</strong> measures how often a word appears in a document, with a higher frequency indicating greater relevance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*_0raN3jaXlIxjYRFxstBOw.png" /></figure><ul><li><strong>Inverse Document Frequency (IDF)</strong> reduces the weight of common words across multiple documents while increasing the weight of rare words, reflecting their significance in the overall corpus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*aJyWzUal_Qk_VSn6jQmawg.png" /></figure><p>The total value of TF-IDF = TF (t, d) * IDF (t, d).</p><p><strong>Advantages and disadvantages of TF-IDF.</strong></p><p>Advantages:</p><ul><li>Intuitive</li><li>Fixed size</li><li>Captures word importance.</li></ul><p>Disadvantages:</p><ul><li>Sparsity remains</li><li>Does not handle out-of-vocabulary words.</li></ul><pre>import pandas as pd<br># you need to dowload the dataset from kaggle.&quot;https://www.kaggle.com/datasets/uciml/sms-spam-collection-dataset&quot;<br>messages= pd.read_csv(&#39;SpamClassifier/SMSSpamcollection&#39;,sep=&#39;\t&#39;, names=[&quot;names&quot;,&quot;message&quot;]) # sep = seperator<br><br>messages<br><br>## Data Cleaning and Preprocessing<br>import re # --&gt; regular expression<br>import nltk<br>nltk.download(&#39;stopwords&#39;)<br><br>from nltk.corpus import stopwords<br># from nltk.stem.porter import PorterStemmer<br># ps= PorterStemmer()<br>from nltk.stem import WordNetLemmatizer<br>wordlemmatize= WordNetLemmatizer()<br><br>corpus=[]<br>for i in range (0, len(messages)):<br>  review=re.sub(&#39;[^a-zA-Z]&#39;, &#39; &#39;, messages[&#39;message&#39;][i])<br>  review=review.lower()<br>  review=review.split()<br>  review=[wordlemmatize.lemmatize(word) for word in review if not word in stopwords.words(&#39;english&#39;)]<br>  review=&#39; &#39;.join(review)<br>  corpus.append(review)<br><br>corpus<br><br>## Create TF-IDF and NGrams<br>from sklearn.feature_extraction.text import TfidVectorizer<br>tfidf=TfidVectorizer(max_features=100)<br>X=tfidf.fit_transform(corpus).toarray()<br><br>import numpy as np<br>np.set_printoptions(edgeitems=30, linewidth= 100000, formatter = dict(float=lambda x: &quot;%.3g&quot; %x))<br>X<br><br>## N-Grams<br>tfidf=TfidVectorizer(max_features=100, ngram_range=(2,2))<br>X=tfidf.fit_transform(corpus).toarray()<br>tfidf.vocabulary_<br><br>X<br></pre><h4>Word Embedding (Words-&gt;Vectors OR Sentences-&gt; Vectors):</h4><p>In NLP, Word Embedding is a term used for the representation of words for text analysis, typically in the form of a real-valued vector that encodes the meaning of the word such that the words that are closer in the vector space are expected to be similar in meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*u6w-hPWS-BOQbcM4epsyCQ.png" /></figure><p>Here Happy and Excited have same meaning so when we convert this text into vectors there positioning in 2D space is very close but Angry is opp. of happy that’s why it ‘s position is far away to the positioning of Happy.</p><h4>Word Embedding Technique’s:</h4><p><strong>It is mainly two types</strong>.</p><p><strong>1- Count or frequency</strong></p><ul><li>OHE (One-Hot Encoding)</li><li>BOW (Bag Of Words)</li><li>TF-IDF</li></ul><p><strong>2- Deep learning trained model (very good Accuracy)</strong></p><ul><li>Word2Vec</li></ul><p><strong>Word2Vec also two Types.</strong></p><ul><li>CBOW (continuous Bag Of Words)</li><li>Skipgram.</li></ul><h3><strong>Word2Vec:</strong></h3><p>The Word2vec algo uses a neural network model to learn word association from a large corpus of text. once trained, such a model can detect synonymous words or suggest additional words for a partial sentence. As the name implies, word2vec represents each distinct word with a particular list of numbers called a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ClV-g9cOCtvNdlfPk2RfxA.png" /></figure><p>In Word2Vec we try to create feature representation of every word. take large corpus of words as features representation and our words as vectors.</p><p><strong>Word2vec: (prerequisite: knowledge of ANN, Loss fun, optimizer)</strong></p><p>There are two ways through which we can trained our model</p><ul><li>Using pretrained model. (Google)</li><li>Train a model from scratch.</li></ul><h4><em>1- CBOW (continuous Bag of Words): Fully Connected Neural Network</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*u_cSQQ_BmW4YKAr4-jffhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYCj98j-FXuZUmI17K0Wrg.png" /></figure><h4>Skipgram:</h4><p>it is mostly same as CBOW only difference is whatever the output in CBOW is now Input for Skipgram and input in CBOW is now output to that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRFc2JhGZFSSV0QE5mKxIQ.png" /></figure><p>When should we apply CBOW or Skipgram:</p><ul><li>When Dataset is small -&gt; CBOW</li><li>When Large/Huge Dataset -&gt; Skipgram</li></ul><h4>Advantages of Word2Vec:</h4><ul><li>Sparse Matrix → got Dense matrix</li><li>semantic info is getting captured</li><li>No worry of Vocabulary size -&gt; we have fixed set of dimensions (eg: Google word2vec [300 dimension] used to train a lot of big datasets).</li><li>Out of Vocabulary problem is solved.</li></ul><h4>Avg Word2Vec:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*eKynL2gOMMks2_mMfunVYA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cde9bdc4a678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero to Hero in SQL (Every Beginner must read):]]></title>
            <link>https://medium.com/@varshneyrajat01/learn-sql-by-doing-easy-fda526a8a7b5?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/fda526a8a7b5</guid>
            <category><![CDATA[leetcode-sql]]></category>
            <category><![CDATA[sql-basic-to-advance]]></category>
            <category><![CDATA[handbook]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[leetcode50sql]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 11:04:21 GMT</pubDate>
            <atom:updated>2026-03-23T06:37:26.831Z</atom:updated>
            <content:encoded><![CDATA[<p>Best way to know any skill or knowledge is to practice on Question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*2Z7Zkal9M8oXosJK.png" /><figcaption>Table for Question 1 to 5</figcaption></figure><p><strong>-&gt;Question1: </strong>Write a SQL query to select everything in the books table<strong>.</strong></p><pre><br>SELECT *<br>FROM books;</pre><p><strong>Question2: </strong>Write a SQL query to find the names of all authors in the books table.</p><pre>SELECT Author<br>FROM books;</pre><p><strong>Question3: </strong>Write a SQL query to retrieve the title and price of all books in the books table that have a price greater than $13.</p><pre>Select title, price<br>from books<br>where price &gt; 13;</pre><p><strong>Question4: </strong>Retrieve the titles of books along with the corresponding author names where the author’s name starts with the letter ‘J’.</p><pre>SELECT title, author<br>from books<br>Where author LIKE &#39;J%&#39;;</pre><p><strong>Question5: </strong>Retrieve the first name, last name, major, and GPA of students whose GPA is above the average GPA of all students.</p><pre>Select first_name, last_name, major, gpa<br>From students<br>Where gpa &gt; (<br>             Select AVG(gpa) <br>             from students<br>            ); </pre><p><strong>Question6:</strong> You are given a database table named paperwork which contains two columns: n and m. Each row in the table represents a pair of integers. You need to write an SQL query to select the following:</p><ol><li>The value of n.</li><li>The value of m.</li><li>A calculated result, <strong>res</strong>, which is defined as follows:</li></ol><ul><li>If either n or m is negative, res should be 0.</li><li>Otherwise, res should be the product of n and m.</li></ul><p>The goal is to produce a result set where each row contains the values of n, m, and the computed res based on the specified conditions.</p><pre>select n,m, <br>      CASE <br>          when n&lt;0 OR m&lt;0 THEN 0<br>          ELSE n*m<br>      End AS res<br>From paperwork </pre><p><strong>Question 7: </strong>Let’s say you have a table named students with the following columns: id, name, age, and grade. How would you write an SQL query to select all students who are older than 20 years old?</p><pre>select id,name,age,grade<br>from students<br>where age&gt;20;</pre><p><strong>Question 8: </strong>Suppose you have a table named employees with the following columns: employee_id, name, department, and salary. How would you write an SQL query to select the names of employees who work in the &quot;Sales&quot; department and have a salary greater than $50,000?</p><pre>select name<br>from employees<br>where department=&#39;Sales&#39; AND salary&gt;50000;</pre><p><strong>Question9</strong>: You have a table named orders with the following columns: order_id, Customer_id, order_date, and total_amount. How would you write an SQL query to find the total amount of all orders placed in the year 2023?</p><pre>SELECT SUM(total_amount) AS total_amount_2023<br>FROM orders<br>WHERE order_date &gt;= &#39;2023-01-01&#39; AND order_date &lt;  &#39;2024-01-01&#39;;</pre><p><strong>Question10:</strong> You have a table named products with the following columns: id, name, category, and price. How would you write an SQL query to find the average price of products in the category &#39;Electronics&#39;?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*GEiXGxJNKpx7A8P3.png" /><figcaption>‘Products’ table</figcaption></figure><pre>SELECT ROUND(AVG(price), 2) AS average_price<br>FROM products<br>WHERE category = &#39;Electronics&#39;;</pre><p><strong>11. Creating a Table</strong>.</p><pre>CREATE TABLE students (<br>   id INTEGER PRIMARY KEY,<br>   name TEXT NOT NULL,<br>   gender TEXT NOT NULL<br>);<br><br>-- Now you want to Insert the value into students table. <br>INSERT INTO students VALUES (1, &#39;Ryan&#39;, &#39;M&#39;);<br>INSERT INTO students VALUES (2, &#39;Merry&#39;, &#39;F&#39;);<br><br>-- Update the table value by using UPDATE method<br>UPDATE students SET name=&quot;jenny&quot; where id=2;</pre><p><strong>NOTE:</strong></p><p>Single Line Comments -&gt; “ — ” and multi-line Comments is done by /* ……….. */</p><p><strong>12. </strong><a href="https://leetcode.com/problems/recyclable-and-low-fat-products/"><strong>Recyclable and Low Fat Products</strong></a><strong>.</strong></p><pre>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| product_id  | int     |<br>| low_fats    | enum    |<br>| recyclable  | enum    |<br>+-------------+---------+<br>product_id is the primary key (column with unique values) for this table.<br>low_fats is an ENUM (category) of type (&#39;Y&#39;, &#39;N&#39;) where &#39;Y&#39; means this product is low fat and &#39;N&#39; means it is not.<br>recyclable is an ENUM (category) of types (&#39;Y&#39;, &#39;N&#39;) where &#39;Y&#39; means this product is recyclable and &#39;N&#39; means it is not.<br><br>Write a solution to find the ids of products that are both low fat and recyclable.<br>Return the result table in any order. The result format is in the following example.</pre><pre>SELECT product_id <br>from Products <br>where low_fats=&#39;Y&#39; and recyclable=&#39;Y&#39;</pre><p><strong>13. </strong><a href="https://leetcode.com/problems/find-customer-referee/"><strong>Find Customer Referee</strong></a></p><pre>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| id          | int     |<br>| name        | varchar |<br>| referee_id  | int     |<br>+-------------+---------+<br>In SQL, id is the primary key column for this table.<br>Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them.<br><strong>Find the names of the customer that are either:</strong><br><br>referred by any customer with id != 2.<br>not referred by any customer.<br>Return the result table in any order.<br><br>The result format is in the following example.</pre><pre>select name <br>from Customer<br>where referee_id is null or referee_id != 2</pre><p><strong>14. </strong><a href="https://leetcode.com/problems/big-countries/"><strong>Big Countries</strong></a></p><pre>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| name        | varchar |<br>| continent   | varchar |<br>| area        | int     |<br>| population  | int     |<br>| gdp         | bigint  |<br>+-------------+---------+<br>name is the primary key (column with unique values) for this table.<br>Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value.<br><br>A country is big if:<br><br>it has an area of at least three million (i.e., 3000000 km2), or<br>it has a population of at least twenty-five million (i.e., 25000000).<br>Write a solution to find the name, population, and area of the big countries.<br><br>Return the result table in any order.<br><br>The result format is in the following example.</pre><pre>select name, population, area<br>from world <br>where area &gt;= 3000000 or population &gt;= 25000000</pre><p>15. <a href="https://leetcode.com/problems/article-views-i/">Article Views I</a></p><pre>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| article_id    | int     |<br>| author_id     | int     |<br>| viewer_id     | int     |<br>| view_date     | date    |<br>+---------------+---------+<br>There is no primary key (column with unique values) for this table, the table may have duplicate rows.<br>Each row of this table indicates that some viewer viewed an article (written by some author) on some date. <br>Note that equal author_id and viewer_id indicate the same person.<br><br>Write a solution to find all the authors that viewed at least one of their own articles.<br>Return the result table sorted by id in ascending order.<br>The result format is in the following example.</pre><pre>select distinct author_id as id <br>from Views<br>where author_id = viewer_id<br>order by id</pre><p>16. <a href="https://leetcode.com/problems/invalid-tweets/">Invalid Tweets</a>.</p><pre>+----------------+---------+<br>| Column Name    | Type    |<br>+----------------+---------+<br>| tweet_id       | int     |<br>| content        | varchar |<br>+----------------+---------+<br>tweet_id is the primary key (column with unique values) for this table.<br>content consists of alphanumeric characters, &#39;!&#39;, or &#39; &#39; and no other special characters.<br>This table contains all the tweets in a social media app.<br><br>Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15.<br><br>Return the result table in any order.<br><br>The result format is in the following example.</pre><pre>Select tweet_id<br>from Tweets <br>where LENGTH(content)&gt;15</pre><h3>Aggregate Function.</h3><p><strong>→ Aggregate Functions</strong></p><ul><li><strong>MIN()</strong>: Returns the smallest value within the selected column. SELECT MIN(salary) AS LowestSalary FROM Employee; This query returns the minimum salary from the Employee table.</li><li>Min() Syntax.</li></ul><pre>Min() SyntaxSELECT MIN(column_name)<br>FROM table_name<br>WHERE condition;</pre><ul><li><strong>MAX()</strong>: Returns the largest value within the selected column. SELECT MAX(salary) AS Highest Salary FROM Employee; This query returns the maximum salary from the Employee table.</li></ul><pre>-- MAX() Syntax<br>SELECT MAX(column_name)<br>FROM table_name<br>WHERE condition;</pre><ul><li><strong>COUNT()</strong>: Returns the number of rows in a set. SELECT COUNT(*) AS TotalEmployees FROM Employee; This query returns the total number of employees in the Employee table.</li></ul><pre>-- COUNT SYNTAX<br>SELECT COUNT([DISTINCT] column_name | *)<br>FROM table_name<br>WHERE condition;<br>/*The behavior of COUNT() depends on the argument used within the parentheses:<br>COUNT(*) - Counts the total number of rows in a table (including NULL values).<br>COUNT(columnname) - Counts all non-null values in the column.<br>COUNT(DISTINCT columnname) - Counts only the unique, non-null values in the column.*/</pre><ul><li><strong>SUM()</strong>: Returns the total sum of a numerical column. SELECT SUM(salary) AS TotalSalary FROM Employee; This query returns the total sum of salaries from the Employee table.</li></ul><pre>SELECT SUM(column_name)<br>FROM table_name<br>WHERE condition;</pre><ul><li><strong>AVG()</strong>: Returns the average value of a numerical column. SELECT AVG(salary) AS AverageSalary FROM Employee; This query returns the average salary from the Employee table.</li></ul><pre>SELECT AVG(column_name)<br>FROM table_name<br>WHERE condition;</pre><p><strong>→</strong> <strong>GROUP BY And HAVING.</strong></p><ul><li>The “<strong>GROUP BY</strong>” statement is used to group rows that have the same values into summary rows, like “Find the number of customers in each country”.</li><li>The GROUP BY statement is almost always used in conjunction with aggregate functions, like COUNT(), MAX(), MIN(), SUM(), AVG(), to perform calculations on each group.</li><li>SYNTAX</li></ul><pre>SELECT column1, aggregate_function(column2), ...<br>FROM table_name<br>WHERE condition<br>GROUP BY column1, column3<br>ORDER BY column_name;</pre><ul><li><strong>“HAVING” </strong>clause is used to filter the results of a GROUP BY query based on aggregate functions. Unlike the <strong>WHERE</strong> clause, which filters individual rows before grouping, HAVING filters groups after the aggregation has been performed.</li><li>NOTE: GROUP BY always used after where clause and HAVING is used after group by.</li><li>NOTE: WHERE keyword doesn’t use aggregate function so there is need of special arrangement for this “HAVING” clause.</li></ul><h3>Sorting and Grouping.</h3><p>Ques 1: <a href="https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher/">Number of Unique Subjects Taught by Each Teacher</a></p><pre>Table: Teacher<br>+-------------+------+<br>| Column Name | Type |<br>+-------------+------+<br>| teacher_id  | int  |<br>| subject_id  | int  |<br>| dept_id     | int  |<br>+-------------+------+<br>(subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table.<br>Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.<br>Write a solution to calculate the number of unique subjects each teacher teaches in the university.<br>Return the result table in any order. The result format is shown in the following example.</pre><pre>SELECT teacher_id, COUNT(DISTINCT subject_id) as cnt<br>from Teacher<br>group by teacher_id;</pre><p>Question 2: <a href="https://leetcode.com/problems/user-activity-for-the-past-30-days-i/">1141. User Activity for the Past 30 Days I</a></p><pre>Table: Activity<br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| user_id       | int     |<br>| session_id    | int     |<br>| activity_date | date    |<br>| activity_type | enum    |<br>+---------------+---------+<br>This table may have duplicate rows.<br>The activity_type column is an ENUM (category) of type (&#39;open_session&#39;, &#39;end_session&#39;, &#39;scroll_down&#39;, &#39;send_message&#39;).<br>The table shows the user activities for a social media website. <br>Note that each session belongs to exactly one user. <br>Write a solution to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on someday if they made at least one activity on that day.<br>Return the result table in any order.<br>The result format is in the following example.<br>Note: Any activity from (&#39;open_session&#39;, &#39;end_session&#39;, &#39;scroll_down&#39;, &#39;send_message&#39;) will be considered valid activity for a user to be considered active on a day.</pre><pre>select activity_date as day, count(distinct user_id) as active_users<br>from activity<br>where activity_date &gt; &#39;2019-06-27&#39; and activity_date &lt;= &#39;2019-07-27&#39;<br>group by activity_date</pre><h3>Relationship between Primary and foreign key:</h3><h4>Primary key:</h4><ul><li>It is a unique ID for each row. (NOTE: No two rows have same primary key)</li><li>basic Syntax:</li></ul><pre>CREATE TABLE students (<br>  student_id INTEGER PRIMARY KEY,<br>  name VARCHAR(100),<br>  age INTEGER<br>);<br>-- SERIAL is used to auto generation of id.<br>CREATE TABLE students (<br>  student_id SERIAL PRIMARY KEY,<br>  name VARCHAR(100)<br>);</pre><h4>-&gt; Primary Key Rules</h4><ol><li><strong>Must be unique</strong> — No duplicates</li><li><strong>Cannot be NULL</strong> — Must have value</li><li><strong>One per table</strong> — Only one Primary Key</li><li><strong>Never changes</strong> — Don’t modify it.</li></ol><h4>Foreign Key:</h4><p>A Foreign Key connects two tables. It points to a Primary Key in another table.</p><p><strong>Example:</strong></p><pre>-- Main table (has Primary Key)<br>CREATE TABLE customers (<br>  customer_id SERIAL PRIMARY KEY,<br>  name VARCHAR(100)<br>);<br>-- Connected table (has Foreign Key)<br>CREATE TABLE orders (<br>  order_id SERIAL PRIMARY KEY,<br>  customer_id INTEGER REFERENCES customers(customer_id),<br>  total DECIMAL(10,2)<br>);</pre><h4>Foreign Key Rules</h4><ol><li><strong>Must reference Primary Key</strong> — Points to PK in another table</li><li><strong>Value must exist</strong> — Can’t reference non-existent customer</li><li><strong>Prevents bad data</strong> — Database rejects invalid references</li><li><strong>Can be NULL</strong> — Optional relationship allowed</li></ol><h4>Joins:</h4><p>SQL joins as name suggest used to combine rows from two or more tables based on a related column between them.</p><p>Here are the different types of JOINs in SQL:</p><ul><li><strong>Inner join:</strong> Returns only rows that have <strong>matching values</strong> in both tables</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/0*yx_qAGvETi29K32Y.png" /><figcaption>Inner Join</figcaption></figure><pre>-- inner join syntax<br>SELECT column_name(s)<br>FROM table1<br>INNER JOIN table2 <br>ON table1.column_name = table2.column_name;<br>/* we can use just JOIN instead of INNER JOIN, as INNER is the default join type*/ </pre><ul><li><strong>Left Outer join:</strong> Returns <strong>all rows from the left table</strong>, and only the matched rows from the right table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*F0Uy1Cue4xDvWdDTf-N-wg.png" /></figure><pre>-- Left join syntax <br>SELECT column_name(s)<br>FROM table1<br>LEFT JOIN table2<br>ON table1.column_name = table2.column_name</pre><ul><li><strong>Right outer join:</strong> Returns <strong>all rows from the right table</strong>, and only the matched rows from the left table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*64vXv9lTGVQMCPhKtH6XNQ.png" /></figure><pre>-- RIGHT JOIN Syntax   <br>SELECT column_name(s)<br>FROM table1<br>RIGHT JOIN table2<br>ON table1.column_name = table2.column_name;</pre><ul><li><strong>full outer Join:</strong> Returns <strong>all rows</strong> when there is a match in either the left or right table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*VHj-mtpbPSHNDN_Wd1D7fA.png" /></figure><pre>--full join syntax<br>SELECT column_name(s)<br>FROM table1<br>FULL JOIN table2<br>ON table1.column_name = table2.column_name<br>WHERE condition;</pre><h4><strong>Cross join:</strong></h4><p>Creates a <strong>Cartesian product</strong> → every row of table A combined with every row of table B. E<strong>xample:</strong> 10 students × 5 subjects = 50 rows.</p><h4>Self Join:</h4><p>A table joins with itself.</p><p><strong>Example:<br></strong>Employees table linked to itself to find manager ↔ employee relationships.</p><pre>SELECT e.name AS employee, m.name AS manager<br>FROM employees e<br>JOIN employees m<br>ON e.manager_id = m.id;</pre><h3><strong>Summary:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*cvhTNB5J61_Jl1dcqP_ozw.png" /></figure><p><strong>Questions on Joins.</strong></p><p><strong>Ques 1: </strong><a href="https://leetcode.com/problems/rising-temperature/"><strong>Rising Temperature</strong></a><strong> (self join)</strong></p><pre>Table: Weather<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| id            | int     |<br>| recordDate    | date    |<br>| temperature   | int     |<br>+---------------+---------+<br>id is the column with unique values for this table.<br>There are no different rows with the same recordDate.<br>This table contains information about the temperature on a certain day.<br><br>Write a solution to find all dates&#39; id with higher temperatures compared to its previous dates (yesterday).<br><br>Return the result table in any order.<br><br>The result format is in the following example.</pre><pre>-- Write your MySQL query statement below <br>select w.id<br>from Weather w join Weather x<br>where DATEDIFF(w.recordDate, x.recordDate)=1 and w.temperature &gt; x.temperature</pre><p><strong>Ques 2: </strong><a href="https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/"><strong>Replace Employee ID With The Unique Identifier</strong></a></p><pre>Table: Employees<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| id            | int     |<br>| name          | varchar |<br>+---------------+---------+<br>id is the primary key (column with unique values) for this table.<br>Each row of this table contains the id and the name of an employee in a company.<br><br>Table: EmployeeUNI<br><br>+---------------+---------+<br>| Column Name   | Type    |<br>+---------------+---------+<br>| id            | int     |<br>| unique_id     | int     |<br>+---------------+---------+<br>(id, unique_id) is the primary key (combination of columns with unique values) for this table.<br>Each row of this table contains the id and the corresponding unique id of an employee in the company.<br><br>Write a solution to show the unique ID of each user, If a user does not have a unique ID replace just show null.<br><br>Return the result table in any order.<br><br>The result format is in the following example.</pre><pre>select b.unique_id, a.name <br>from Employees a left join EmployeeUNI b<br>ON a.id = b.id</pre><p><strong>Ques 3: </strong><a href="https://leetcode.com/problems/product-sales-analysis-i/"><strong>Product Sales Analysis I</strong></a></p><pre>Table: Sales<br><br>+-------------+-------+<br>| Column Name | Type  |<br>+-------------+-------+<br>| sale_id     | int   |<br>| product_id  | int   |<br>| year        | int   |<br>| quantity    | int   |<br>| price       | int   |<br>+-------------+-------+<br>(sale_id, year) is the primary key (combination of columns with unique values) of this table.<br>product_id is a foreign key (reference column) to Product table.<br>Each row of this table shows a sale on the product product_id in a certain year.<br>Note that the price is per unit.<br><br>Table: Product<br><br>+--------------+---------+<br>| Column Name  | Type    |<br>+--------------+---------+<br>| product_id   | int     |<br>| product_name | varchar |<br>+--------------+---------+<br>product_id is the primary key (column with unique values) of this table.<br>Each row of this table indicates the product name of each product.<br><br>Write a solution to report the product_name, year, and price for each sale_id in the Sales table.<br><br>Return the resulting table in any order.<br><br>The result format is in the following example.</pre><pre>SELECT b.product_name, a.year, a.price<br>FROM sales as a left join Product as b<br>ON a.product_id = b.product_id<br><br>/* we have two choices  first use inner join or second use left join, but here Sales.product_id is a foreign key to Product.product_id.<br>That implies every product_id in Sales must exist in Product (referential integrity), so the join will always find a matching product row. <br><br><br>Use LEFT JOIN only if you have a reason to allow sales with missing products and still want to show those rows with NULL product_name. In this schema, that’s not expected, so the JOIN version is more appropriate.*/<br></pre><p><strong>Quest 4: </strong><a href="https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions/"><strong>Customer Who Visited but Did Not Make Any Transactions</strong></a><strong> (Good)</strong></p><pre>Table: Visits<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| visit_id    | int     |<br>| customer_id | int     |<br>+-------------+---------+<br>visit_id is the column with unique values for this table.<br>This table contains information about the customers who visited the mall.<br><br>Table: Transactions<br><br>+----------------+---------+<br>| Column Name    | Type    |<br>+----------------+---------+<br>| transaction_id | int     |<br>| visit_id       | int     |<br>| amount         | int     |<br>+----------------+---------+<br>transaction_id is column with unique values for this table.<br>This table contains information about the transactions made during the visit_id.<br><br>Write a solution to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits.<br><br>Return the result table sorted in any order.<br><br>The result format is in the following example.</pre><pre>select v.customer_id, COUNT(v.visit_id) as count_no_trans<br>from Visits as v left join Transactions as t<br>On v.visit_id = t.visit_id<br>where t.transaction_id IS NULL<br>Group by v.customer_id</pre><h4>Sub Query in SQL:</h4><p>a subquery (also called inner or nested query) is a query inside another query.</p><pre>select column1, column2<br>from table1<br>where column3 (operator) (<br>                            select column3 <br>                            from table2  <br>                             where condition<br>                          );<br> </pre><p><strong>types of subqueries.</strong></p><p>a) Single-row subqueries: (return one row and one column, and usually used with operators)</p><p>b) Multiple-row Subquery: (return multiple rows but have one column, typically used with IN, NOT, ANY, ALL).</p><p>c) Multiple-column Subquery: (return multiple-column subquery)</p><p>d) subquery in select clause:</p><pre>select name, <br>            (select count(*) <br>             from orders <br>             where orders.customer_id = customer.customer_id) AS total orders <br>from customers;</pre><p><strong>Ques: </strong><a href="https://leetcode.com/problems/managers-with-at-least-5-direct-reports/"><strong>Managers with at Least 5 Direct Reports</strong></a></p><pre>Table: Employee<br><br>+-------------+---------+<br>| Column Name | Type    |<br>+-------------+---------+<br>| id          | int     |<br>| name        | varchar |<br>| department  | varchar |<br>| managerId   | int     |<br>+-------------+---------+<br>id is the primary key (column with unique values) for this table.<br>Each row of this table indicates the name of an employee, their department, and the id of their manager.<br>If managerId is null, then the employee does not have a manager.<br>No employee will be the manager of themself.<br><br>Write a solution to find managers with at least five direct reports.<br><br>Return the result table in any order.<br><br>The result format is in the following example.</pre><pre>-- Write your MySQL query statement below<br>select a.name<br>from employee a<br>where id in (<br>  select managerId <br>  from employee <br>  group by managerId <br>  having count(*)&gt;=5 <br>)</pre><p><strong>Ques: </strong><a href="https://leetcode.com/problems/employees-whose-manager-left-the-company/"><strong>1978. Employees Whose Manager Left the Company</strong></a></p><pre>Table: Employees<br><br>+-------------+----------+<br>| Column Name | Type     |<br>+-------------+----------+<br>| employee_id | int      |<br>| name        | varchar  |<br>| manager_id  | int      |<br>| salary      | int      |<br>+-------------+----------+<br>In SQL, employee_id is the primary key for this table.<br>This table contains information about the employees, their salary, and the ID of their manager. Some employees do not have a manager (manager_id is null).<br><br>Find the IDs of the employees whose salary is strictly less than $30000 and whose manager left the company. When a manager leaves the company, their information is deleted from the Employees table, but the reports still have their manager_id set to the manager that left.<br><br>Return the result table ordered by employee_id.<br><br>The result format is in the following example.</pre><pre>SELECT employee_id<br>FROM Employees<br>WHERE salary &lt; 30000<br>AND manager_id IS NOT NULL<br>AND manager_id NOT IN (<br>    SELECT employee_id FROM Employees<br>)<br>ORDER BY employee_id; </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fda526a8a7b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSA Made Simple: From Basics to Advanced Question and Answer.]]></title>
            <link>https://medium.com/@varshneyrajat01/complete-dsa-guide-5de4024ce9ec?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de4024ce9ec</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 19:35:18 GMT</pubDate>
            <atom:updated>2026-04-28T10:14:17.551Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@varshneyrajat01/basic-to-advance-pattern-problems-using-loops-in-c-2f7b145ccd9f">Basic To Advance Pattern Problem in C++;</a></p><h3>0. Bit Manipulation</h3><p>0.1 <a href="https://leetcode.com/problems/single-number/">136. Single Number</a>:</p><pre><strong>Example 1:</strong><br><br>Input: nums = [4,1,2,1,2]<br><br>Output: 4<br><br><strong>Example 2:</strong><br><br>Input: nums = [1]<br><br>Output: 1</pre><p>Because XOR is commutative and associative, the order doesn’t matter. The calculation effectively becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*-7HYIGCoBnn8gRn7dca4pQ.png" /></figure><pre>class Solution {<br>public:<br>    int singleNumber(vector&lt;int&gt;&amp; nums) {<br>        int x=0;<br>        for(int i=0;i&lt;nums.size();i++){<br>            x=x^nums[i];<br>        }<br>        return x;<br>    }<br>};</pre><p>0.2 <a href="https://leetcode.com/problems/power-of-two/">231. Power of Two</a></p><pre>class Solution {<br>public:<br>    bool isPowerOfTwo(int n) {<br>        return n &gt; 0 &amp;&amp; !(n &amp; n - 1);<br>    }<br>};</pre><p>0.3 <a href="https://leetcode.com/problems/missing-number/">268. Missing Number</a></p><pre>class Solution {<br>public:<br>    int missingNumber(vector&lt;int&gt;&amp; nums) {<br>        int res=nums.size();<br><br>        for(int i=0;i&lt;nums.size();i++)<br>        {<br>            res+=i-nums[i];<br>        }<br>        return res;<br>    }<br>};</pre><h3><strong>1: Array</strong></h3><ol><li>1 <a href="https://leetcode.com/problems/pascals-triangle/">118. Pascal’s Triangle</a>.</li></ol><pre>class Solution {<br>public:<br>    int nCr(int n,int r){<br>        long long result=1;<br>        for(int i=0;i&lt;r;i++){<br>            result=result*(n-i);<br>            result=result/(i+1);<br>        }<br>    return (int)(result);<br>    }<br>    vector&lt;vector&lt;int&gt;&gt; generate(int numRows) {<br>        vector&lt;vector &lt;int&gt;&gt; ans;<br>        for(int i=1;i&lt;=numRows;i++){<br>            vector &lt;int&gt; temp;<br>            for(int j=1;j&lt;=i;j++){<br>                temp.push_back(nCr(i-1,j-1));<br>            }<br>            ans.push_back(temp);<br>        }<br>        return ans;<br>    }<br>};</pre><p>1.2 <a href="https://leetcode.com/problems/two-sum/">1. Two Sum</a></p><pre>class Solution {<br>public:<br>    // vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {<br>    // int n=nums.size();<br>    // vector &lt;int&gt; temp;<br>    // for(int i =0;i&lt;n;i++){<br>    //     for(int j=i+1;j&lt;n;j++){<br>    //         if(nums[i]+nums[j]==target){<br>    //             temp.push_back(i);<br>    //             temp.push_back(j);<br>    //             return temp;<br>    //         }<br>    //     }<br>    // }  <br>    // return {-1,-1}; <br>    // }<br>    vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {<br>        unordered_map&lt;int, int&gt; mpp;<br>        int n=nums.size();<br>        for (int i = 0; i &lt; n; i++) {<br>            int num = nums[i];<br>            int moreNeeded = target - num;<br>            if (mpp.find(moreNeeded) != mpp.end()) {<br>                return {mpp[moreNeeded], i};<br>            }<br>            mpp[num] = i;<br>        }<br>        return { -1, -1};<br>    }<br>};</pre><p>1.3 <a href="https://leetcode.com/problems/3sum/">15. 3Sum</a></p><pre>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br><br>class Solution {<br>public:<br>    vector&lt;vector&lt;int&gt;&gt; threeSum(vector&lt;int&gt;&amp; nums) {<br>        vector&lt;vector&lt;int&gt;&gt; ans;<br>        int n = nums.size();<br>        sort(nums.begin(), nums.end());<br>        for (int i = 0; i &lt; n - 2; i++) {<br>            if (i &gt; 0 &amp;&amp; nums[i] == nums[i - 1]) continue; // Skip duplicate elements<br>            <br>            int left = i + 1, right = n - 1;<br>            <br>            // Step 3: Two-pointer approach<br>            while (left &lt; right) {<br>                int sum = nums[i] + nums[left] + nums[right];<br>                <br>                if (sum == 0) {<br>                    ans.push_back({nums[i], nums[left], nums[right]});<br>                    <br>                    // Move both pointers and avoid duplicates<br>                    while (left &lt; right &amp;&amp; nums[left] == nums[left + 1]) left++;<br>                    while (left &lt; right &amp;&amp; nums[right] == nums[right - 1]) right--;<br>                    <br>                    left++;<br>                    right--;<br>                } <br>                else if (sum &lt; 0) {<br>                    left++;  // Increase sum by moving left pointer<br>                } <br>                else {<br>                    right--; // Decrease sum by moving right pointer<br>                }<br>            }<br>        }<br>        return ans;<br>    }<br>};<br><br></pre><p>1.4 <a href="https://leetcode.com/problems/container-with-most-water/">11. Container With Most Water</a></p><pre>class Solution {<br>public:<br>    int maxArea(vector&lt;int&gt;&amp; height) {<br>        int left = 0;<br>        int right = height.size() - 1;<br>        int maxArea = 0;<br><br>        while (left &lt; right) {<br>            int currentArea = min(height[left], height[right]) * (right - left);<br>            maxArea = max(maxArea, currentArea);<br><br>            if (height[left] &lt; height[right]) {<br>                left++;<br>            } else {<br>                right--;<br>            }<br>        }<br>        return maxArea;<br>    }<br>};</pre><p>1.5 <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/">26. Remove Duplicates from Sorted Array</a></p><pre>#include&lt;bits/stdc++.h&gt;<br>class Solution {<br>public:<br>    int removeDuplicates(vector&lt;int&gt;&amp; nums) {<br>        int n=nums.size();<br>        set &lt;int&gt; temp;<br>        for(int i=0;i&lt;n;i++){<br>           temp.insert(nums[i]);<br>        }<br>        int k = temp.size();<br>        int j = 0;<br>        for (int x: temp) {<br>           nums[j++] = x;<br>        }<br>        return k;<br>    }<br>};</pre><p>1.6 <a href="https://leetcode.com/problems/maximum-subarray/">53. Maximum Subarray</a> <strong>(kadane’s algorithm)</strong></p><pre>class Solution {<br>public:<br>    int maxSubArray(vector&lt;int&gt;&amp; nums) {<br>        int maxi= nums[0];<br>        int res= nums[0];<br>        for(int i=1;i&lt;nums.size();i++){<br>            maxi = max(maxi + nums[i], nums[i]);<br>            res = max(res, maxi);<br>        }<br>        return res;<br>    }<br>};</pre><p>1.8 <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">121. Best Time to Buy and Sell Stock</a></p><pre>class Solution {<br>public:<br>    int maxProfit(vector&lt;int&gt;&amp; prices) {<br>        int m=prices.size();<br>        int maxi=0;<br>        int min_price= INT_MAX;<br>        for(int i=0;i&lt;m;i++){<br>            min_price=min(min_price,prices[i]);<br>            maxi=max(maxi,prices[i]-min_price);<br>        }<br>        return maxi;<br>    }<br>};</pre><p>1.9 <a href="https://leetcode.com/problems/peak-index-in-a-mountain-array/">852. Peak Index in a Mountain Array</a></p><pre>class Solution {<br>public:<br>    int peakIndexInMountainArray(vector&lt;int&gt;&amp; arr) {<br>        int n=arr.size();<br>        int left=0;<br>        int right=n-1;<br>        while(left&lt;right){<br>            int mid=left+(right-left)/2;<br>            if(arr[mid]&lt;arr[mid+1]){<br>                left=mid+1;<br>            }else{<br>                right=mid;<br>            }<br>        }<br>        return left;<br>    }<br>};</pre><p>1.10 <a href="https://leetcode.com/problems/tuple-with-same-product/">1726. Tuple with Same Product</a></p><pre>#include &lt;vector&gt;<br>#include &lt;unordered_map&gt;<br>using namespace std;<br><br>class Solution {<br>public:<br>    int tupleSameProduct(vector&lt;int&gt;&amp; nums) {<br>        unordered_map&lt;int, int&gt; productCount;<br>        int n = nums.size();<br>        int result = 0;<br><br>        // Count frequency of each product<br>        for (int i = 0; i &lt; n; i++) {<br>            for (int j = i + 1; j &lt; n; j++) {<br>                int product = nums[i] * nums[j];<br>                productCount[product]++;<br>            }<br>        }<br>        // For each product, calculate the number of tuples<br>        for (auto&amp; [product, count] : productCount) {<br>            if (count &gt; 1) {<br>                result += count * (count - 1) * 4;<br>            }<br>        }<br>        return result;<br>    }<br>};</pre><p>1.11 <a href="https://neetcode.io/problems/is-anagram?list=neetcode150">Valid Anagram</a></p><pre>class Solution {<br>public:<br>    bool isAnagram(string s, string t) {<br>        if(s.length()!=t.length()){<br>            return false;<br>        }<br>        unordered_map&lt;int, int&gt; counts;<br>        unordered_map&lt;int, int&gt; countt;<br>        for(int i=0;i&lt;s.length();i++){<br>            counts[s[i]]++;<br>            countt[t[i]]++;<br>        }<br>        return counts == countt;<br>    }<br>};</pre><h3><strong>2. String</strong></h3><p>2.1 <a href="https://leetcode.com/problems/palindrome-number/">9. Palindrome Number</a></p><pre>class Solution {<br>public:<br>    bool isPalindrome(int x) {<br>        if (x &lt; 0 ){<br>           return false ;<br>        }<br>        int reverse=0;<br>        int temp=x;<br>        while(temp != 0){<br>            int r = temp % 10;<br>            if (reverse &gt; (INT_MAX - r) / 10) {<br>                return false;<br>            }<br>            reverse = reverse*10 + r;<br>            temp /= 10;<br>        }<br>        if (x == reverse){<br>            return true;<br>        }else{<br>            return false;<br>        }   <br>    }<br>};</pre><p>2.2 <a href="https://leetcode.com/problems/valid-palindrome/">125. Valid Palindrome</a></p><pre>#include&lt;bits/stdc++.h&gt;<br>class Solution {<br>public:<br>    bool isPalindrome(string s) {<br>        int left=0;<br>        int right=s.length()-1;<br>        while(left&lt;right){<br>        if(!isalnum(s[left])){<br>            left++;<br>        }<br>        else if(!isalnum(s[right])){<br>            right--;<br>        }<br>        else if(tolower(s[left])!=tolower(s[right])){<br>            return false;<br>        }<br>        else{<br>            left++;<br>            right--;<br>        }<br>        }<br>        return true;<br>    }<br>};</pre><p>2.3 <a href="https://leetcode.com/problems/longest-palindromic-substring/">5. Longest Palindromic Substring</a></p><pre>class Solution {<br>public:<br>    bool pln(int i,int j, string &amp;s){<br>        while(i&lt;j){<br>            if(s[i]!=s[j]){<br>                return false;<br>            }<br>            i++;<br>            j--;<br>        }<br>        return true;<br>    }<br>    string longestPalindrome(string s) {<br>        int n=s.size();<br>        if(n==0){<br>            return &quot;&quot;;<br>        }<br>        string result=&quot;&quot;;<br>        int maxLength=0;<br><br>        for(int i=0;i&lt;n;i++){<br>            for(int j=i;j&lt;n;j++){<br>                if (pln(i, j, s)) {<br>                    int length = j - i + 1;<br>                    if (length &gt; maxLength) {<br>                        maxLength = length;<br>                        result = s.substr(i, length);<br>                    }<br>                }<br>            }<br>        }<br>        return result;<br>    }<br>};</pre><p>2.4 <a href="https://leetcode.com/problems/valid-palindrome-ii/">680. Valid Palindrome II</a></p><pre>class Solution {<br>public:<br>    bool checkPalindrome (string s, int i,int j){<br>        while(i&lt;j){<br>            if(s[i] != s[j]){<br>                return false;<br>            }else{<br>                i++;<br>                j--;<br>            }<br>        }<br>        return true;<br>    }<br>    bool validPalindrome(string s) {<br>        int i=0;<br>        int j=s.length()-1;<br>        while(i&lt;=j){<br>            if(s[i]==s[j]){<br>                i++;<br>                j--;<br>            }else{<br>                bool ans1=checkPalindrome(s,i+1,j);<br>                bool ans2=checkPalindrome(s,i,j-1);<br><br>                return ans1 || ans2;<br>            }<br>        }<br>        return true;<br>    }<br>};</pre><p>2.5 <a href="https://leetcode.com/problems/longest-common-prefix/">14. Longest Common Prefix</a></p><pre>class Solution {<br>public:<br>    string longestCommonPrefix(vector&lt;string&gt;&amp; strs) {<br>        string ans = &quot;&quot;;<br>        sort(strs.begin() ,strs.end());<br>        int n=strs.size();<br>        string first=strs[0],last=strs[n-1];<br>        for(int i=0; i&lt;min(first.size(),last.size());i++){<br>            if(first[i] != last[i]){<br>                return ans;<br>            }<br>            ans += first[i];<br>        } <br>        return ans;<br>    }<br>};</pre><h3>4: Linked List</h3><p>4.1 <a href="https://leetcode.com/problems/add-two-numbers/">2. Add Two Numbers</a>. (use of dummy node)</p><pre>class Solution {<br>public:<br>    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {<br>        ListNode * dummyNode;<br>        ListNode* head;<br>        dummyNode=head= new ListNode(-1);<br>        if(!l1){<br>            return l2;<br>        }<br>        if(!l2){<br>            return l1;<br>        }<br>        int carry=0;<br>        while(l1 || l2){<br>            int firstVal=  l1? l1-&gt;val:0;<br>            int secondVal= l2? l2-&gt;val:0;<br>            int total=firstVal+secondVal+carry;<br>            carry=total / 10;<br>            total=total % 10;<br>            ListNode* newNode= new ListNode(total);<br>            dummyNode-&gt;next= newNode;<br>            dummyNode= dummyNode-&gt;next;<br>            l1= l1? l1-&gt;next: l1;<br>            l2= l2? l2-&gt;next: l2;<br>        }<br>        if(carry){<br>            dummyNode-&gt;next= new ListNode(1);<br>        }<br>        return head-&gt;next;<br>    }<br>};</pre><p>4.2 <a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">19. Remove Nth Node From End of List</a></p><pre>class Solution {<br>public:<br>    ListNode* removeNthFromEnd(ListNode* head, int n) {<br>        ListNode* res = new ListNode(0, head);<br>        ListNode* dummy = res;<br><br>        for (int i = 0; i &lt; n; i++) {<br>            head = head-&gt;next;<br>        }<br>        while (head != nullptr) {<br>            head = head-&gt;next;<br>            dummy = dummy-&gt;next;<br>        }<br>        dummy-&gt;next = dummy-&gt;next-&gt;next;<br>        return res-&gt;next;<br>    }<br>};</pre><p>4.3 <a href="https://leetcode.com/problems/merge-two-sorted-lists/">21. Merge Two Sorted Lists</a></p><pre>class Solution {<br>public:<br>    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {<br>        if(l1==NULL){<br>            return l2;<br>        }<br>        if(l2==NULL){<br>            return l1;<br>        }<br>        ListNode* dummy= new ListNode(-101);<br>        ListNode* head = dummy;<br>        while(l1 != NULL &amp;&amp; l2 != NULL){<br>            if(l1-&gt;val &lt; l2-&gt;val){<br>                ListNode* newnode= new ListNode(l1-&gt;val);<br>                dummy-&gt;next=newnode;<br>                l1=l1-&gt;next;<br>            }else{<br>                ListNode* newnode= new ListNode(l2-&gt;val);<br>                dummy-&gt;next=newnode;<br>                l2=l2-&gt;next;<br>            }<br>            dummy= dummy-&gt;next;<br>        }<br>        if(l1 != NULL){<br>            dummy-&gt;next=l1;<br>        }<br>        if(l2 != NULL){<br>            dummy-&gt;next=l2;<br>        }<br>        return head-&gt;next;<br>    }<br>};</pre><p>4.4 <a href="https://leetcode.com/problems/linked-list-cycle/">141. Linked List Cycle</a></p><pre>class Solution {<br>public:<br>    bool hasCycle(ListNode *head) {<br>        ListNode* fast= head;<br>        ListNode* slow= head;<br>        while( fast != NULL &amp;&amp; fast-&gt;next != NULL /*&amp;&amp; slow != NULL &amp;&amp; slow-&gt;next != NULL*/){<br>            slow= slow-&gt;next;<br>            fast= fast-&gt;next-&gt;next;<br>            if(slow==fast){<br>                return true;<br>            }<br>        }<br>        return false;<br>    }<br>};</pre><h3>5: Stack</h3><p>5.1 <a href="https://leetcode.com/problems/valid-parentheses/"><strong>20. Valid Parentheses</strong></a></p><pre>class Solution {<br>public:<br>    bool isValid(string s) {<br>    stack&lt;char&gt; st;<br>    for (int i = 0; i &lt; s.length(); i++) {<br>        char current = s[i];<br>        if (current == &#39;(&#39; || current == &#39;{&#39; || current == &#39;[&#39;) {<br>            st.push(current);<br>        }<br>        else if (current == &#39;)&#39; || current == &#39;}&#39; || current == &#39;]&#39;) {<br>            if (st.empty()) {<br>                return false;<br>            }<br>            char top = st.top();<br>            if ((current == &#39;)&#39; &amp;&amp; top == &#39;(&#39;) || <br>                (current == &#39;}&#39; &amp;&amp; top == &#39;{&#39;) || <br>                (current == &#39;]&#39; &amp;&amp; top == &#39;[&#39;)) {<br>                st.pop(); <br>            } else {<br>                return false; <br>            }<br>        }<br>    }<br>    // If the stack is empty at the end, all brackets were properly closed<br>    return st.empty();<br>}<br>};</pre><p><a href="https://www.geeksforgeeks.org/problems/infix-to-postfix-1587115620/1"><strong>5.2 Infix to Postfix</strong></a></p><pre>class Solution {<br>  public:<br>    int priority(char c){<br>        if(c== &#39;^&#39;){<br>            return 3;<br>        }else if(c==&#39;*&#39; || c== &#39;/&#39;){<br>            return 2;<br>        }else if(c==&#39;+&#39;|| c==&#39;-&#39;){<br>            return 1;<br>        }else{<br>            return -1;<br>        }<br>    }<br>    string infixToPostfix(string&amp; s) {<br>        // code here<br>        int i=0;<br>        string ans=&quot;&quot;;<br>        stack&lt;char&gt; st;<br>        while(i&lt;s.length()){<br>            if((s[i]&gt;=&#39;A&#39;&amp;&amp; s[i]&lt;=&#39;Z&#39;)||(s[i]&gt;=&#39;a&#39;&amp;&amp; s[i]&lt;=&#39;z&#39;)|| (s[i]&gt;=&#39;0&#39;&amp;&amp; s[i]&lt;=&#39;9&#39;)){<br>                ans += s[i];<br>            }<br>            else if(s[i]==&#39;(&#39;){<br>                st.push(s[i]);<br>            }<br>            else if(s[i]==&#39;)&#39;){<br>                while(st.top() != &#39;(&#39;){<br>                    ans+= st.top();<br>                    st.pop();<br>                }<br>                st.pop();<br>            }<br>            else{<br>                while(!st.empty() &amp;&amp; priority(s[i])&lt;=priority(st.top())){<br>                    ans+= st.top();<br>                    st.pop();<br>                }<br>                st.push(s[i]);<br>            }<br>            <br>            i++;<br>        }<br>        while(!st.empty()){<br>            ans=ans + st.top();<br>            st.pop();<br>        }<br>        return ans;<br>    }<br>};</pre><p>5.3 <a href="https://leetcode.com/problems/min-stack/">155. Min Stack</a></p><pre>class MinStack {<br>    stack&lt;pair&lt;int,int&gt;&gt; st;<br>    long long mini;<br>public:<br>    MinStack() {<br>        <br>    }  <br>    void push(int val) {<br>        if(st.empty()){<br>            st.push({val,val});<br>        }<br>        else{<br>            int minVal=min(val,st.top().second);<br>            st.push({val,minVal});<br>        }<br>    }<br>    void pop() {<br>        st.pop();<br>    }<br>    <br>    int top() {<br>        return st.top().first;<br>    }<br>    <br>    int getMin() {<br>        return st.top().second;<br>    }<br>};    </pre><p>5.4 <a href="https://leetcode.com/problems/next-greater-element-i/">496. Next Greater Element I</a></p><h3>6: Queue</h3><h3>7: Tree</h3><p>7.1 <a href="https://leetcode.com/problems/binary-tree-inorder-traversal/">94. Binary Tree Inorder Traversal</a></p><pre>class Solution {<br>public:<br>    vector&lt;int&gt; inorderTraversal(TreeNode* root) {<br>        vector&lt;int&gt; result;<br>        inorder(root,result);<br>        return result;<br>    }<br>    void inorder(TreeNode* Node, vector&lt;int&gt;&amp; result){<br>        if(Node== NULL){<br>            return ;<br>        }<br>        inorder(Node-&gt;left, result);<br>        result.push_back(Node-&gt;val);<br>        inorder(Node-&gt;right, result);<br>    }<br>};</pre><p>7.2 <a href="https://leetcode.com/problems/path-sum/">112. Path Sum</a></p><pre>class Solution {<br>public:<br>    bool Solve(TreeNode* root, int targetSum, int sum){<br>        if(root==NULL){<br>            return false;<br>        }<br>        sum += root-&gt;val;<br>        if(root-&gt;left==NULL &amp;&amp; root-&gt;right==NULL){<br>            if(sum==targetSum){<br>                return true;<br>            }<br>            else{<br>                return false;<br>            }<br>        }<br>        bool leftAns=Solve(root-&gt;left,targetSum,sum);<br>        bool rightAns=Solve(root-&gt;right,targetSum,sum);<br>        return leftAns||rightAns ;<br>    }<br><br>    bool hasPathSum(TreeNode* root, int targetSum) {<br>        int sum=0;<br>        bool ans=Solve(root,targetSum,sum);<br>        return ans;<br>    }<br>};</pre><p>7.3 <a href="https://leetcode.com/problems/path-sum-ii/">113. Path Sum II</a></p><pre>class Solution {<br>public:<br>    void solve(TreeNode* root, int targetSum,vector&lt;vector&lt;int&gt;&gt; &amp;ans,vector&lt;int&gt; temp,int sum){<br>        if(root==NULL){<br>            return ;<br>        }<br>        sum += root-&gt;val;<br>        temp.push_back(root-&gt;val);<br>        if(!root-&gt;left &amp;&amp; !root-&gt;right){<br>            if(sum==targetSum){<br>                ans.push_back(temp);<br>            }<br>        }<br>        solve(root-&gt;left,targetSum,ans,temp,sum);<br>        solve(root-&gt;right,targetSum,ans,temp,sum);  <br>    }<br>    vector&lt;vector&lt;int&gt;&gt; pathSum(TreeNode* root, int targetSum) {<br>        int sum=0;<br>        vector&lt;vector&lt;int&gt;&gt; ans;<br>        vector&lt;int&gt; temp;<br>        solve(root,targetSum,ans,temp,sum);<br>        return ans;<br>    }<br>};</pre><p>7.4 <a href="https://leetcode.com/problems/balanced-binary-tree/">110. Balanced Binary Tree</a></p><pre>class Solution {<br>public:<br>    int height(TreeNode* root){<br>        if(root==NULL){<br>            return 0;<br>        }<br>        return 1+max(height(root-&gt;left),height(root-&gt;right));<br>    }<br><br>    bool isBalanced(TreeNode* root) {<br>        if(root==NULL){<br>            return true;<br>        }<br>        int l = height(root-&gt;left);<br>        int r = height(root-&gt;right);<br>        if (abs(l-r) &gt; 1) return false;<br><br>        return isBalanced(root-&gt;left) &amp;&amp; isBalanced(root-&gt;right);<br>    }<br>};</pre><p>7.5 <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/">236. Lowest Common Ancestor of a Binary Tree</a></p><pre>class Solution {<br>public:<br>    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {<br>        if(root==NULL){<br>            return NULL;<br>        }<br>        if(root-&gt;val==p-&gt;val){<br>            return p;<br>        }<br>        if(root-&gt;val==q-&gt;val){<br>            return q;<br>        }<br>        TreeNode* leftAns=lowestCommonAncestor(root-&gt;left,p,q);<br>        TreeNode* rightAns=lowestCommonAncestor(root-&gt;right,p,q);<br><br>        if(leftAns==NULL &amp;&amp; rightAns==NULL){<br>            return NULL;<br>        }<br>        else if(leftAns!=NULL &amp;&amp; rightAns==NULL){<br>            return leftAns;<br>        }<br>        else if(leftAns==NULL &amp;&amp; rightAns!=NULL){<br>            return rightAns;<br>        }<br>        else{<br>            return root;<br>        }<br>    }<br>};</pre><p>7.6 <a href="https://leetcode.com/problems/diameter-of-binary-tree/">543. Diameter of Binary Tree</a></p><pre>class Solution {<br>public:<br>    int Height(TreeNode* root){<br>        if(root==NULL){<br>            return 0;<br>        }<br>        return max(Height(root-&gt;left), Height(root-&gt;right)) +1;<br>    }<br><br>    int diameterOfBinaryTree(TreeNode* root) {<br>        if(root == NULL){<br>            return 0;<br>        }<br>        int option1=diameterOfBinaryTree(root-&gt;left);<br>        int option2=diameterOfBinaryTree(root-&gt;right);<br>        int option3=Height(root-&gt;left)+Height(root-&gt;right);<br>        <br>        int diameter= max(option1, max(option2,option3));<br>        return diameter;<br><br>    }<br>};</pre><p>7.7 <a href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/">889. Construct Binary Tree from Preorder and Postorder Traversal</a></p><pre>class Solution {<br>public:<br>    unordered_map&lt;int, int&gt; postOrderIndexMap;    // Map to store the index of each value in postorder.<br><br>    // Function that constructs the binary tree from preorder and postorder traversal vectors.<br>    TreeNode* constructFromPrePost(std::vector&lt;int&gt;&amp; preorder, std::vector&lt;int&gt;&amp; postorder) {<br>        // Fill the map with the postorder values and their indices.<br>        for (int i = 0; i &lt; postorder.size(); ++i) {<br>            postOrderIndexMap[postorder[i]] = i;<br>        }<br>        // Call the recursive build function to construct the tree.<br>        return buildTree(preorder, 0, preorder.size() - 1, postorder, 0, postorder.size() - 1);<br>    }<br><br>private:<br>    TreeNode* buildTree(std::vector&lt;int&gt;&amp; preorder, int preStart, int preEnd,<br>                        std::vector&lt;int&gt;&amp; postorder, int postStart, int postEnd) {<br>        // If there are no elements to construct the tree, return nullptr.<br>        if (preStart &gt; preEnd) return nullptr;<br><br>        // The first value in preorder is the root node value.<br>        TreeNode* root = new TreeNode(preorder[preStart]);<br><br>        // If there is only one node, it is the root of the current subtree.<br>        if (preStart == preEnd) return root;<br><br>        // Find the index of the root of the left subtree in postorder traversal using the map.<br>        int leftRootIndex = postOrderIndexMap[preorder[preStart + 1]];<br>      <br>        // The length of the left subtree in the postorder array can be calculated from the indices.<br>        int leftSubtreeLength = leftRootIndex - postStart + 1;<br><br>        // Recursively construct the left subtree.<br>        root-&gt;left = buildTree(preorder, preStart + 1, preStart + leftSubtreeLength,<br>                               postorder, postStart, leftRootIndex);<br><br>        // Recursively construct the right subtree.<br>        root-&gt;right = buildTree(preorder, preStart + leftSubtreeLength + 1, preEnd,<br>                                postorder, leftRootIndex + 1, postEnd - 1);<br><br>        // Return the root of the constructed subtree.<br>        return root;<br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de4024ce9ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic to Advance Top Pattern problems in C++]]></title>
            <link>https://medium.com/@varshneyrajat01/basic-to-advance-pattern-problems-using-loops-in-c-2f7b145ccd9f?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f7b145ccd9f</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 27 May 2025 08:40:59 GMT</pubDate>
            <atom:updated>2026-04-28T09:12:37.490Z</atom:updated>
            <content:encoded><![CDATA[<p>Question 1: Print Star’s in N-Square structured using loops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*ipr-i7w2MmE0C2f8m20_xQ.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>int n;<br>cin&gt;&gt;n;<br>for(int i=0;i&lt;n;i++){ //outer loop<br>    for(int j=0;j&lt;n;j++){ //inner loop used for printing<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl;           // next line<br>}<br>return 0;<br>}</pre><p>Question 2: Printing star in rectangle (n=4, m=5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*P7s7u-D3KrjF2gnAcRZd_w.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n, m;<br>    cin&gt;&gt;n&gt;&gt;m;<br>    for(int i=0;i&lt;n;i++){        //outer loop<br>        for(int j=0;j&lt;m;j++){    //inner loop used for printing<br>            cout&lt;&lt;&quot;* &quot;;<br>        }<br>        cout&lt;&lt;endl;              //next line<br>    }<br>    return 0;<br>}</pre><p>Question 3: Printing Hollow rectangle Star pattern.</p><pre>* * * * * * * *   <em># row0 contains 8*</em><br>*             *   <em># row1 contains 1* 6space 1*<br></em>*             *   <em># row2 contains 1* 6space 1*<br></em>*             *   <em># row3 contains 1* 6space 1*<br></em>* * * * * * * *   <em># row4 contains 8*</em></pre><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n=5;<br>    int m=8;<br>for(int i=0;i&lt;n; i= i+1){ // outer loop<br>    for(int j=0;j&lt;m; j= j+1){ //inner loop used for printing<br>        if(i==0 || i==n-1){<br>            cout&lt;&lt;&quot;* &quot;;  <br>        }<br>        else{<br>            if(j==0 || j == m-1){<br>                cout&lt;&lt;&quot;* &quot;;<br>            }<br>            else{<br>                cout&lt;&lt;&quot;  &quot;;<br>            }<br>        }<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 4: print left-side star pyramid (let N=5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*8K6Wvx6jOLiPa7ha_kdM-w.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int i=0;i&lt;n; i= i+1){ // outer loop<br>    for(int j=0;j&lt;i+1; j= j+1){ //inner loop used for printing<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 5: Inverted Half pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*vQaH0p_zy3hi4rNA9boeOw.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int i=0;i&lt;n; i= i+1){ // outer loop<br>    for(int j=0;j&lt;n-i; j= j+1){ //inner loop used for printing<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 6: Numeric Half Pyramid: (printing numeric value not *).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*XHzT1umV6VS51YeBCCT-Lg.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int row=0;row&lt;n; row++){ // outer loop<br>    for(int col=0;col&lt;row+1;col++){ //inner loop used for printing<br>        cout&lt;&lt;col+1&lt;&lt;&quot; &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 7: Inverted Numeric Half Pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*onrV60_Z3YR6ID50GfE6qQ.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int row=0;row&lt;n; row++){ // outer loop<br>    for(int col=0;col&lt;n-row;col++){ //inner loop used for printing<br>        cout&lt;&lt;col+1&lt;&lt;&quot; &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 8: Print Full Pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*X2N3eQSXB3mtuzyeFfxXDQ.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int row=0;row&lt;n; row++){ // outer loop<br>    // print Space<br>    for(int col=0;col&lt;n-row-1;col++){<br>        cout&lt;&lt;&quot; &quot;;<br>    }<br>    //print Stars<br>    for(int col=0;col&lt;row+1;col++){<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 9: Print Inverted Full Pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*yK-PW8y6tPzYKlUJMGhgwQ.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int row=0;row&lt;n; row++){ // outer loop<br>    // print Space <br>    for(int col=0;col&lt;row;col++){<br>        cout&lt;&lt;&quot; &quot;;<br>    }<br>    //print star&#39;s<br>    for(int col=0;col&lt;n-row;col++){<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 10: print diamond star pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*Hy8JM62X6bqNepoNWwAOMw.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>for(int row=0;row&lt;n; row++){ // normal pyramid<br>    // print Space<br>    for(int col=0;col&lt;n-row-1;col++){<br>        cout&lt;&lt;&quot; &quot;;<br>    }<br>    //print Stars<br>    for(int col=0;col&lt;row+1;col++){<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>for(int row=0;row&lt;n; row++){ // inverted pyramid<br>    // print Space <br>    for(int col=0;col&lt;row;col++){<br>        cout&lt;&lt;&quot; &quot;;<br>    }<br>    //print star&#39;s<br>    for(int col=0;col&lt;n-row;col++){<br>        cout&lt;&lt;&quot;* &quot;;<br>    }<br>    cout&lt;&lt;endl; // next line<br>}<br>return 0;<br>}</pre><p>Question 11: Hollow Pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*6FKsQnVZZzIMRH2xkh-jIQ.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>    for(int row=0;row&lt;n; row++){ // outer loop<br>      // print Space<br>      for(int col=0;col&lt;n-row-1;col++){<br>          cout&lt;&lt;&quot; &quot;;<br>      }<br>      //print Stars<br>      for(int col=0;col&lt;row+1;col++){<br>        if(col==0 || col== row + 1 - 1){<br>            cout&lt;&lt;&quot;* &quot;;<br>        }<br>        else{<br>            cout&lt;&lt;&quot;  &quot;;<br>        }<br>      }<br>    cout&lt;&lt;endl; // next line<br>    }<br> return 0;<br>}</pre><p>Question 12: Inverted hollow Pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*WyzRS2i54wTQic9no_aIfQ.png" /></figure><pre>#include&lt;iostream&gt;<br>using namespace std;<br>int main (){<br>    int n;<br>    cin&gt;&gt; n;<br>    for(int row=0;row&lt;n;row++){<br>        //space<br>        for(int col=0;col&lt;row;col++){<br>            cout&lt;&lt;&quot; &quot;;<br>        }<br>        //star<br>        for(int col=0;col&lt;n-row;col++){<br>            if(col == 0 || col == n-row-1){<br>                cout&lt;&lt;&quot;* &quot;;<br>            }else{<br>                cout&lt;&lt;&quot;  &quot;;<br>            }<br>        }<br>        cout&lt;&lt;endl;<br>    }<br>    return 0;<br>}</pre><p>Question 13: Hollow diamond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*I653cKaZs0PLomQMz21ePQ.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int num;<br>    cin&gt;&gt;num;<br>    int n=num/2;<br>    for(int row=0;row&lt;n; row++){ // outer loop<br>        // print Space<br>        for(int col=0;col&lt;n-row-1;col++){<br>            cout&lt;&lt;&quot; &quot;;<br>        }<br>        //print Stars<br>        for(int col=0;col&lt;row+1;col++){<br>            if(col==0 || col== row + 1 - 1){<br>                cout&lt;&lt;&quot;* &quot;;<br>            }<br>            else{<br>                cout&lt;&lt;&quot;  &quot;;<br>            }<br>        }<br>        cout&lt;&lt;endl; // next line<br>    }<br>    for(int row=0;row&lt;n;row++){<br>        //space<br>        for(int col=0;col&lt;row;col++){<br>            cout&lt;&lt;&quot; &quot;;<br>        }<br>        //star<br>        for(int col=0;col&lt;n-row;col++){<br>            if(col == 0 || col == n-row-1){<br>                cout&lt;&lt;&quot;* &quot;;<br>            }else{<br>                cout&lt;&lt;&quot;  &quot;;<br>            }<br>            <br>        }<br>        cout&lt;&lt;endl;<br>    }<br>return 0;<br>}</pre><p>Question 14: Combination of all above type of pattern in one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*Vnr8TPaL4u_c2x7QiYwGRw.png" /></figure><pre>#include &lt;iostream&gt; <br>using namespace std;<br>int main(){<br>    int num;<br>    cin&gt;&gt;num;<br>    int n=num/2;<br>    for(int row=0;row&lt;n; row++){<br>        for(int i=0;i&lt;n-row;i++){        // left helf inverted pyramid<br>            cout&lt;&lt;&quot;* &quot;;<br>        }<br>        for(int i=0;i &lt; 2*row + 1;i++){  // full pyramid<br>            cout&lt;&lt;&quot;- &quot;;<br>        }<br>        for(int i=0;i&lt;n-row;i++){        // right helf inverted pyramid<br>            cout&lt;&lt;&quot;* &quot;;<br>        }<br>        cout&lt;&lt;endl;<br>    }<br>    for(int row=0;row&lt;n; row++){ <br>        for(int i=0;i&lt;row+1;i++){         <br>            cout&lt;&lt;&quot;* &quot;;<br>        }<br>        for(int i=0;i &lt; 2*(n-row)-1;i++){<br>            cout&lt;&lt;&quot;- &quot;;<br>        }<br>        for(int i=0;i&lt;row+1;i++){<br>            cout&lt;&lt;&quot;* &quot;;<br>        }<br>        cout&lt;&lt;endl;<br>    }<br>return 0;<br>}</pre><p>Question 15: print character pyramid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*oaxThxwsgiehyxwKojicXA.png" /></figure><pre>#include &lt;iostream&gt;<br>using namespace std;<br>int main(){<br>    int n;<br>    cin&gt;&gt;n;<br>    for(int row=0;row&lt;n;row++){<br>        char ch;<br>        for(int col=0;col&lt;row+1;col++){<br>            int num=col+1;<br>            ch=num+&#39;A&#39;-1;<br>            cout&lt;&lt;ch;<br>        }<br>        for(char alpha=ch; alpha &gt;&#39;A&#39;; ){       //for reversing the pattern<br>            alpha--;<br>            cout&lt;&lt;alpha;   <br>        }<br>        cout&lt;&lt;endl;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f7b145ccd9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problem of the day of Leet Code: (February)]]></title>
            <link>https://medium.com/@varshneyrajat01/potd-leet-code-16d1398f9431?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d1398f9431</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 10:22:14 GMT</pubDate>
            <atom:updated>2025-02-28T16:21:21.882Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/special-array-i/"><strong>1 Feb: 3151. Special Array I</strong></a><strong>:</strong></p><p>→An array is considered <strong>special</strong> if every pair of its adjacent elements contains two numbers with different parity. You are given an array of integers <strong>nums </strong>. Return true if <strong>nums</strong> is a <strong>special</strong> array, otherwise, return <strong>false</strong>.</p><pre>class Solution {<br>public:<br>    bool isArraySpecial(vector&lt;int&gt;&amp; nums) {<br>        int n=nums.size();<br>        if(n==1){<br>            return true;<br>        }<br>        for(int i=0;i&lt;n-1;i++){<br>            int a=nums[i]%2;<br>            int b=nums[i+1]%2;<br>            if(a==b){<br>                return false;<br>            }<br>        }<br>        return true;<br>    }<br>};</pre><p><a href="https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/"><strong>2 feb: 1752. Check if Array Is Sorted and Rotated</strong></a><strong>:</strong></p><p>→Given an array <strong>nums</strong>, return <em>if the </em><strong><em>true</em></strong><em> array was originally sorted in non-decreasing order, then rotated </em><strong><em>some</em></strong><em> number of positions (including zero)</em>. Otherwise, return <strong>false</strong>.</p><pre>#include &lt;algorithm&gt;<br>#include &lt;vector&gt;<br>class Solution {<br>public:<br>    bool check(vector&lt;int&gt;&amp; nums) {<br>        vector &lt;int&gt; arr1(nums.begin(),nums.end());<br>        sort(arr1.begin(),arr1.end());<br>        for(int i=0; i&lt;nums.size();i++){<br>            if(nums==arr1){<br>                return true;<br>            }<br>            rotate(nums.begin(), nums.begin() + 1, nums.end());<br>        }<br>        return false;<br>    }<br>};</pre><p><strong>3 feb: </strong><a href="https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/"><strong>3105. Longest Strictly Increasing or Strictly Decreasing Subarray</strong></a><strong>.</strong></p><p>You are given an array of integers nums. Return <em>the length of the </em><strong><em>longest</em></strong></p><p><em>subarray of </em>nums<em> which is either </em><strong><em>strictly increasing </em></strong><em>or </em><strong><em>strictly decreasing</em></strong>.</p><pre>class Solution {<br>public:<br>    int longestMonotonicSubarray(std::vector&lt;int&gt;&amp; nums) {<br>        int incLength = 1, decLength = 1, maxLength = 1;<br><br>        for (size_t i = 0; i &lt; nums.size() - 1; i++) {<br>            if (nums[i + 1] &gt; nums[i]) {<br>                incLength++;<br>                decLength = 1;<br>            } else if (nums[i + 1] &lt; nums[i]) {<br>                decLength++;<br>                incLength = 1;<br>            } else {<br>                incLength = 1;<br>                decLength = 1;<br>            }<br>            maxLength = std::max(maxLength, std::max(incLength, decLength));<br>        }<br><br>        return maxLength;<br>    }<br>};</pre><p><strong>4 feb: </strong><a href="https://leetcode.com/problems/maximum-ascending-subarray-sum/"><strong>1800. Maximum Ascending Subarray Sum</strong></a><strong>.</strong></p><p>Given an array of positive integers nums, return the <strong>maximum</strong> possible sum of an strictly increasing subarray in<em> </em>nums.A subarray is defined as a contiguous sequence of numbers in an array.</p><pre>class Solution {<br>public:<br>    int maxAscendingSum(vector&lt;int&gt;&amp; nums) {<br>        int currentSum = nums[0], maxSum = currentSum;<br>        <br>        for (int i = 1; i &lt; nums.size(); i++) {<br>            if (nums[i] &gt; nums[i - 1]) {<br>                currentSum += nums[i]; // Extend ascending subarray<br>            } else {<br>                currentSum = nums[i]; // Start new subarray<br>            }<br>            maxSum = max(maxSum, currentSum); // Update max sum<br>        }<br>        <br>        return maxSum;<br>    }<br>};</pre><p><a href="https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/"><strong>5 feb-1790. Check if One String Swap Can Make Strings Equal</strong></a><strong> (today):</strong></p><p>→This function(<strong>areAlmostEqual</strong>) takes two strings, S1 and S2, as input and checks whether you can make S1 and S2 equal by swapping at most one pair of characters in s1.</p><pre>class Solution {<br>public:<br>    bool areAlmostEqual(string s1, string s2) {<br>        int i= -1, j= -1;<br>        int count=0;<br>        for(int k=0;k&lt;s1.length();k++){<br>            if(s1[k] != s2[k]){<br>                count++;<br>                if(i==-1){<br>                    i=k;<br>                }else if(j == -1){<br>                    j=k;<br>                }<br>            }<br>        }<br>        if(count == 0){<br>            return true;<br>        }else if(count==2 &amp;&amp; s1[i]==s2[j] &amp;&amp; s1[j]==s2[i]){<br>            return true;<br>        }<br>        return false;<br>    }<br>};</pre><p><a href="https://leetcode.com/problems/tuple-with-same-product/"><strong>6 feb: 1726. Tuple with Same Product</strong></a><strong>:</strong></p><p>→Given an array nums of <strong>distinct</strong> positive integers, return <em>the number of tuples (a,b,c,d) such that a*b = c*d where a, b, c and d are elements of nums, and a != b != c !=d.</em></p><pre>#include &lt;vector&gt;<br>#include &lt;unordered_map&gt;<br>using namespace std;<br><br>class Solution {<br>public:<br>    int tupleSameProduct(vector&lt;int&gt;&amp; nums) {<br>        unordered_map&lt;int, int&gt; productCount;<br>        int n = nums.size();<br>        int result = 0;<br><br>        // Count frequency of each product<br>        for (int i = 0; i &lt; n; i++) {<br>            for (int j = i + 1; j &lt; n; j++) {<br>                int product = nums[i] * nums[j];<br>                productCount[product]++;<br>            }<br>        }<br>        // For each product, calculate the number of tuples<br>        for (auto&amp; [product, count] : productCount) {<br>            if (count &gt; 1) {<br>                result += count * (count - 1) * 4;<br>            }<br>        }<br><br>        return result;<br>    }<br>};</pre><p><a href="https://leetcode.com/problems/find-the-number-of-distinct-colors-among-the-balls/"><strong>7 feb: 3160. Find the Number of Distinct Colors Among the Balls</strong></a><strong>.</strong></p><p>→You are given an integer limit and a 2D array queries of size n*2 . There are limit+1 balls with <strong>distinct</strong> labels in the range [0, limit]. Initially, all balls are uncolored. For every query in queries that is of the form [x, y], you mark ball x with the color y. After each query, you need to find the number of <strong>distinct</strong> colors among the balls. Return an array result of length n, where result[i] denotes the number of distinct colors <em>after</em> ith query.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;unordered_map&gt;<br>using namespace std;<br><br>class Solution {<br>public:<br>    vector&lt;int&gt; queryResults(int limit, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {<br>        vector&lt;int&gt; result;<br>        unordered_map&lt;int, int&gt; color_count;       // color -&gt; number of balls with this color<br>        unordered_map&lt;int, int&gt; ball_colors;       // ball -&gt; current color<br>        int distinct_colors = 0;<br><br>        for (const auto&amp; query : queries) {<br>            int ball = query[0];<br>            int new_color = query[1];<br><br>            // Check if the ball was previously colored<br>            if (ball_colors.count(ball)) {<br>                int old_color = ball_colors[ball];<br>                if (--color_count[old_color] == 0) {<br>                    color_count.erase(old_color);<br>                    distinct_colors--;<br>                }<br>            }<br><br>            // Assign the new color<br>            if (color_count[new_color] == 0) {<br>                distinct_colors++;<br>            }<br>            color_count[new_color]++;<br>            ball_colors[ball] = new_color;<br><br>            // Store the current number of distinct colors<br>            result.push_back(distinct_colors);<br>        }<br><br>        return result;<br>    }<br>};</pre><p><strong>8 feb : </strong><a href="https://leetcode.com/problems/design-a-number-container-system/"><strong>2349. Design a Number Container System</strong></a></p><p>→ Design a number container system that can do the following:</p><ul><li><strong>Insert </strong>or <strong>Replace</strong> a number at the given index in the system.</li><li><strong>Return </strong>the smallest index for the given number in the system.</li></ul><p>Implement the NumberContainers class:</p><ul><li>NumberContainers() Initializes the number container system.</li><li>void change (int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it.</li><li>int find (int number) Returns the smallest index for the given number , or -1 if there is no index that is filled by number in the system.</li></ul><pre>class NumberContainers {<br>private:<br>    unordered_map&lt;int, int&gt; index_to_number;  // Maps index to number<br>    unordered_map&lt;int, set&lt;int&gt;&gt; number_to_indices;  // Maps number to set of indices<br><br>public:<br>    NumberContainers() {}<br><br>    void change(int index, int number) {<br>        // If the index already exists with a different number<br>        if (index_to_number.count(index)) {<br>            int old_number = index_to_number[index];<br>            if (old_number == number) return; // No change needed<br><br>            // Remove the index from the old number&#39;s set<br>            number_to_indices[old_number].erase(index);<br>        }<br><br>        // Update the index with the new number<br>        index_to_number[index] = number;<br>        number_to_indices[number].insert(index);<br>    }<br><br>    int find(int number) {<br>        if (number_to_indices.count(number) &amp;&amp; !number_to_indices[number].empty()) {<br>            return *number_to_indices[number].begin();  // Smallest index<br>        }<br>        return -1;<br>    }<br>};</pre><p><a href="https://leetcode.com/problems/count-number-of-bad-pairs/"><strong>9 feb: 2364. Count Number of Bad Pairs</strong></a></p><p>You are given a <strong>0-indexed</strong> integer array nums. A pair of indices (i,j) is a <strong>bad pair</strong> if i&lt; j and j - i != nums[j] - nums[i].</p><p>Return<em> the total number of </em><strong><em>bad pairs</em></strong><em> in nums</em>.</p><pre>class Solution {<br>public:<br>    long long countBadPairs(vector&lt;int&gt;&amp; nums) {<br>        unordered_map&lt;int, int&gt; freq;<br>        long long goodPairs = 0;<br>        long long n = nums.size();<br>        <br>        for (int i = 0; i &lt; n; i++) {<br>            int key = nums[i] - i;<br>            goodPairs += freq[key];<br>            freq[key]++;<br>        }<br>        <br>        return  ((n * (n - 1)) / 2) - goodPairs;<br>    }<br>};</pre><p><a href="https://leetcode.com/problems/clear-digits/"><strong>10 feb: 3174. Clear Digits</strong></a></p><p>→ You are given a string s.</p><p>Your task is to remove <strong>all</strong> digits by doing this operation repeatedly:</p><ul><li>Delete the <em>first</em> digit and the <strong>closest</strong> <strong>non-digit</strong> character to its <em>left</em>.</li></ul><p>Return the resulting string after removing all digits.</p><pre>class Solution {<br>public:<br>    string clearDigits(string s) {<br>        string str;<br>        for( char c:s){<br>            if(isdigit(c)){<br>                if(!str.empty())<br>                    str.pop_back();<br>            }<br>            else{<br>                str.push_back(c);<br>            }<br>        }<br>        return str;<br>    }<br>};</pre><p><strong>11 feb. </strong><a href="https://leetcode.com/problems/remove-all-occurrences-of-a-substring/"><strong>1910. Remove All Occurrences of a Substring</strong></a></p><p>Given two strings s and part, perform the following operation on s until <strong>all</strong> occurrences of the substring part are removed:</p><ul><li>Find the <strong>leftmost</strong> occurrence of the substring part and <strong>remove</strong> it from s.</li></ul><p>Return s <em>after removing all occurrences of part</em>.</p><p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p><pre>#include &lt;stack&gt;<br>class Solution {<br>public:<br>    string removeOccurrences(string s, string part) {<br>        string result;  // Using result as a stack<br>        for (char ch : s) {<br>            result.push_back(ch);  // Push character to the &quot;stack&quot;<br><br>            // Check if the last characters match &#39;part&#39;<br>            if (result.size() &gt;= part.size() &amp;&amp; result.substr(result.size() - part.size()) == part) {<br>                result.erase(result.size() - part.size());  // Remove &#39;part&#39;<br>            }<br>        }<br>        return result;<br>    }<br>};</pre><p><strong>12. feb : </strong><a href="https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/"><strong>2342. Max Sum of a Pair With Equal Sum of Digits</strong></a></p><p>You are given a <strong>0-indexed</strong> array nums consisting of <strong>positive</strong> integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].</p><p>Return <em>the </em><strong><em>maximum</em></strong><em> value of </em>nums[i] + nums[j]<em> that you can obtain over all possible indices </em>i<em> and </em>j<em> that satisfy the conditions.</em></p><pre>1st approch<br><br> #include &lt;bits/stdc++.h&gt;<br>using namespace std;<br><br>class Solution {<br>public:<br>    int maximumSum(vector&lt;int&gt;&amp; nums) {<br>        const int MAX_DIGIT_SUM = 90; // Maximum possible sum of digits (for numbers up to 10^9)<br>        int max1[MAX_DIGIT_SUM + 1];  // Largest number for each digit sum<br>        int max2[MAX_DIGIT_SUM + 1];  // Second largest number for each digit sum<br><br>        // Initialize both arrays with -1 (indicating no number yet)<br>        for (int i = 0; i &lt;= MAX_DIGIT_SUM; i++) {<br>            max1[i] = -1;<br>            max2[i] = -1;<br>        }<br><br>        int result = -1; // To keep track of the maximum sum<br><br>        // Mapping process<br>        for (int i = 0; i &lt; nums.size(); i++) {<br>            int sumOfDigits = getDigitSum(nums[i]);<br><br>            if (max1[sumOfDigits] == -1) {<br>                // First number with this digit sum<br>                max1[sumOfDigits] = nums[i];<br>            } else if (nums[i] &gt; max1[sumOfDigits]) {<br>                // New largest number, shift the previous largest to second largest<br>                max2[sumOfDigits] = max1[sumOfDigits];<br>                max1[sumOfDigits] = nums[i];<br>            } else if (nums[i] &gt; max2[sumOfDigits]) {<br>                // Update second largest if applicable<br>                max2[sumOfDigits] = nums[i];<br>            }<br>        }<br><br>        // Find the maximum sum of valid pairs<br>        for (int i = 0; i &lt;= MAX_DIGIT_SUM; i++) {<br>            if (max1[i] != -1 &amp;&amp; max2[i] != -1) {<br>                int currentSum = max1[i] + max2[i];<br>                result = max(result, currentSum);<br>            }<br>        }<br><br>        return result;<br>    }<br><br>private:<br>    // Helper function to calculate the sum of digits<br>    int getDigitSum(int num) {<br>        int sum = 0;<br>        while (num &gt; 0) {<br>            sum += num % 10;<br>            num /= 10;<br>        }<br>        return sum;<br>    }<br>};<br><br></pre><pre>2nd approch<br><br>#include &lt;vector&gt;<br>#include &lt;unordered_map&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;<br><br>class Solution {<br>public:<br>    // Helper function to calculate the sum of digits of a number<br>    int digitSum(int num) {<br>        int sum = 0;<br>        while (num &gt; 0) {<br>            sum += num % 10;<br>            num /= 10;<br>        }<br>        return sum;<br>    }<br><br>    int maximumSum(vector&lt;int&gt;&amp; nums) {<br>        unordered_map&lt;int, vector&lt;int&gt;&gt; digitSumMap;<br>        int maxSum = -1;<br><br>        // Group numbers by their digit sum<br>        for (int num : nums) {<br>            int sum = digitSum(num);<br>            digitSumMap[sum].push_back(num);<br>        }<br><br>        // For each group, find the top two largest numbers<br>        for (auto&amp; entry : digitSumMap) {<br>            vector&lt;int&gt;&amp; group = entry.second;<br>            if (group.size() &gt;= 2) {<br>                // Sort in descending order to get the top two largest numbers<br>                sort(group.rbegin(), group.rend());<br>                maxSum = max(maxSum, group[0] + group[1]);<br>            }<br>        }<br><br>        return maxSum;<br>    }<br>};</pre><p><strong>13. feb : </strong><a href="https://leetcode.com/problems/minimum-operations-to-exceed-threshold-value-ii/"><strong>3066. Minimum Operations to Exceed Threshold Value II</strong></a></p><p>You are given a <strong>0-indexed</strong> integer array nums, and an integer k.</p><p>In one operation, you will:</p><ul><li>Take the two smallest integers x and y in nums.</li><li>Remove x and y from nums.</li><li>Add min(x, y) * 2 + max(x, y) anywhere in the array.</li></ul><p><strong>Note</strong> that you can only apply the described operation if nums contains at least two elements.</p><p>Return <em>the </em><strong><em>minimum</em></strong><em> number of operations needed so that all elements of the array are greater than or equal to</em> k.</p><pre>class Solution {<br>public:<br>    int minOperations(vector&lt;int&gt;&amp; nums, int k) {<br>        priority_queue&lt;long long, vector&lt;long long&gt;, greater&lt;long long&gt;&gt; pq(nums.begin(), nums.end()); // Min heap<br>        int count = 0;<br>        <br>        // If the smallest element is already &gt;= k, return 0<br>        if (pq.top() &gt;= k) return 0;<br>        <br>        while (pq.size() &gt; 1) { <br>            long long min1 = pq.top(); pq.pop();<br>            long long min2 = pq.top(); pq.pop();<br>            <br>            long long newVal = min1 * 2 + min2; // Use long long to prevent overflow<br>            pq.push(newVal);<br>            count++;<br><br>            // If the smallest value in heap is now &gt;= k, we are done<br>            if (pq.top() &gt;= k) return count;<br>        }<br><br>        return count;<br>    }<br>};</pre><p><strong>14 feb: </strong><a href="https://leetcode.com/problems/product-of-the-last-k-numbers/"><strong>1352. Product of the Last K Numbers</strong></a></p><p>Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.</p><p>Implement the ProductOfNumbers class:</p><ul><li>ProductOfNumbers() Initializes the object with an empty stream.</li><li>void add(int num) Appends the integer num to the stream.</li><li>int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.</li></ul><p>The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>using namespace std;<br><br>class ProductOfNumbers {<br>private:<br>    vector&lt;int&gt; prefixProduct;<br>public:<br>    ProductOfNumbers() {<br>        prefixProduct = {1}; // Initialize with 1 for easy multiplication<br>    }<br>    void add(int num) {<br>        if (num == 0) {<br>            prefixProduct = {1}; // Reset on zero, as everything before becomes irrelevant<br>        } else {<br>            prefixProduct.push_back(prefixProduct.back() * num);<br>        }<br>    }<br>    int getProduct(int k) {<br>        int n = prefixProduct.size();<br>        if (k &gt;= n) return 0; // If k exceeds valid range, return 0 (due to reset on zero)<br>        return prefixProduct[n - 1] / prefixProduct[n - 1 - k];<br>    }<br>};</pre><p>15 feb : <a href="https://leetcode.com/problems/find-the-punishment-number-of-an-integer/">2698. Find the Punishment Number of an Integer</a></p><p>Given a positive integer n, return <em>the </em><strong><em>punishment number</em></strong> of n.</p><p>The <strong>punishment number</strong> of n is defined as the sum of the squares of all integers i such that:</p><ul><li>1 &lt;= i &lt;= n</li><li>The decimal representation of i * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.</li></ul><pre>//using recursion<br>class Solution {<br>public:<br>    bool isValid(string &amp;sq, int p,int sum,int&amp; val){<br>        if(p&gt;=sq.size()){<br>            return sum==val;<br>        }<br>        for(int i=0;i+p&lt;sq.size();++i){<br>            int curr_val=stoi(sq.substr(p,i+1));  //stoi change string to integer<br>            if(isValid(sq,i+p+1,sum+curr_val,val)){<br>                return true;<br>            }<br>        }<br>        return false;<br>    }<br>    int punishmentNumber(int n) {<br>        int punishment_num=1;<br>        for(int i=2;i&lt;=n;i++){<br>            string sq=to_string(i*i);  //to_string convert integer to string <br>            if(isValid(sq,0,0,i)){<br>                punishment_num += i*i;<br>            }<br>        }<br>        return punishment_num;<br>    }<br>};<br><br><br><br>// dp solution<br>class Solution {<br>public:<br>    bool findPartitions(int startIndex, int sum, string stringNum,int target, vector&lt;vector&lt;int&gt;&gt;&amp; memo){<br>        if(startIndex == stringNum.size()){<br>            return sum == target;<br>        }<br>        if(sum &gt; target){<br>            return false;<br>        }<br>        if(memo[startIndex][sum] != -1){<br>            return memo[startIndex][sum];<br>        }<br>        bool partitionfound=false;<br>        for (int currentIndex = startIndex; currentIndex &lt; stringNum.size(); currentIndex++) {<br>            string currentString = stringNum.substr(startIndex, currentIndex - startIndex + 1);<br>            int addend = stoi(currentString);<br>            partitionfound = partitionfound || findPartitions(currentIndex + 1, sum + addend,stringNum, target, memo);<br>            if (partitionfound == true){<br>                return true;<br>            }<br>        }<br>        return memo[startIndex][sum] = partitionfound;<br>    }<br>    int punishmentNumber(int n) {<br>        int punishmentNum =0;<br>        for (int currentNum = 1; currentNum &lt;= n; currentNum++) {<br>            int squareNum = currentNum * currentNum;<br>            string stringNum = to_string(squareNum);<br>            vector&lt;vector&lt;int&gt;&gt; memoArray(stringNum.size(), vector&lt;int&gt;(currentNum + 1, -1));<br>            if (findPartitions(0, 0, stringNum, currentNum, memoArray)) {<br>                punishmentNum += squareNum;<br>            }<br>        }<br>        return punishmentNum;<br>    }<br>};</pre><p><strong>16 feb: </strong><a href="https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/"><strong>1718. Construct the Lexicographically Largest Valid Sequence</strong></a></p><p>Given an integer n, find a sequence that satisfies all of the following:</p><ul><li>The integer 1 occurs once in the sequence.</li><li>Each integer between 2 and n occurs twice in the sequence.</li><li>For every integer i between 2 and n, the <strong>distance</strong> between the two occurrences of i is exactly i.</li></ul><p>The <strong>distance</strong> between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|.</p><p>Return <em>the </em><strong><em>lexicographically largest</em></strong><em> sequence. It is guaranteed that under the given constraints, there is always a solution.</em></p><pre>class Solution {<br>public:<br>    vector&lt;int&gt; constructDistancedSequence(int n) {<br>        vector&lt;int&gt; result(2 * n - 1, 0);<br>        vector&lt;bool&gt; used(n + 1, false);<br>        backtrack(result, used, n, 0);<br>        return result;<br>    }<br><br>private:<br>    bool backtrack(vector&lt;int&gt;&amp; result, vector&lt;bool&gt;&amp; used, int n, int index) {<br>        while (index &lt; result.size() &amp;&amp; result[index] != 0) {<br>            index++;<br>        }<br>        if (index == result.size()) {<br>            return true;<br>        }<br><br>        for (int i = n; i &gt;= 1; i--) {<br>            if (used[i]) continue;<br><br>            if (i == 1) {<br>                result[index] = 1;<br>                used[1] = true;<br>                if (backtrack(result, used, n, index + 1)) return true;<br>                result[index] = 0;<br>                used[1] = false;<br>            } else if (index + i &lt; result.size() &amp;&amp; result[index + i] == 0) {<br>                result[index] = i;<br>                result[index + i] = i;<br>                used[i] = true;<br>                if (backtrack(result, used, n, index + 1)) return true;<br>                result[index] = 0;<br>                result[index + i] = 0;<br>                used[i] = false;<br>            }<br>        }<br>        return false;<br>    }<br>};</pre><p><strong>17 feb: </strong><a href="https://leetcode.com/problems/letter-tile-possibilities/"><strong>1079. Letter Tile Possibilities</strong></a></p><p>You have n tiles, where each tile has one letter tiles[i] printed on it.</p><p>Return <em>the number of possible non-empty sequences of letters</em> you can make using the letters printed on those tiles.</p><pre>#include &lt;iostream&gt;<br>#include &lt;unordered_map&gt;<br>using namespace std;<br><br>void backtrack(unordered_map&lt;char, int&gt; &amp;freq, int &amp;count, int n) {<br>    for (auto &amp;[ch, val] : freq) {<br>        if (val &gt; 0) {<br>            count++;  // Count the new sequence<br>            freq[ch]--;  // Use the character<br>            backtrack(freq, count, n);<br>            freq[ch]++;  // Backtrack to restore state<br>        }<br>    }<br>}<br><br>class Solution {<br>public:<br>    int numTilePossibilities(string tiles) {<br>    unordered_map&lt;char, int&gt; freq;<br>    for (char ch : tiles) freq[ch]++;  // Count frequency of each letter<br>    <br>    int count = 0;<br>    backtrack(freq, count, tiles.size());<br>    return count;<br>    }<br>};</pre><p><strong>18 feb: </strong><a href="https://leetcode.com/problems/construct-smallest-number-from-di-string/"><strong>2375. Construct Smallest Number From DI String</strong></a></p><p>You are given a <strong>0-indexed</strong> string pattern of length n consisting of the characters &#39;I&#39; meaning <strong>increasing</strong> and &#39;D&#39; meaning <strong>decreasing</strong>.</p><p>A <strong>0-indexed</strong> string num of length n + 1 is created using the following conditions:</p><ul><li>num consists of the digits &#39;1&#39; to &#39;9&#39;, where each digit is used <strong>at most</strong> once.</li><li>If pattern[i] == &#39;I&#39;, then num[i] &lt; num[i + 1].</li><li>If pattern[i] == &#39;D&#39;, then num[i] &gt; num[i + 1].</li></ul><p>Return <em>the lexicographically </em><strong><em>smallest</em></strong><em> possible string </em>num<em> that meets the conditions.</em></p><pre>class Solution {<br>public:<br>    string smallestNumber(string pattern) {<br>        string result;<br>        stack&lt;int&gt; st;<br>        int num = 1; // Start filling numbers from 1<br>        for (int i = 0; i &lt;= pattern.size(); i++) {<br>            st.push(num++);  // Push the next available number<br>            // If it&#39;s an &#39;I&#39; or end of pattern, pop stack elements<br>            if (i == pattern.size() || pattern[i] == &#39;I&#39;) {<br>                while (!st.empty()) {<br>                    result += to_string(st.top());<br>                    st.pop();<br>                }<br>            }<br>        }<br>        return result;<br>    }<br>};</pre><p><strong>19 feb: </strong><a href="https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/"><strong>1415. The k-th Lexicographical String of All Happy Strings of Length n</strong></a><strong>.</strong></p><p>A <strong>happy string</strong> is a string that:</p><ul><li>consists only of letters of the set [a,b,c].</li><li>s[i] != s[i+1] for all values of i from 1 to s.length()-1 (string is 1-indexed).</li></ul><p>For example, strings <strong>“abc”, “ac”, “b”</strong> and <strong>“abcbabcbcb”</strong> are all happy strings and strings <strong>“aa”, “baa”</strong> and <strong>“ababbc”</strong> are not happy strings.</p><p>Given two integers n and k , consider a list of all happy strings of length n sorted in lexicographical order.</p><p>Return <em>the kth string</em> of this list or return an <strong>empty string</strong> if there are less than k happy strings of length n .</p><pre>class Solution {<br>public:<br>    string result = &quot;&quot;;<br>    int kth;  // Global counter for the kth string<br><br>    // Recursive function to build happy strings.<br>    void dfs(string current, int n) {<br>        // If we built a string of length n:<br>        if (current.size() == n) {<br>            kth--;  // We found one valid string.<br>            if (kth == 0) {<br>                result = current; // kth string found.<br>            }<br>            return;<br>        }<br>        <br>        // Try to add &#39;a&#39;, &#39;b&#39;, &#39;c&#39; in lexicographical order.<br>        for (char c : {&#39;a&#39;, &#39;b&#39;, &#39;c&#39;}) {<br>            // Make sure we don&#39;t add the same character twice consecutively.<br>            if (current.empty() || current.back() != c) {<br>                dfs(current + c, n);<br>                // If we&#39;ve already found the kth string, we can stop early.<br>                if (!result.empty()) return;<br>            }<br>        }<br>    }<br>    <br>    string getHappyString(int n, int k) {<br>        kth = k;<br>        dfs(&quot;&quot;, n);<br>        return result;  // Returns empty string if kth happy string does not exist.<br>    }<br>};</pre><p><strong>20 feb: </strong><a href="https://leetcode.com/problems/find-unique-binary-string/"><strong>1980. Find Unique Binary String</strong></a><strong>.</strong></p><p>Given an array of strings nums containing n <strong>unique</strong> binary strings each of length n, return <em>a binary string of length n that </em><strong><em>does not appear</em></strong><em> in nums. If there are multiple answers, you may return </em><strong><em>any</em></strong><em> of them</em>.</p><pre>//greedy approch<br><br>class Solution {<br>public:<br>// Function to generate all binary strings of length n<br>  void generateAllBinaryStrings(int n, string current, unordered_set&lt;string&gt;&amp; allStrings) {<br>    if (current.length() == n) {<br>        allStrings.insert(current);<br>        return;<br>    }<br>    generateAllBinaryStrings(n, current + &quot;0&quot;, allStrings);<br>    generateAllBinaryStrings(n, current + &quot;1&quot;, allStrings);<br>  }<br><br>  string findDifferentBinaryString(vector&lt;string&gt;&amp; nums) {<br>    int n = nums.size();<br>    unordered_set&lt;string&gt; numsSet(nums.begin(), nums.end()); // Store given strings in a set<br>    <br>    unordered_set&lt;string&gt; allStrings;<br>    generateAllBinaryStrings(n, &quot;&quot;, allStrings); // Generate all possible binary strings<br>    <br>    // Find the first missing binary string<br>    for (const string&amp; str : allStrings) {<br>        if (numsSet.find(str) == numsSet.end()) {<br>            return str;<br>        }<br>    }<br>    <br>    return &quot;&quot;; // Should never reach here<br>  }<br>};<br><br><br><br><br>// Best Solution(2nd approach)<br>class Solution {<br>public:<br>    string findDifferentBinaryString(vector&lt;string&gt;&amp; nums) {<br>        int n=nums[0].size();<br>        string result = &quot;&quot;;<br>        // Cantor&#39;s Diagonalization: Flip the i-th character of the i-th string<br>        for (int i = 0; i &lt; n; i++) {<br>            result += (nums[i][i] == &#39;0&#39;) ? &#39;1&#39; : &#39;0&#39;;<br>        }<br>        return result;<br><br>    }<br>};</pre><p><strong>21 feb: </strong><a href="https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/"><strong>1261. Find Elements in a Contaminated Binary Tree</strong></a></p><p>Given a binary tree with the following rules:</p><ol><li>root.val == 0</li><li>For any treeNode:</li><li>If treeNode.val has a value x and treeNode.left != null, then treeNode.left.val == 2 * x + 1</li><li>If treeNode.val has a value x and treeNode.right != null, then treeNode.right.val == 2 * x + 2</li></ol><p>Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.</p><p>Implement the FindElements class:</p><ul><li>FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.</li><li>bool find(int target) Returns true if the target value exists in the recovered binary tree.</li></ul><pre>class FindElements {<br>    unordered_set&lt;int&gt; values; // Stores recovered values for O(1) lookup<br>    void recover(TreeNode* node, int value) {<br>        if (!node) return;<br>        node-&gt;val = value;       // Restore the correct value<br>        values.insert(value);     // Store in hash set for quick lookup<br>        if (node-&gt;left) recover(node-&gt;left, 2 * value + 1);<br>        if (node-&gt;right) recover(node-&gt;right, 2 * value + 2);<br>    }<br><br>public:<br>    FindElements(TreeNode* root) {<br>        if (root) recover(root, 0);  // Start recovery from root with value 0<br>    }<br>    <br>    bool find(int target) {<br>        return values.count(target); // O(1) average lookup time<br>    }<br>};</pre><p><strong>22 feb: </strong><a href="https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/"><strong>1028. Recover a tree from Preorder Traversal</strong></a><strong>.</strong></p><p>We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D+1 . The depth of the root node is 0. If a node has only one child, that child is guaranteed to be <strong>the left child</strong>. Given the output traversal of this traversal, recover the tree and return <em>its</em> root.</p><pre>class Solution {<br>public:<br>    string s;<br>    int idx=0, level=0;<br>    TreeNode* recoverFromPreorder(string traversal) {<br>        s= traversal;<br>        TreeNode* node= new TreeNode(-1);<br>        helper(node, 0);<br>        return node-&gt;left;<br>    }<br>    void helper(TreeNode* parent, int val){<br>        while(idx&lt;s.length() &amp;&amp; val == level){<br>            int num=0;<br>            while(idx &lt; s.length() &amp;&amp; isdigit(s[idx])){<br>                num = num*10 + (s[idx++] -&#39;0&#39;);<br>            }<br>            TreeNode* node = new TreeNode(num);<br>            if(!parent-&gt; left){<br>                parent-&gt;left = node;<br>            }else{<br>                parent-&gt;right= node;<br>            }<br>            level=0;<br>            while(idx&lt;s.length() &amp;&amp; s[idx]==&#39;-&#39;){<br>                level++;<br>                idx++;<br>            }<br>            helper(node, val+1);<br>        }<br>    }<br>};</pre><p><strong>23 feb: </strong><a href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/"><strong>889. Construct Binary Tree from Preorder and Postorder Traversal</strong></a><strong>:</strong></p><p>Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of <strong>distinct</strong> values and postorder is the postorder traversal of the same tree, reconstruct and return <em>the binary tree</em>.</p><p>If there exist multiple answers, you can <strong>return any</strong> of them.</p><pre>class Solution {<br>public:<br>    unordered_map&lt;int, int&gt; postOrderIndexMap;    // Map to store the index of each value in postorder.<br><br>    // Function that constructs the binary tree from preorder and postorder traversal vectors.<br>    TreeNode* constructFromPrePost(std::vector&lt;int&gt;&amp; preorder, std::vector&lt;int&gt;&amp; postorder) {<br>        // Fill the map with the postorder values and their indices.<br>        for (int i = 0; i &lt; postorder.size(); ++i) {<br>            postOrderIndexMap[postorder[i]] = i;<br>        }<br>        // Call the recursive build function to construct the tree.<br>        return buildTree(preorder, 0, preorder.size() - 1, postorder, 0, postorder.size() - 1);<br>    }<br><br>private:<br>    // Helper function to recursively build the binary tree from preorder and postorder traversal subsets.<br>    TreeNode* buildTree(std::vector&lt;int&gt;&amp; preorder, int preStart, int preEnd,<br>                        std::vector&lt;int&gt;&amp; postorder, int postStart, int postEnd) {<br>        // If there are no elements to construct the tree, return nullptr.<br>        if (preStart &gt; preEnd) return nullptr;<br><br>        // The first value in preorder is the root node value.<br>        TreeNode* root = new TreeNode(preorder[preStart]);<br><br>        // If there is only one node, it is the root of the current subtree.<br>        if (preStart == preEnd) return root;<br><br>        // Find the index of the root of the left subtree in postorder traversal using the map.<br>        int leftRootIndex = postOrderIndexMap[preorder[preStart + 1]];<br>      <br>        // The length of the left subtree in the postorder array can be calculated from the indices.<br>        int leftSubtreeLength = leftRootIndex - postStart + 1;<br><br>        // Recursively construct the left subtree.<br>        root-&gt;left = buildTree(preorder, preStart + 1, preStart + leftSubtreeLength,<br>                               postorder, postStart, leftRootIndex);<br><br>        // Recursively construct the right subtree.<br>        root-&gt;right = buildTree(preorder, preStart + leftSubtreeLength + 1, preEnd,<br>                                postorder, leftRootIndex + 1, postEnd - 1);<br><br>        // Return the root of the constructed subtree.<br>        return root;<br>    }<br>};</pre><p><strong>24 Feb: </strong><a href="https://leetcode.com/problems/most-profitable-path-in-a-tree/"><strong>2467. Most Profitable Path in a Tree</strong></a><strong>.</strong></p><p>There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.</p><p>At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:</p><ul><li>the price needed to open the gate at node i, if amount[i] is negative, or,</li><li>the cash reward obtained on opening the gate at node i, otherwise.</li></ul><p>The game goes on as follows:</p><ul><li>Initially, Alice is at node 0 and Bob is at node bob.</li><li>At every second, Alice and Bob <strong>each</strong> move to an adjacent node. Alice moves towards some <strong>leaf node</strong>, while Bob moves towards node 0.</li><li>For <strong>every</strong> node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:</li><li>If the gate is <strong>already open</strong>, no price will be required, nor will there be any cash reward.</li><li>If Alice and Bob reach the node <strong>simultaneously</strong>, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.</li><li>If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are <strong>independent</strong> of each other.</li></ul><p>Return<em> the </em><strong><em>maximum</em></strong><em> net income Alice can have if she travels towards the optimal leaf node.</em></p><pre>class Solution {<br>public:<br>    int mostProfitablePath(vector&lt;vector&lt;int&gt;&gt;&amp; edges, int bob, vector&lt;int&gt;&amp; amount) {<br>        // Calculate the number of vertices.<br>        int numVertices = edges.size() + 1;<br>        // Create an adjacency list for the graph.<br>        vector&lt;vector&lt;int&gt;&gt; graph(numVertices);<br>      <br>        // Convert the edge list into an adjacency list.<br>        for (const auto&amp; edge : edges) {<br>            int from = edge[0], to = edge[1];<br>            graph[from].emplace_back(to);<br>            graph[to].emplace_back(from);<br>        }<br>      <br>        // Initialize the time-stamps vector with a default value of &#39;n&#39; which is out of bounds.<br>        vector&lt;int&gt; timestamps(numVertices, numVertices);<br>      <br>        // Depth-first search to update the timestamps at which each node can be visited when started from Bob&#39;s location.<br>        function&lt;bool(int, int, int)&gt; dfsUpdateTimeStamps = [&amp;](int vertex, int parent, int time) -&gt; bool {<br>            if (vertex == 0) {<br>                timestamps[vertex] = time;<br>                return true;<br>            }<br>            for (int neighbor : graph[vertex]) {<br>                if (neighbor != parent &amp;&amp; dfsUpdateTimeStamps(neighbor, vertex, time + 1)) {<br>                    timestamps[neighbor] = min(timestamps[neighbor], time + 1);<br>                    return true;<br>                }<br>            }<br>            return false;<br>        };<br>      <br>        // Run DFS from Bob&#39;s position to update the timestamps.<br>        dfsUpdateTimeStamps(bob, -1, 0);<br>        // Bob&#39;s position must have a timestamp of 0.<br>        timestamps[bob] = 0;<br>      <br>        // Variable to store the answer - maximum profit.<br>        int maximumProfit = INT_MIN;<br>      <br>        // Depth-first search to calculate the maximum possible profit while traversing the graph.<br>        function&lt;void(int, int, int, int)&gt; dfsCalculateProfit = [&amp;](int vertex, int parent, int time, int profit) {<br>            // Increment the profit depending on the time relative to the timestamp.<br>            if (time == timestamps[vertex])<br>                profit += amount[vertex] / 2;<br>            else if (time &lt; timestamps[vertex])<br>                profit += amount[vertex];<br>          <br>            // If it&#39;s a leaf node, update the maximum profit.<br>            if (graph[vertex].size() == 1 &amp;&amp; graph[vertex][0] == parent) {<br>                maximumProfit = max(maximumProfit, profit);<br>                return;<br>            }<br>          <br>            // Continue DFS on adjacent nodes to explore further profit opportunities.<br>            for (int neighbor : graph[vertex])<br>                if (neighbor != parent) dfsCalculateProfit(neighbor, vertex, time + 1, profit);<br>        };<br>      <br>        // Start DFS from vertex 0 to calculate the profit.<br>        dfsCalculateProfit(0, -1, 0, 0);<br>      <br>        // Return the maximum calculated profit.<br>        return maximumProfit;<br>    }<br>};</pre><p><strong>25 feb: </strong><a href="https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/"><strong>1524. Number of Sub-arrays With Odd Sum</strong></a></p><p>Given an array of integers arr , return <em>the number of subarrays with an </em><strong><em>odd</em></strong><em> sum</em>. Since the answer can be very large, return it modulo 10^9+7.</p><pre>// class Solution {<br>// public:<br>//     int numOfSubarrays(vector&lt;int&gt;&amp; arr) {<br>//         int count = 0, n = arr.size();<br>//         const int MOD = 1e9 + 7;<br>    <br>//         for (int i = 0; i &lt; n; i++) {<br>//             int sum = 0;<br>//             for (int j = i; j &lt; n; j++) {<br>//                 sum += arr[j];<br>//                 if (sum % 2 != 0) {<br>//                     count = (count + 1) % MOD;<br>//                 }<br>//             }<br>//         }<br>//         return count;<br>//     }<br>// };<br><br><br>class Solution {<br>public:<br>    const int mod= 1e9 + 7;<br>    int numOfSubarrays(vector&lt;int&gt;&amp; arr) {<br>        long long oddCount =0, prefix_sum= 0;<br>        for(int num: arr){<br>            prefix_sum += num;<br>            oddCount = oddCount + prefix_sum % 2;<br>        }<br>        oddCount += (arr.size()-oddCount) * oddCount;<br>        return oddCount % mod;<br>    }<br>};<br><br></pre><p><strong>26 feb: </strong><a href="https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/"><strong>1749. Maximum Absolute Sum of Any Subarray</strong></a></p><p>You are given an integer array nums. The <strong>absolute sum</strong> of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr).</p><p>Return <em>the </em><strong><em>maximum</em></strong><em> absolute sum of any </em><strong><em>(possibly empty)</em></strong><em> subarray of </em>nums.</p><p>Note that abs(x) is defined as follows:</p><ul><li>If x is a negative integer, then abs(x) = -x.</li><li>If x is a non-negative integer, then abs(x) = x.</li></ul><pre>class Solution {<br>public:<br>    int maxAbsoluteSum(vector&lt;int&gt;&amp; nums) {<br>        int max_sum = 0, min_sum = 0, curr_max = 0, curr_min = 0;<br>        for(int num : nums) {<br>            curr_max = max(num, curr_max + num);<br>            curr_min = min(num, curr_min + num);<br>            <br>            max_sum = max(max_sum, curr_max);<br>            min_sum = min(min_sum, curr_min);<br>        }<br>        <br>        return max(abs(max_sum), abs(min_sum));<br>    }<br>};</pre><p><strong>27 feb: </strong><a href="https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/"><strong>873. Length of Longest Fibonacci Subsequence</strong></a><strong>.</strong></p><p>A sequence x1, x2, ..., xn is <em>Fibonacci-like</em> if:</p><ul><li>n &gt;= 3</li><li>xi + xi+1 == xi+2 for all i + 2 &lt;= n</li></ul><p>Given a <strong>strictly increasing</strong> array arr of positive integers forming a sequence, return <em>the </em><strong><em>length</em></strong><em> of the longest Fibonacci-like subsequence of</em> arr. If one does not exist, return 0. A <strong>subsequence</strong> is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].</p><pre>class Solution {<br>public:<br>    int lenLongestFibSubseq(vector&lt;int&gt;&amp; arr) {<br>        int n = arr.size();<br>        vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n, 0));<br>        int maxLen = 0;<br><br>        for (int curr = 2; curr &lt; n; curr++) {<br>            int start = 0, end = curr - 1;<br>            while (start &lt; end) {<br>                int pairSum = arr[start] + arr[end];<br>                if (pairSum &gt; arr[curr]) {<br>                    end--;<br>                } else if (pairSum &lt; arr[curr]) {<br>                    start++;<br>                } else {<br>                    dp[end][curr] = dp[start][end] + 1;<br>                    maxLen = max(dp[end][curr], maxLen);<br>                    end--;<br>                    start++;<br>                }<br>            }<br>        }<br>        return maxLen == 0 ? 0 : maxLen + 2;<br>    }<br>};</pre><p><strong>28 feb: </strong><a href="https://leetcode.com/problems/shortest-common-supersequence/"><strong>1092. Shortest Common Supersequence</strong></a><strong>.</strong></p><p>Given two strings str1 and str2, return <em>the shortest string that has both </em>str1<em> and </em>str2<em> as </em><strong><em>subsequences</em></strong>. If there are multiple valid strings, return <strong>any</strong> of them.</p><p>A string s is a <strong>subsequence</strong> of string t if deleting some number of characters from t (possibly 0) results in the string s.</p><pre>class Solution {<br>public:<br>    string shortestCommonSupersequence(string str1, string str2) {<br>          int m = str1.size(), n = str2.size();<br>    <br>    // Step 1: Compute LCS using DP<br>    vector&lt;vector&lt;int&gt;&gt; dp(m + 1, vector&lt;int&gt;(n + 1, 0));<br><br>    for (int i = 1; i &lt;= m; i++) {<br>        for (int j = 1; j &lt;= n; j++) {<br>            if (str1[i - 1] == str2[j - 1])<br>                dp[i][j] = 1 + dp[i - 1][j - 1];<br>            else<br>                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);<br>        }<br>    }<br><br>    // Step 2: Construct SCS from LCS table<br>    int i = m, j = n;<br>    string scs = &quot;&quot;;<br><br>    while (i &gt; 0 &amp;&amp; j &gt; 0) {<br>        if (str1[i - 1] == str2[j - 1]) {<br>            scs += str1[i - 1];  // Add common character<br>            i--; j--;<br>        } else if (dp[i - 1][j] &gt; dp[i][j - 1]) {<br>            scs += str1[i - 1];  // Add unique char from str1<br>            i--;<br>        } else {<br>            scs += str2[j - 1];  // Add unique char from str2<br>            j--;<br>        }<br>    }<br><br>    // Add remaining characters from str1 or str2<br>    while (i &gt; 0) {<br>        scs += str1[i - 1];<br>        i--;<br>    }<br>    while (j &gt; 0) {<br>        scs += str2[j - 1];<br>        j--;<br>    }<br><br>    // Reverse the constructed string<br>    reverse(scs.begin(), scs.end());<br>    return scs; <br>    }<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d1398f9431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 150 DSA Sheet To Crack Any Coding Interview]]></title>
            <link>https://medium.com/@varshneyrajat01/top-150-dsa-sheet-to-crack-any-coding-interview-22dcea5fbd9a?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/22dcea5fbd9a</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 13:26:11 GMT</pubDate>
            <atom:updated>2025-01-31T13:26:11.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9mm4dUdi9Nr2MwEmiXU-lw.png" /></figure><p><strong>→ Bit Manipulation</strong></p><ol><li><a href="https://leetcode.com/problems/single-number/">Single Element</a></li><li><a href="https://leetcode.com/problems/single-number-ii/">Single Element 2</a></li><li><a href="https://leetcode.com/problems/single-number-iii/">Single Number 3</a></li><li><a href="https://leetcode.com/problems/divide-two-integers/">Divide 2 Integers</a></li><li><a href="https://practice.geeksforgeeks.org/problems/maximum-and-value-1587115620/1">Max AND Pair.</a></li></ol><p><strong>→ Array</strong></p><ol><li><a href="https://leetcode.com/problems/rotate-array/">Rotate Array</a></li><li><a href="https://leetcode.com/problems/squares-of-a-sorted-array/">Squares of a sorted array</a></li><li><a href="https://leetcode.com/problems/maximum-subarray/">Kadane’s Algo</a></li><li><a href="https://leetcode.com/problems/maximum-product-subarray/">maximum product subarray</a></li><li><a href="https://leetcode.com/problems/majority-element/">majority element</a></li><li><a href="https://leetcode.com/problems/majority-element-ii/">majority element 2</a></li><li><a href="https://leetcode.com/problems/next-greater-element-iii">Next Greater Element III</a></li><li><a href="https://leetcode.com/problems/max-chunks-to-make-sorted/">Max chunks to make sorted</a></li><li><a href="https://leetcode.com/problems/max-chunks-to-make-sorted-ii">Max Chunks To Make Sorted II</a></li><li><a href="https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/">number of subarrays with bounded maximum</a></li><li><a href="https://leetcode.com/problems/first-missing-positive/">First missing positive</a></li><li><a href="https://www.lintcode.com/problem/range-addition/description">Range Addition</a></li><li><a href="https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/">Min No. of Platform</a></li><li><a href="https://leetcode.com/problems/trapping-rain-water/">Trapping rain water</a></li></ol><p><strong>→</strong> <strong>two Pointers</strong></p><ol><li><a href="https://leetcode.com/problems/permutations/">Permutations</a></li><li><a href="https://leetcode.com/problems/permutation-sequence/">Permutation Sequence</a></li><li><a href="https://leetcode.com/problems/combination-sum/">Combination Sum</a></li><li><a href="https://leetcode.com/problems/combination-sum-ii/">Cmbination Sum 2</a></li><li><a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/">Letter combination of Phone number</a></li><li><a href="https://leetcode.com/problems/n-queens/">N Queens</a></li><li><a href="https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1">Rat in a Maze Path</a></li></ol><p><strong>→ Binary Search</strong></p><ol><li><a href="https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/">capacity to ship within D days</a></li><li><a href="https://www.interviewbit.com/problems/painters-partition-problem/#">Painter’s partition problem</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">search in rotated sorted array</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array-ii/">Search in rotated sorted array 2</a></li><li><a href="https://www.interviewbit.com/problems/allocate-books/">Allocate books</a></li><li><a href="https://leetcode.com/problems/median-of-two-sorted-arrays/">median of two sorted array</a></li></ol><p><strong>→ HashMap</strong></p><ol><li><a href="https://www.geeksforgeeks.org/check-whether-arithmetic-progression-can-formed-given-array/">Check AP sequence</a></li><li><a href="https://leetcode.com/problems/grid-illumination/">Grid illumination</a></li><li><a href="https://leetcode.com/problems/brick-wall/">Brick wall</a></li><li><a href="https://leetcode.com/problems/subarray-sum-equals-k/">Count of subarray with sum = k</a></li><li><a href="https://www.pepcoding.com/resources/online-java-foundation/hashmap-and-heap/hashmap-official/ojquestion">Write hashmap</a></li><li><a href="https://www.geeksforgeeks.org/count-subarrays-equal-number-1s-0s/">subarray with equal number of 0 and 1</a></li><li><a href="https://www.geeksforgeeks.org/substring-equal-number-0-1-2/">Substring with equal 0,1 and 2</a></li><li><a href="https://leetcode.com/problems/subarray-sums-divisible-by-k/">Subarray sum divisible by K</a></li><li><a href="https://leetcode.com/problems/longest-consecutive-sequence/">Longest consecutive sequence</a></li><li><a href="https://leetcode.com/problems/insert-delete-getrandom-o1/">Insert Delete GetRandom O(1)</a></li><li><a href="https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/">Insert delete get random duplicates allowed</a></li><li><a href="https://leetcode.com/problems/find-all-anagrams-in-a-string/">Find all anagrams in a string</a></li><li><a href="https://leetcode.com/problems/minimum-window-substring/">Find smallest size of string containing all char of other</a></li></ol><p><strong>→ Heap</strong></p><ol><li><a href="https://leetcode.com/problems/kth-largest-element-in-an-array/">Kth Largest Element</a></li><li><a href="https://leetcode.com/problems/minimum-number-of-refueling-stops/">Minimum number of refueling spots</a></li><li><a href="https://leetcode.com/problems/minimum-cost-to-connect-sticks/">minimum cost to connect sticks</a></li><li><a href="https://leetcode.com/problems/employee-free-time/">Employee Free time</a></li><li><a href="https://leetcode.com/problems/find-median-from-data-stream/">Find Median from Data Stream</a></li></ol><p><strong>→ LinkedList</strong></p><ol><li><a href="https://leetcode.com/problems/reverse-linked-list/">reverse LinkedList</a></li><li><a href="https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/">Find the middle element</a></li><li><a href="https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/">Floyd cycle</a></li><li><a href="https://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/">Clone a linkedlist</a></li><li><a href="https://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/">Intersection point of 2 linked list</a></li><li><a href="https://leetcode.com/problems/lru-cache/">LRU Cache</a></li></ol><p><strong>→ Stacks and Queues</strong></p><ol><li><a href="https://leetcode.com/problems/next-greater-element-i/">Next Greater Element</a></li><li><a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">Largest Rectangular Area Histogram</a></li><li><a href="https://leetcode.com/problems/maximal-rectangle/">maximu size binary matrix containing 1</a></li><li><a href="https://leetcode.com/problems/valid-parentheses/">Valid Parentheses</a></li><li><a href="https://leetcode.com/problems/min-stack/">Min Stack</a></li><li><a href="https://www.geeksforgeeks.org/efficiently-implement-k-stacks-single-array/">K stacks in a single array</a></li><li><a href="https://leetcode.com/problems/basic-calculator/">Infix evaluation</a></li><li><a href="https://www.geeksforgeeks.org/reversing-first-k-elements-queue/">K reverse in a queue</a></li><li><a href="https://www.geeksforgeeks.org/efficiently-implement-k-queues-single-array/">K queue</a></li></ol><p><strong>→ TREES</strong></p><ol><li><a href="https://leetcode.com/problems/binary-tree-preorder-traversal/">Preorder Traversal</a></li><li><a href="https://leetcode.com/problems/binary-tree-inorder-traversal/">Inorder Traversal</a></li><li><a href="https://leetcode.com/problems/binary-tree-postorder-traversal/">Postorder Traversal</a></li><li><a href="https://leetcode.com/problems/binary-tree-right-side-view/">right side view</a></li><li><a href="https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1">Left View</a></li><li><a href="https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1">Top View</a></li><li><a href="https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1">Bottom View</a></li><li><a href="https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/">Vertical order</a></li><li><a href="https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/">Diagonal Traversal</a></li><li><a href="https://leetcode.com/problems/boundary-of-binary-tree/">Boundary Traversal</a></li><li><a href="https://leetcode.com/problems/binary-tree-cameras/">Binary Tree Cameras</a></li><li><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/">Max path sum</a></li><li><a href="https://leetcode.com/problems/delete-node-in-a-bst/">Delete node in bst</a></li><li><a href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/">Construct from inorder and preorder</a></li><li><a href="https://leetcode.com/problems/populating-next-right-pointers-in-each-node/">Next right pointer in each node</a></li><li><a href="https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/">Convert a binary tree to circular doubly linked list</a></li><li><a href="https://www.geeksforgeeks.org/in-place-conversion-of-sorted-dll-to-balanced-bst/">Conversion of sorted DLL to BST</a></li><li><a href="https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-binary-tree/1">Lowest common ancestor</a></li><li><a href="https://leetcode.com/problems/serialize-and-deserialize-binary-tree/">serialize and deserialise</a></li></ol><p><strong>→ Trie</strong></p><ol><li><a href="https://leetcode.com/problems/implement-trie-prefix-tree/">Implement Trie</a></li><li><a href="https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/">Max XOR of two numbers in an array</a></li><li><a href="https://leetcode.com/problems/maximum-xor-with-an-element-from-array/">Maximum XOR with an element from Array</a></li></ol><p><strong>→ DP</strong></p><ol><li><a href="https://leetcode.com/problems/longest-increasing-subsequence/">longest increasing subsequence</a></li><li><a href="https://leetcode.com/problems/longest-increasing-subsequence/">longest increasing subsequence</a></li><li><a href="https://www.geeksforgeeks.org/dynamic-programming-building-bridges/">building bridges</a></li><li><a href="https://leetcode.com/problems/russian-doll-envelopes/">Russian doll envelopes</a></li><li><a href="https://practice.geeksforgeeks.org/problems/box-stacking/1">Box stacking</a></li><li><a href="https://www.lintcode.com/problem/paint-house/description">Paint house</a></li><li><a href="https://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/">No. of binary string without consecutive 1</a></li><li><a href="https://www.geeksforgeeks.org/count-possible-ways-to-construct-buildings/">Possible ways to construct the building</a></li><li><a href="https://www.geeksforgeeks.org/total-number-of-possible-binary-search-trees-with-n-keys/">Total no. of bst</a></li><li>No. of balanced parentheses sequence</li><li><a href="https://leetcode.com/problems/minimum-path-sum/">Min cost path</a></li><li><a href="https://leetcode.com/problems/cherry-pickup/">Cherry pickup</a></li><li><a href="https://leetcode.com/problems/cherry-pickup-ii/">Cherry pickup 2</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">best time to buy and sell stock</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/">best time to buy and sell 2</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/">buy and sell with transaction fee</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/">best time to buy and sell with cool down</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/">best time to buy and sell 3</a></li><li><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/">best time to but and sell 4</a></li><li><a href="https://leetcode.com/problems/burst-balloons/">burst balloons</a></li><li><a href="https://www.geeksforgeeks.org/optimal-binary-search-tree-dp-24/">Optimal BST</a></li><li><a href="https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/">Matrix chain multiplication</a></li><li><a href="https://leetcode.com/problems/longest-common-subsequence/">Longest common subsequence</a></li><li><a href="https://www.geeksforgeeks.org/count-palindromic-subsequence-given-string/">Count all pallindromic subsequence</a></li><li><a href="https://leetcode.com/problems/count-different-palindromic-subsequences/">Count distinct pallindromic subsequence</a></li><li><a href="https://www.geeksforgeeks.org/number-subsequences-form-ai-bj-ck/">No. of sequence of type a^i+b^j+c^k</a></li><li><a href="https://www.geeksforgeeks.org/puzzle-set-35-2-eggs-and-100-floors/">2 egg 100 floor</a></li><li><a href="https://www.geeksforgeeks.org/egg-dropping-puzzle-dp-11/">egg drop</a></li><li><a href="https://leetcode.com/problems/regular-expression-matching/">Regular Expression Matching</a></li><li><a href="https://leetcode.com/problems/palindrome-partitioning-ii/">Palindrome partitioning</a></li><li><a href="https://leetcode.com/problems/frog-jump/">Frog jump</a></li><li><a href="https://leetcode.com/problems/edit-distance/">Edit Distance</a></li><li><a href="https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/">0–1 Knapsack</a></li><li><a href="https://www.geeksforgeeks.org/unbounded-knapsack-repetition-items-allowed/">unbounded knapsack</a></li><li><a href="https://www.geeksforgeeks.org/fractional-knapsack-problem/">Fractional knapsack</a></li><li><a href="https://www.pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/coin-change-combination-official/ojquestion">Coin change combination</a></li><li><a href="https://www.pepcoding.com/resources/online-java-foundation/dynamic-programming-and-greedy/coin-change-permutations-official/ojquestion">Coin change permutation</a></li></ol><p><strong>→ GRAPHS</strong></p><ol><li><a href="https://leetcode.com/problems/number-of-islands">Number of Islands</a></li><li><a href="https://leetcode.com/problems/number-of-distinct-islands">Number of Distinct Islands</a></li><li><a href="https://leetcode.com/problems/rotting-oranges">Rotting Oranges</a></li><li><a href="https://leetcode.com/problems/is-graph-bipartite/">Bipartite graph</a></li><li><a href="https://leetcode.com/problems/bus-routes/">Bus routes</a></li><li><a href="https://www.spoj.com/problems/MST/">Prim’s Algo</a></li><li><a href="https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/">Dijkstra algo</a></li><li><a href="https://leetcode.com/problems/swim-in-rising-water/">swim in rising water</a></li><li><a href="https://leetcode.com/problems/01-matrix/">0–1 matrix</a></li><li><a href="https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/">bellman ford</a></li><li><a href="https://leetcode.com/problems/sliding-puzzle">Sliding Puzzle</a></li><li><a href="https://practice.geeksforgeeks.org/problems/implementing-floyd-warshall/0">Floyd Warshall</a></li><li><a href="https://practice.geeksforgeeks.org/problems/strongly-connected-components-kosarajus-algo/1">Strongly Connected Components (Kosaraju’s Algo)</a></li><li><a href="https://practice.geeksforgeeks.org/problems/mother-vertex/1">Mother Vertex</a></li><li><a href="https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/">Kahn’s algo</a></li><li><a href="https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/">Alien Dictionary</a></li><li><a href="https://www.lintcode.com/en/old/problem/number-of-islands-ii/#">Number of Islands II</a></li><li><a href="https://leetcode.com/problems/regions-cut-by-slashes">Regions Cut By Slashes</a></li><li><a href="https://medium.com/@rebeccahezhang/leetcode-737-sentence-similarity-ii-2ca213f10115">Sentence Similarity II</a></li><li><a href="https://leetcode.com/problems/redundant-connection">Redundant Connection</a></li><li><a href="https://leetcode.com/problems/redundant-connection-ii/">Redundant connection 2</a></li><li><a href="https://www.geeksforgeeks.org/articulation-points-or-cut-vertices-in-a-graph/">Articulation point</a></li><li><a href="https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/">Min swaps required to sort array</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22dcea5fbd9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DeepSeek-R1 vs. ChatGPT: Your AI Matchmaker for 2024 (No Boring Charts, We Promise!)]]></title>
            <link>https://medium.com/@varshneyrajat01/deepseek-r1-vs-chatgpt-your-ai-matchmaker-for-2024-no-boring-charts-we-promise-a376ed6927e0?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a376ed6927e0</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 19:40:18 GMT</pubDate>
            <atom:updated>2025-02-04T14:11:14.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>The AI Assistant Landscape in 2024</h3><p>The AI revolution has resulted in the creation of tools designed for specific purposes. While generalists such as ChatGPT steal the spotlight, other tools like DeepSeek-R1 are utilized by experts in other fields. Let’s highlight what differentiates these two with the help of performance metrics, user studies, and case studies.</p><h3>Let’s Meet the Models.</h3><h4>DeepSeek-R1</h4><ul><li>Develper: DeepSeek (China), AGI-focused and tech-centric.</li><li>Training Data: 40% STEM resources, 30% Chinese language, 30% general knowledge.</li><li>Mission: “Solve, don’t sermonize. “</li></ul><h4>ChatGPT</h4><ul><li>Developer: OpenAI (U.S.), focused on accessibility.</li><li>Training Data: 15% STEM, 50% literature/web material, 35% multilingual datasets.</li><li>Mission: “Conversation without constraints. ”</li></ul><h3>Head-to-Head Performance</h3><h4>1. Technical Tasks</h4><p><em>(Hypothetical Graph 1: Accuracy in STEM Benchmarks)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*qUOHMjm6ep9nouqLsA1tBA.png" /><figcaption>Technical task performance</figcaption></figure><p><strong>Key Insight</strong>: DeepSeek-R1’S STEM focused training provides them with advantage around 15–20% for more structured and technical tasks.</p><p>Able to outperform more focused technology and structured tasks.</p><h4>2. Creativity &amp; Fluency</h4><p><em>(Hypothetical Graph 2: User Ratings for Creative Writing)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*RcfRvLBk-jpseSFkUy35ow.png" /></figure><p><strong>Key Insight</strong>: In contrast to DeepSeek-R1, ChatGPT ensures control over factual creativity alone.</p><h3>Language Support Breakdown</h3><p><em>(Hypothetical Table 3: Nuance in Language Processing)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*U5Dvu1NVRjvtaQ68-K2NRA.png" /></figure><h3>Response Philosophy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*nI_XovriNzkQmw49CejJxA.png" /></figure><h3>When to Use Which Tool</h3><h4>DeepSeek-R1 Excels At:</h4><p><strong>Coding &amp; Debugging</strong>:</p><ul><li><em>Example</em>: “Optimize this SQL query for faster joins.”</li><li><strong>Result</strong>: Direct code edits with runtime benchmarks.</li></ul><p><strong>Math/Engineering</strong>:</p><ul><li><em>Example</em>: “Derive the Navier-Stokes equation step-by-step.”</li><li><strong>Result</strong>: LaTeX-formatted proofs, no small talk.</li></ul><p><strong>Chinese-Language Tasks</strong>:</p><ul><li><em>Example</em>: “Write a marketing email in Mandarin for a tech startup.”</li><li><strong>Result</strong>: Culturally nuanced, industry-specific drafts.</li></ul><h4>ChatGPT Shines At:</h4><p><strong>Creative Writing</strong>:</p><ul><li><em>Example</em>: “Write a dystopian short story about AI rebellion.”</li><li><strong>Result</strong>: Character-driven narratives with plot twists.</li></ul><p><strong>Brainstorming</strong>:</p><ul><li><em>Example</em>: “Generate 10 viral TikTok video ideas for a bakery.”</li><li><strong>Result</strong>: Humorous, trend-aligned concepts.</li></ul><p><strong>Multilingual Casual Use</strong>:</p><ul><li><em>Example</em>: “Explain quantum physics to a 5-year-old in Spanish.”</li><li><strong>Result</strong>: Simple analogies with playful language.</li></ul><h3>Ethical Guardrails</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*WKseCFyB7Cltc65_ylQPzw.png" /></figure><h3>The Takeaway</h3><ul><li><strong>Choose DeepSeek-R1</strong> for:</li><li><em>Technical precision (coding, math, engineering).</em></li><li><em>Mandarin fluency and cultural tasks.</em></li><li><em>Time-sensitive, no-nonsense problem-solving.</em></li><li><strong>Choose ChatGPT </strong>for<strong>:</strong></li><li><em>Creative writing and ideation.</em></li><li><em>Multilingual casual conversations.</em></li><li><em>Exploratory, open-ended dialogue.</em></li></ul><h3>When to Use Which Tool</h3><h4>DeepSeek-R1 Excels At:</h4><p><strong>Coding &amp; Debugging</strong>:</p><ul><li><em>Example</em>: “Optimize this SQL query for faster joins.”</li><li><strong>Result</strong>: Direct code edits accompanied by runtime benchmarks.</li></ul><p><strong>Math/Engineering</strong>:</p><ul><li><em>Example</em>: “Derive the Navier-Stokes equation step-by-step.”</li><li><strong>Result</strong>: LaTeX-formatted proofs without unnecessary conversation.</li></ul><p><strong>Chinese-Language Tasks</strong>:</p><ul><li><em>Example</em>: “Write a marketing email in Mandarin for a tech startup.”</li><li><strong>Result</strong>: Drafts that are culturally nuanced and specific to the industry.</li></ul><h4>ChatGPT Shines At:</h4><p><strong>Creative Writing</strong>:</p><ul><li><em>Example</em>: “Write a dystopian short story about AI rebellion.”</li><li><strong>Result</strong>: Narratives driven by characters and filled with plot twists.</li></ul><p><strong>Brainstorming</strong>:</p><ul><li><em>Example</em>: “Generate 10 viral TikTok video ideas for a bakery.”</li><li><strong>Result</strong>: Humorous concepts that align with current trends.</li></ul><p><strong>Multilingual Casual Use</strong>:</p><ul><li><em>Example</em>: “Explain quantum physics to a 5-year-old in Spanish.”</li><li><strong>Result</strong>: Simple analogies presented in a playful manner.</li></ul><h3>Ethical Guardrails</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*WKseCFyB7Cltc65_ylQPzw.png" /></figure><h3>The Takeaway</h3><ul><li><strong>Choose DeepSeek-R1</strong> for:</li><li>Technical precision in coding, math, and engineering.</li><li>Fluency in Mandarin and cultural tasks.</li><li>Time-sensitive problem-solving without fluff<em>.</em></li><li><strong>Choose ChatGPT </strong>for<strong>:</strong></li><li>Creative writing and brainstorming.</li><li>Casual multilingual conversations.</li><li>Exploratory and open-ended discussions.</li></ul><h3>The Future: Specialized AI Ecosystems</h3><p>The era of one-size-fits-all AI is coming to a close. In the future, users will switch between tools like DeepSeek-R1 (for professional tasks) and ChatGPT (for creative endeavors), similar to how one would alternate between a scalpel and a paintbrush. The key to efficiency is using the right tool for the job, rather than relying on just one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a376ed6927e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless Learning of Data Structures and Algorithms]]></title>
            <link>https://medium.com/@varshneyrajat01/effortless-learning-of-data-structures-and-algorithms-fce91b3c2fd6?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce91b3c2fd6</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 11:21:56 GMT</pubDate>
            <atom:updated>2025-01-18T11:21:56.161Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step-by-Step DSA Learning Plan</h3><h3>1. Basics of Programming.</h3><p>If you’re comfortable with the <a href="https://www.geeksforgeeks.org/basics-of-computer-programming-for-beginners/">basics</a>, ensure you’re familiar with:</p><ul><li>Variables, loops, and conditionals.</li><li>Functions (including recursion).</li><li>Basic input/output.</li><li>Arrays and strings.</li></ul><h3>2. Understanding Time and Space Complexity</h3><p>Learn the <a href="https://www.geeksforgeeks.org/complete-guide-on-complexity-analysis/">basics</a> of:</p><ul><li>Big-O Notation.</li><li><a href="https://www.geeksforgeeks.org/complete-guide-on-complexity-analysis/">How to calculate time and space complexity for algorithms</a>.</li><li>Common time complexities like O(1), O(n), O(log n), etc.</li></ul><h3>3. Core Data Structures</h3><p>Start with these, in this order:</p><h4><a href="https://www.geeksforgeeks.org/array-data-structure-guide/">Arrays</a></h4><ul><li>Basics, searching (linear, binary), sorting (bubble, selection, insertion).</li><li>Problems like finding duplicates, subarray sums, etc.</li></ul><h4><a href="https://www.geeksforgeeks.org/linked-list-data-structure/">Linked Lists</a></h4><ul><li>Singly and doubly linked lists.</li><li><a href="https://leetcode.com/discuss/career/448024/topic-wise-problems-for-beginners">Operations</a> like insertion, deletion, reversal.</li></ul><h4><a href="https://www.w3schools.com/cpp/cpp_stacks.asp">Stacks</a> and <a href="https://www.w3schools.com/cpp/cpp_queues.asp">Queues</a></h4><ul><li><strong>Stack</strong>: LIFO operations, balanced parentheses problem.</li><li><strong>Queue</strong>: FIFO operations, circular queues.</li></ul><h4><a href="https://www.geeksforgeeks.org/hashing-data-structure/">Hashing</a></h4><ul><li>Hash tables, collision handling.</li><li>Problems like two-sum, frequency count.</li></ul><h4><a href="https://www.geeksforgeeks.org/introduction-to-tree-data-structure/">Trees</a></h4><ul><li><strong>Binary Trees</strong>: Traversals (in-order, pre-order, post-order).</li><li><a href="https://www.geeksforgeeks.org/tree-c-cpp-programs/"><strong>Binary Search Trees</strong></a><strong> (BST)</strong>.</li></ul><h4><a href="https://www.w3schools.com/dsa/dsa_theory_graphs.php">Graphs</a></h4><ul><li>Representations (adjacency list, matrix).</li><li><a href="https://www.javatpoint.com/breadth-first-search-algorithm">BFS</a>, <a href="https://www.javatpoint.com/depth-first-search-algorithm">DFS</a>.</li></ul><h4><a href="https://www.geeksforgeeks.org/heap-data-structure/">Heaps</a></h4><ul><li>Min-heap and max-heap.</li><li>Applications like priority queues.</li></ul><h4>Advanced Data Structures (Optional)</h4><ul><li>Tries, Segment Trees, <a href="https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/">Fenwick Trees</a>.</li></ul><h3>4. Core Algorithms</h3><p>Learn these step-by-step:</p><h4>Sorting Algorithms</h4><ul><li>QuickSort, MergeSort, HeapSort.</li></ul><h4>Searching Algorithms</h4><ul><li>Binary search, DFS, BFS.</li></ul><h4>Divide and Conquer</h4><ul><li>MergeSort, Binary Search.</li></ul><h4>Dynamic Programming</h4><ul><li>Fibonacci series, knapsack problem, longest common subsequence.</li></ul><h4>Greedy Algorithms</h4><ul><li>Activity selection, Huffman coding.</li></ul><h4>Backtracking</h4><ul><li>N-Queens, solving mazes.</li></ul><h4>Graph Algorithms</h4><ul><li>Dijkstra’s, Kruskal’s, Prim’s, Floyd-Warshall.</li></ul><h3>5. Practice Regularly</h3><p>Start with beginner-friendly platforms like:</p><ul><li><a href="https://leetcode.com/">LeetCode</a> (problems).</li><li><a href="https://www.hackerrank.com/">HackerRank</a>(Basic)<a href="https://www.hackerrank.com/">.</a></li><li><a href="https://codeforces.com/">Codeforces</a> (contests).</li><li><a href="https://www.geeksforgeeks.org/">GeeksforGeeks</a> for DSA resources.</li></ul><h3>6. Build Problem-Solving Habits</h3><p>Dedicate 1–2 hours daily for consistent progress. Focus on solving problems using a step-by-step approach:</p><ol><li>Understand the problem.</li><li>Break it into parts.</li><li>Write pseudo-code or dry-run examples.</li><li>Implement and debug.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce91b3c2fd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first Project: Email Spam Classification Using Machine Learning]]></title>
            <link>https://medium.com/@varshneyrajat01/my-first-project-email-spam-classification-2f9dfb329c47?source=rss-35e7de8cbaae------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f9dfb329c47</guid>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 09:11:49 GMT</pubDate>
            <atom:updated>2025-02-08T16:39:17.819Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hii, I am undergraduate Student. In my collage I work on machine learning project named Email Spam classification. Email spam filtration involves building a model that can classify incoming emails as either spam or legitimate (ham).</em></p><p><em>If you eager to learn data science and want to become data scientist, the best way to learn is build small project like this one. Here I am giving you the insight of my project so if you would wish to make the project or just explore for knowledge purpose.</em></p><p><em>I build a model (you can say machine) and then Train that model by set of test dataset. I used my 80% of data for training purposes. For classification or labeling the data into Spam or Ham. I used Naive Bayes Algorithm to detect Spam-ham Emails. It is based on conditional probability.</em></p><p><strong><em>Basic knowledge needed to understand the project:</em></strong></p><ol><li><em>Python and its libraries like NumPy, panda, Scikit-learn.</em></li><li><em>mathematics(probability)</em></li><li><em>Know about Google Colab or jupytor notebook.</em></li></ol><p>Lets start the project:</p><h3>Introduction</h3><p>Spam emails have become an unavoidable part of digital communication. From promotional messages to phishing scams, filtering out spam emails is crucial to ensuring secure and clutter-free inboxes.</p><p>In this blog, I will walk you through my <strong>Email Spam Classification</strong> project, where I used <strong>machine learning techniques</strong> to classify emails as either <strong>spam</strong> or <strong>ham (legitimate emails).</strong> This project is a great starting point for anyone looking to gain hands-on experience.</p><h3>1. Data Collection</h3><p>For this project, I used the <strong>SMSSpamCollection</strong> dataset, which consists of labeled SMS messages. The dataset was uploaded and read using <strong>Pandas</strong> in <strong>Google Colab</strong>:</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>from google.colab import files<br><br># Upload dataset<br>uploaded = files.upload()<br><br># Load dataset<br>df_sms = pd.read_csv(&#39;SMSSpamCollection2.csv&#39;, encoding=&#39;latin-1&#39;)<br><br># Display first few rows<br>df_sms.head()</pre><p>The dataset contains the following columns:</p><ul><li><strong>v1</strong>: Label (ham for legitimate messages, spam for spam messages).</li><li><strong>v2</strong>: The SMS text.</li></ul><p>After loading the data, I cleaned it by removing unnecessary columns:</p><pre>df_sms = df_sms.drop([&quot;Unnamed: 2&quot;, &quot;Unnamed: 3&quot;, &quot;Unnamed: 4&quot;], axis=1)<br>df_sms = df_sms.rename(columns={&quot;v1&quot;: &quot;label&quot;, &quot;v2&quot;: &quot;SMS&quot;})<br>df_sms.head()</pre><h3>2. Data Cleaning and Preprocessing</h3><p>Since machine learning models require numerical data, we need to convert text-based labels into <strong>binary values</strong> (ham = 0, spam = 1):</p><pre>df_sms[&#39;label&#39;] = df_sms[&#39;label&#39;].map({&#39;ham&#39;: 0, &#39;spam&#39;: 1})<br>df_sms.head()</pre><p>Next, I removed duplicates and checked for missing values:</p><pre>df_sms.drop_duplicates(inplace=True)<br>df_sms.isnull().sum()  # Checking for missing values</pre><p>To prepare the text data for the model, I used <strong>Natural Language Processing (NLP)</strong> techniques:</p><ul><li><strong>Tokenization</strong>: Breaking sentences into words.</li><li><strong>Removing Stopwords</strong>: Eliminating words like <em>“is,” “the,”</em> etc.</li><li><strong>Lemmatization</strong>: Converting words to their root forms.</li></ul><pre>import nltk<br>from nltk.corpus import stopwords<br>from nltk.stem import WordNetLemmatizer<br>import string<br><br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;wordnet&#39;)<br><br>lemmatizer = WordNetLemmatizer()<br>stop_words = set(stopwords.words(&#39;english&#39;))<br><br>def preprocess_text(text):<br>    text = text.lower()<br>    text = &quot;&quot;.join([char for char in text if char not in string.punctuation])  # Remove punctuation<br>    words = text.split()<br>    words = [lemmatizer.lemmatize(word) for word in words if word not in stop_words]<br>    return &quot; &quot;.join(words)<br><br>df_sms[&#39;cleaned_SMS&#39;] = df_sms[&#39;SMS&#39;].apply(preprocess_text)<br>df_sms.head()</pre><h3>3. Exploratory Data Analysis (EDA)</h3><p>Before building the model, I explored the data to understand its distribution:</p><pre>plt.figure(figsize=(6, 4))<br>sns.countplot(x=df_sms[&#39;label&#39;])<br>plt.title(&quot;Distribution of Spam vs Ham Messages&quot;)<br>plt.xlabel(&quot;Message Type (0 = Ham, 1 = Spam)&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.show()</pre><p>This plot helped me identify any imbalance in the dataset.</p><p>To analyze the most common words in spam vs. ham messages, I generated <strong>word clouds</strong>:</p><pre>from wordcloud import WordCloud<br><br>spam_words = &quot; &quot;.join(df_sms[df_sms[&#39;label&#39;] == 1][&#39;cleaned_SMS&#39;])<br>ham_words = &quot; &quot;.join(df_sms[df_sms[&#39;label&#39;] == 0][&#39;cleaned_SMS&#39;])<br><br>plt.figure(figsize=(10, 5))<br>plt.subplot(1, 2, 1)<br>plt.title(&quot;Spam Messages Word Cloud&quot;)<br>plt.imshow(WordCloud().generate(spam_words))<br>plt.axis(&quot;off&quot;)<br><br>plt.subplot(1, 2, 2)<br>plt.title(&quot;Ham Messages Word Cloud&quot;)<br>plt.imshow(WordCloud().generate(ham_words))<br>plt.axis(&quot;off&quot;)<br><br>plt.show()</pre><h3>4. Model Building</h3><p>To convert text into numerical form, I used <strong>TF-IDF Vectorization</strong>:</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br><br>vectorizer = TfidfVectorizer(max_features=3000)<br>X = vectorizer.fit_transform(df_sms[&#39;cleaned_SMS&#39;])<br>y = df_sms[&#39;label&#39;]</pre><p>Then, I split the dataset into <strong>training and testing sets</strong>:</p><pre>from sklearn.model_selection import train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>For classification, I chose the <strong>Naïve Bayes Algorithm</strong> due to its efficiency in text classification:</p><pre>from sklearn.naive_bayes import MultinomialNB<br><br>nb_model = MultinomialNB()<br>nb_model.fit(X_train, y_train)</pre><h3>5. Model Evaluation</h3><p>To evaluate model performance, I calculated <strong>accuracy, precision, recall, and F1-score</strong>:</p><pre>from sklearn.metrics import accuracy_score, classification_report<br><br>y_pred = nb_model.predict(X_test)<br><br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(classification_report(y_test, y_pred))</pre><p>Test the input giveb by user:</p><pre>input_sms=input(&quot;enter the message&quot;)<br>transformed_sms=transform_text(input_sms)<br>X_test_transformed=tfidf.transform([transformed_sms])<br>result=model.predict(X_test_transformed)[0]<br>if result==1:<br>  print(&quot;Ham&quot;)<br>else:<br>  print(&quot; spam&quot;)</pre><p>for more accurate result: <a href="https://github.com/Rkv2001/Email-spam_Classifier">Click here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f9dfb329c47" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>