<?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 Nitesh Kumar Ojha on Medium]]></title>
        <description><![CDATA[Stories by Nitesh Kumar Ojha on Medium]]></description>
        <link>https://medium.com/@coderNitesh101?source=rss-45c4e092579------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3ivAdM2QhCdfffI065MUpw.jpeg</url>
            <title>Stories by Nitesh Kumar Ojha on Medium</title>
            <link>https://medium.com/@coderNitesh101?source=rss-45c4e092579------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:43:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@coderNitesh101/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 Secret Power of Data Types in Data Science]]></title>
            <link>https://medium.com/@coderNitesh101/the-secret-power-of-data-types-in-data-science-7e9e571d6ed7?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e9e571d6ed7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 15:25:11 GMT</pubDate>
            <atom:updated>2025-07-25T15:25:11.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pg0BvZHE1xFTFhjrF2w43Q.png" /></figure><p>When people picture data science, flashy visualizations, trend predictions, or sophisticated machine learning often come to mind. But beneath all this modern magic lies something fundamental and frequently overlooked: deep understanding of the types of data you are working with. Get this step wrong, and even the most advanced algorithm may lead you astray.</p><p>The roots of this wisdom reach back to the work of John Tukey, a brilliant and unconventional statistician. Long before the rise of big data, Tukey predicted that exploring and understanding the nature of our data would matter far more than simply crunching numbers. His guidance helped lay the groundwork for what we now call data science, and his ideas remain essential for anyone looking to extract truth from data, no matter the size or domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>John Tukey and the Dawn of Data Analysis</h3><p>In the early 1960s, statistics meant one primary thing: drawing conclusions about an entire population based on a small, carefully selected sample. This practice, known as inference, was the main goal of the discipline. John Tukey, however, saw beyond this narrow horizon. In his pivotal 1962 paper, “The Future of Data Analysis,” Tukey argued that the act of data exploration was both an art and a science all its own. He championed what he called data analysis, a hands-on, creative process where investigators became detectives, eagerly searching for patterns, relationships, and surprising facts hiding within their data.</p><p>This philosophy took formal shape in Tukey’s 1977 book, “Exploratory Data Analysis.” He introduced simple but powerful visualization tools like boxplots and scatterplots, as well as straightforward statistical summaries such as means, medians, and quantiles. These techniques encourage people to “look at their data” before applying any formal statistical models, because sometimes simple visual clues reveal more than a complex equation ever could.</p><p>Tukey’s profound insight was that technology makes this approach more effective rather than less. As computers became faster and storage cheaper, his emphasis on flexible, iterative exploration set the tone for what we now recognize as modern data science.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>The Data Deluge: How Structure Gives Meaning to Information</h3><p>In today’s world, the volume of data generated each day is breathtaking. From social media posts and online purchases to satellite images and sensor readings from smart refrigerators, information floods in from all directions. Yet most of this data is not immediately ready for analysis.</p><p>Consider a digital photograph. To a computer, it is nothing but a grid of pixels, each pixel containing numbers for red, green, and blue. Text documents are simply sequences of characters strung together, often without clear boundaries between words or paragraphs. Streams of clicks on a website are just time-stamped lists of actions.</p><p>Before analysts or data scientists can extract value from this chaos, they need to provide structure. The most common method is to represent data as tables, with each row corresponding to an observation (such as a person, a transaction, or a moment in time) and each column representing a variable (such as age, purchase amount, or product category).</p><p>At this stage, the nature or type of each variable becomes critically important. Understanding the difference between types of data is what empowers analysts to apply the right tools and draw valid conclusions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>The Building Blocks: Types of Structured Data</h3><p>Every field, project, or analysis boils down to a handful of fundamental data types. Recognizing and using them properly unlocks the true power of data science.</p><p>Let’s take a closer look:</p><h4>Numeric Data</h4><p>Numeric data consists of numbers that can be measured or counted. This type splits into two major categories:</p><ul><li><strong>Continuous Numeric Data:</strong><br>These values can take on <em>any</em> number within a specific range, including fractions and decimals. For example, wind speed, height, temperature, or the weight of a shipment all vary smoothly and can, in theory, be measured with infinite precision. Continuous variables are ideal for methods such as correlation, regression analysis, or time-series forecasting.</li><li><strong>Discrete Numeric Data:</strong><br>These are quantities that can only take on integer values — whole numbers — often counts of things. Examples include the number of times a user logs into an app, the number of products sold during a day, or the count of errors in a batch. Discrete variables call for their own statistical techniques, and knowing this distinction helps prevent subtle mistakes.</li></ul><h4>Categorical Data</h4><p>Categorical data divides all possible values into a fixed set of groups, and comes in two primary forms:</p><ul><li><strong>Nominal Data:<br></strong>Here, categories have no logical order or ranking. A customer’s home city, the brand of a device, or the type of fruit in a fruit basket are all nominal data. These labels are useful for grouping and counting but cannot sensibly be averaged or arranged in sequence.</li><li><strong>Ordinal Data:</strong><br>These categories have an established order, but the distance between them is not necessarily consistent. Think of survey responses where people rate their satisfaction as “Very Unsatisfied,” “Unsatisfied,” “Neutral,” “Satisfied,” and “Very Satisfied.” Similarly, shirt sizes like small, medium, large, and extra-large are ordinal: the order matters, but the difference between “small” and “medium” is not necessarily the same as between “large” and “extra-large.” Recognizing ordinal variables allows analysts to preserve order in graphs and models.</li></ul><h4>Binary Data</h4><p>Binary data, a special form of categorical data, contains only two categories or values. Classic examples include “yes” or “no,” 0 or 1, and “true” or “false.” These variables are everywhere in data science. Whether predicting if a customer will buy a product (yes/no), if a transaction is fraudulent (fraudulent/not fraudulent), or if a medical test result is positive or negative, the simplicity of binary data enables streamlined models and efficient storage.</p><h4>Text and Other Complex Data</h4><p>Not all information fits neatly into the numeric or categorical buckets. Text, such as product reviews or customer feedback, is inherently unstructured and often requires further processing to extract meaning. Images, audio recordings, and clickstreams are complex data types that may eventually be summarized and transformed into structured numeric or categorical variables before formal analysis. Knowing when and how to make these transformations is a core skill for modern data practitioners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Why Data Types Are the Foundation of Valuable Analysis</h3><p>Identifying and using the correct data type for every variable is not just a technical or bureaucratic step. It affects every aspect of your work:</p><ul><li><strong>Visualization Choices:</strong><br>The choice of chart or graph depends entirely on the data’s type. The right visualization makes relationships and trends clear, while the wrong one can mislead. For example, scatterplots are perfect for displaying the relationship between two numeric variables, bar charts reveal patterns in categorical data, and boxplots summarize distributions.</li><li><strong>Appropriate Statistical Methods:</strong><br>Mathematical operations and statistical tests only produce valid results when applied to the right data. You cannot calculate an average of country names, nor can you run a regression on unprocessed text. Tools like regression, classification algorithms, or clustering methods expect certain data types and will produce errors or nonsense unless your data is properly prepared.</li><li><strong>Computation and Performance:</strong><br>Data analysis software, including R and Python’s pandas, automatically uses data type information to select efficient ways to store, manipulate, and process your data. When you flag a column as categorical, your software can make lookups faster and save memory. These are crucial advantages when dealing with big data.</li><li><strong>Data Quality and Integrity:</strong><br>Explicitly defining data types reduces the risk of errors and inconsistencies. In R, for instance, a vector defined as a “factor” will only accept predefined category values. If you try to add a new, unrecognized category, it may issue a warning or treat the value as missing. In databases, using an “enum” data type ensures only allowed categories are entered, preserving data integrity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Practical Examples: Data Types in Action</h3><p>Suppose you are analyzing survey data. The respondent’s age is continuous numeric data, their country is nominal categorical data, their answer to a yes/no question is binary, and their satisfaction rating from 1 to 5 is ordinal. If you try to plot satisfaction ratings as a line chart averaging the values, you might mislead your readers if the distance between the ratings is not equal. By calling out this distinction, you can pick a more accurate visualization, such as a bar plot that clearly displays the actual distribution.</p><p>In business analytics, you might examine website traffic logs. The number of clicks per user is discrete numeric, the source of traffic is nominal categorical, and whether or not the user converted into a sale is binary. By properly labeling and handling each type, you can quickly segment users, identify patterns in conversions, and ensure reliable reporting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Simple Habits for Powerful Analysis</h3><p>Here are a few practical tips that can improve your analyses immediately:</p><ul><li>Always review and label the data types for every variable in your dataset before analysis.</li><li>Communicate with your software, using features like “factor” in R or “category” in pandas, to optimize processing and validation.</li><li>Regularly check data imports for unintentional type conversions, especially when working with unfamiliar or changing datasets.</li><li>Think carefully before changing data types. Converting a numeric variable to categorical discards important information, while treating a category as unstructured text can make analysis harder or less precise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3><strong>Conclusion: Data Types, Tukey’s Legacy, and Your Analytical Edge</strong></h3><p>John Tukey’s insight remains evergreen: Real understanding begins with exploration and familiarity, not with formulas. In today’s world of overwhelming information, turning raw, unprocessed data into structured, well-typed tables is the first and most vital step to reliable analysis.</p><p>By mastering data types, you set yourself up for fewer errors, more meaningful insights, and greater confidence in every conclusion you draw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><p>If you found the post to be useful, consider <strong>following</strong> me here on <a href="https://medium.com/@coderNitesh101"><strong>Medium</strong></a> to never miss any new blog posts and updates.</p><p>Connect with me on <a href="https://www.linkedin.com/in/nitesh-kumar-ojha/">Linkedin</a> and <a href="https://x.com/coderNitesh">X</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e9e571d6ed7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python: A Complete Beginner’s Guide to the World’s Most Popular Language]]></title>
            <link>https://medium.com/@coderNitesh101/python-a-complete-beginners-guide-to-the-world-s-most-popular-language-a34007f4070c?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34007f4070c</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Mon, 26 May 2025 13:30:21 GMT</pubDate>
            <atom:updated>2025-05-26T13:30:21.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoY39R5WcOAR4i-pHkzUrg.png" /></figure><p>Python has become the go-to programming language for millions of developers worldwide, and for good reason. Whether you are a complete beginner taking your first steps into programming or an experienced developer looking to expand your toolkit, Python offers an incredibly welcoming and powerful environment to bring your ideas to life.</p><p>Ready to dive into the exciting world of Python? Let’s go! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>What is Python? 🤔</h3><p>Python is a high-level, interpreted programming language that was created by Guido van Rossum and first released in 1991. Think of Python as a bridge between human language and computer language. It’s designed to be as close to English as possible while still being powerful enough to build complex applications.</p><p>Unlike languages that require you to write lengthy, complicated code, Python emphasizes readability and simplicity. When you look at Python code, you can often understand what it does just by reading it, even if you’re not a programmer. Python follows a philosophy called “The Zen of Python,” which includes principles like “Beautiful is better than ugly” and “Simple is better than complex.”</p><p>Python is an interpreted language, which means you don’t need to compile your code before running it. You can write a line of Python code and execute it immediately, making it perfect for experimentation and learning. It’s also cross-platform, meaning Python programs can run on Windows, macOS, Linux, and many other operating systems without modification.</p><p><strong>Fun fact:</strong> 🎭 The language gets its name from the British comedy series “Monty Python’s Flying Circus”. It’s a testament to the creator’s belief that programming should be fun and enjoyable, not a tedious chore!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Advantages of Python 💪</h3><p>Python’s popularity isn’t accidental, it comes with numerous advantages that make it an excellent choice for both beginners and experts:</p><p><strong>🎯 Easy to Learn and Read</strong>: Python’s syntax is clean and intuitive. Where other languages might require dozens of lines of code, Python often accomplishes the same task in just a few lines. For example, printing “Hello, World!” in Python is simply print(&quot;Hello, World!&quot;) – no complex setup required!</p><p><strong>🎨 Versatile and Flexible</strong>: Python is like a Swiss Army knife in the programming world. You can use it for web development, data analysis, artificial intelligence, automation, scientific computing, and much more. This versatility means you can learn Python once and apply it to virtually any field that interests you.</p><p><strong>👥 Huge Community and Support</strong>: Python has one of the largest and most active programming communities in the world. This means you’ll find extensive documentation, tutorials, forums, and help whenever you encounter a problem. The Python Package Index (PyPI) contains over 400,000 third-party packages that you can easily install and use in your projects!</p><p><strong>⚡ Rapid Development</strong>: Python’s simplicity allows developers to build applications quickly. Companies often choose Python for prototyping because you can test ideas and create working versions of software much faster than with other languages.</p><p><strong>💰 Free and Open Source</strong>: Python is completely free to use, modify, and distribute. You don’t need to pay licensing fees, and you can even contribute to Python’s development if you want to help improve the language.</p><p><strong>📚 Great Libraries and Frameworks</strong>: Python comes with a comprehensive standard library, and the ecosystem includes powerful frameworks like Django for web development, NumPy for scientific computing, and TensorFlow for machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Which Big Tech Platforms Use Python? 🏢</h3><p>Python powers some of the world’s largest and most sophisticated technology platforms. Let’s see who’s in the Python fan club! 🎉</p><p><strong>🔍 Google</strong>: Google has been a major Python supporter since the company’s early days. They use Python for everything from their search algorithms to YouTube’s backend systems. Google’s motto regarding Python is “Python where we can, C++ where we must,” showing their preference for Python’s simplicity and productivity.</p><p><strong>🎬 Netflix</strong>: The streaming giant uses Python extensively for their recommendation algorithms, content delivery systems, and data analysis. Python helps Netflix analyze viewing patterns and suggest shows you might enjoy. Ever wonder how Netflix knows you love sci-fi comedies? That’s Python at work!</p><p><strong>📸 Instagram</strong>: One of the world’s largest social media platforms runs on Django, a Python web framework. Instagram serves hundreds of millions of users daily using Python-based infrastructure. Those selfies and food pics? All powered by Python!</p><p><strong>🎵 Spotify</strong>: The music streaming service uses Python for data analysis, backend services, and their recommendation systems that help you discover new music. Your “Discover Weekly” playlist? Python magic!</p><p><strong>☁️ Dropbox</strong>: The cloud storage company was built primarily with Python. Guido van Rossum, Python’s creator, even worked at Dropbox for several years.</p><p><strong>🚀 NASA</strong>: The space agency uses Python for scientific computing, data analysis, and even controlling some spacecraft systems. Python is literally helping us explore the stars!</p><p><strong>🛒 Amazon</strong>: Uses Python for various services including their recommendation engine and infrastructure automation. Those “customers who bought this also bought” suggestions? Python’s doing the heavy lifting!</p><p><strong>👥 Facebook (Meta)</strong>: Employs Python for production engineering, infrastructure automation, and data analysis across their platforms.</p><p><em>Impressed yet? These companies choose Python because it allows their engineers to write maintainable code quickly, handle massive amounts of data efficiently, and integrate easily with other systems.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Python Can Be Used For: 🛠️</h3><p>Here’s where Python really shows off — its versatility is mind-blowing! Check out all these amazing things you can build:</p><p><strong>🌐 Web Development</strong>: Frameworks like Django and Flask make it easy to build everything from simple websites to complex web applications like Instagram or Pinterest. Python handles the backend logic, database interactions, and server management that power modern websites.</p><p><em>Think about it: Every time you scroll through Instagram, Python is working behind the scenes!</em></p><p><strong>📊 Data Science and Analytics</strong>: Python has become the language of choice for data scientists. Libraries like Pandas, NumPy, and Matplotlib allow you to analyze massive datasets, create beautiful visualizations, and extract meaningful insights from data. Companies use Python to understand customer behavior, predict market trends, and make data-driven decisions.</p><p><strong>🤖 Artificial Intelligence and Machine Learning</strong>: Python dominates the AI field with libraries like TensorFlow, PyTorch, and Scikit-learn. Whether you’re building chatbots, image recognition systems, or predictive models, Python provides the tools to create intelligent applications.</p><p><strong>⚙️ Automation and Scripting</strong>: Python excels at automating repetitive tasks. You can write scripts to organize files, send emails, scrape websites, or automate social media posts. Imagine never having to manually organize your downloads folder again!</p><p><strong>🔬 Scientific Computing</strong>: Researchers and scientists use Python for complex calculations, simulations, and modeling. Python’s libraries can handle everything from physics simulations to bioinformatics research.</p><p><strong>🎮 Game Development</strong>: While not as common as other uses, Python can be used for game development, especially for indie games or prototypes. Libraries like Pygame make it possible to create 2D games entirely in Python.</p><p><strong>💻 Desktop Applications</strong>: You can create desktop software with graphical user interfaces using frameworks like Tkinter, PyQt, or Kivy. Many popular applications have Python components or are built entirely in Python.</p><p><strong>🛡️ Cybersecurity</strong>: Security professionals use Python for penetration testing, network analysis, and creating security tools. Python’s simplicity makes it ideal for quickly writing scripts to test system vulnerabilities.</p><p><strong>📡 Internet of Things (IoT)</strong>: Python runs on devices like Raspberry Pi, making it perfect for IoT projects. You can control sensors, automate home systems, or build robotics projects using Python.</p><p><strong>💹 Finance and Trading</strong>: Banks and financial institutions use Python for algorithmic trading, risk analysis, and financial modeling. Python’s mathematical libraries make it excellent for quantitative analysis. Money talks, and it speaks Python!</p><p><em>Feeling excited about the possibilities? You should be! Python opens doors to virtually every tech field imaginable.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Your Python Adventure Awaits! 🎊</h3><p>Congratulations! You’ve just taken your first step into the incredible world of Python programming!</p><p>From understanding what makes Python special to discovering how tech giants like Google, Netflix, and Instagram use it daily, you now have a solid foundation to build upon. Remember, every expert was once a beginner, and every professional programmer started exactly where you are right now.</p><p>The journey ahead is filled with exciting challenges, “wow and aha!” moments, and the incredible satisfaction of bringing your ideas to life through code. Whether you choose web development, data science, Machine learning, AI, or any other path, Python will be your trusty companion along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🤝 Let’s Connect!</h3><p>Did this post spark your interest in Python? I would love to hear from you!</p><p>👏 <strong>Give this post some claps</strong> if it helped you understand Python better.</p><p>💬 <strong>Drop a comment below</strong> and tell me:</p><ul><li>What excites you most about Python?</li><li>Which application area interests you the most?</li><li>Are you ready to start your Python journey?</li></ul><p>🔔 <strong>Follow me on Medium</strong> for more programming guides, tips, and tutorials that make coding accessible and fun!</p><p>📤 <strong>Share this post</strong> with anyone who’s curious about programming. Let’s help more people discover the amazing world of Python together!</p><p><em>Happy coding, and welcome to the Python community! 🐍💚</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a34007f4070c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 283 : Move Zeroes | by Nitesh Kumar Ojha]]></title>
            <link>https://medium.com/@coderNitesh101/leetcode-283-move-zeroes-by-nitesh-kumar-ojha-b9deffc6404f?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9deffc6404f</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 13:05:07 GMT</pubDate>
            <atom:updated>2025-02-09T13:06:06.351Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 283 : Move Zeroes | by Nitesh Kumar Ojha</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqV9Gf4N-Byu_-I-x1q5Fg.png" /></figure><p><strong>Problem Statement</strong>: Move all zeroes in an array to the end while maintaining the <strong>relative order</strong> of the non-zero elements.</p><p><strong>Example</strong>:</p><ul><li><strong>Input</strong>: [0, 1, 0, 3, 12] → <strong>Output</strong>: [1, 3, 12, 0, 0]</li><li><strong>Input</strong>: [2, 0, 1] → <strong>Output</strong>: [2, 1, 0]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🚫 Why Not Just Create a New Array?</h3><p>A naive approach might create a new array, copy non-zeros first, then fill the rest with zeros.</p><pre>def moveZeroesNaive(nums: List[int]) -&gt; None:<br>    temp = []  # Temporary list to store non-zero elements<br>    <br>    # Step 1: Store all non-zero elements in temp<br>    for num in nums:<br>        if num != 0:<br>            temp.append(num)<br>    <br>    # Step 2: Fill the remaining space with zeros<br>    temp.extend([0] * (len(nums) - len(temp)))<br><br>    # Step 3: Copy temp back to nums<br>    for i in range(len(nums)):<br>        nums[i] = temp[i]</pre><h4><strong>Problem</strong>:</h4><ul><li><strong>Space Complexity</strong>: O(n) → Not allowed! We need an <strong>in-place</strong> solution.</li></ul><p><strong>We need a smarter way without extra space!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🧠 Optimal Approach: The Two-Pointer Technique</h3><h4>Intuition</h4><p>Imagine two pointers, left and right, working together like a <strong>dynamic duo</strong>:</p><ol><li><strong>right pointer</strong>: Scans the entire array to find non-zero elements.</li><li><strong>left pointer</strong>: Marks the position where the next non-zero element should be placed.</li></ol><h4><strong>How it works</strong>:</h4><ul><li>Every time right finds a non-zero, swap it with the element at left, then move left forward.</li><li>This pushes zeros to the right while keeping non-zeros in order!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🛠️ Step-by-Step Example</h3><p>Let’s use nums = [0, 1, 0, 3, 12]:</p><h4>Step 1: Initialize Pointers</h4><ul><li>left = 0, right = 0</li></ul><pre>index 0 1 2 3 4<br>Value 0 1 0 3 12</pre><h4>Step 2: right Finds Non-Zero at Index 1</h4><ul><li>Swap nums[right] (1) with nums[left] (0).</li><li><strong>After swap</strong>: [1, 0, 0, 3, 12]</li><li>Move left to <strong>1</strong>.</li></ul><pre>Index 0 1 2 3 4<br>Value 1 0 0 3 12</pre><h4>Step 3: right Finds Non-Zero at Index 3</h4><ul><li>Swap nums[right] (3) with nums[left] (0).</li><li><strong>After swap</strong>: [1, 3, 0, 0, 12]</li><li>Move left to <strong>2</strong>.</li></ul><pre>Index 0 1 2 3 4<br>Value 1 3 0 0 12</pre><h4>Step 4: right Finds Non-Zero at Index 4</h4><ul><li>Swap nums[right] (12) with nums[left] (0).</li><li><strong>After swap</strong>: [1, 3, 12, 0, 0]</li><li>Move left to <strong>3</strong>.</li></ul><p><strong>Final Result</strong>: [1, 3, 12, 0, 0] ✅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>💻 Code Breakdown</h3><pre>def moveZeroes(nums: List[int]) -&gt; None:<br>    left = 0  # Marks the position for the next non-zero<br>    <br>    for right in range(len(nums)):<br>        if nums[right] != 0:  # Found a non-zero!<br>            # Swap with the `left` position<br>            nums[left], nums[right] = nums[right], nums[left]<br>            left += 1  # Move `left` forward</pre><h3>Code Explanation</h3><ol><li><strong>Initialize </strong><strong>left</strong>: Starts at 0, tracking where the next non-zero should go.</li><li><strong>Loop with </strong><strong>right</strong>: Scans every element.</li><li><strong>Swap &amp; Update</strong>: When a non-zero is found, swap it with nums[left] and increment left.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🧪 Edge Cases</h3><h4>Case 1: All Zeros</h4><ul><li><strong>Input</strong>: [0, 0, 0] → <strong>Output</strong>: [0, 0, 0]</li><li>No swaps needed; the array remains unchanged.</li></ul><h4>Case 2: No Zeros</h4><ul><li><strong>Input</strong>: [5, 2, 9] → <strong>Output</strong>: [5, 2, 9]</li><li>Non-zeros are already in place; left and right move together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>⏱️ Time &amp; Space Complexity</h3><ul><li><strong>Time Complexity</strong>: <strong>O(n)</strong> → One pass through the array.</li><li><strong>Space Complexity</strong>: <strong>O(1)</strong> → In-place swaps; no extra memory used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🎓 Key Takeaways</h3><ol><li><strong>Two-Pointer Magic</strong>: left and right work together to reorganize the array efficiently.</li><li><strong>Relative Order Preserved</strong>: Swapping ensures non-zeros stay in their original sequence.</li><li><strong>In-Place Solution</strong>: No extra arrays needed!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><p>If you found the post to be useful, consider following me here on <a href="https://medium.com/@coderNitesh101"><strong>Medium</strong></a> to never miss any new blog posts and updates.</p><p>Follow and connect with me on <a href="https://www.linkedin.com/in/nitesh-kumar-ojha/"><strong>Linkedin</strong></a> and <a href="https://x.com/coderNitesh"><strong>X</strong></a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9deffc6404f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 238 : Product of Array Except Self | by Nitesh]]></title>
            <link>https://medium.com/@coderNitesh101/leetcode-238-product-of-array-except-self-by-nitesh-2d303d2a27b9?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d303d2a27b9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 12:31:59 GMT</pubDate>
            <atom:updated>2025-02-01T12:31:59.920Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 238 : Product of Array Except Self | by Nitesh</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsNFyEcIU1oDW4WZchwAMQ.png" /></figure><p><strong>Problem Statement</strong>: Given an array nums, return an array answer where answer[i] is the product of all elements in nums except nums[i].</p><p><strong>Constraints</strong>: Solve it in <strong>O(n)</strong> time and <strong>O(1)</strong> extra space (the output array doesn’t count).</p><p><strong>Sample Input</strong>: nums = [1, 2, 3, 4]</p><p><strong>Sample Output</strong>: [24, 12, 8, 6]</p><ul><li>24 = 2*3*4, 12 = 1*3*4, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🚫 Why Not Just Multiply All and Divide?</h3><p>A naive approach might calculate the total product of all elements and divide by nums[i] for each index.</p><pre>def productExceptSelfNaive(nums: List[int]) -&gt; List[int]:<br>    n = len(nums)<br>    res = []<br>    <br>    for i in range(n):<br>        product = 1<br>        for j in range(n):<br>            if i != j:<br>                product *= nums[j]<br>        res.append(product)<br>    <br>    return res</pre><p><strong>Problem</strong>:</p><ul><li><strong>Division by zero</strong> if nums[i] = 0.</li><li><strong>Time Complexity</strong>: O(n) ✅, but division is not allowed ❌.</li></ul><p><strong>We need a smarter, division-free approach!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🧠 Optimal Approach: Prefix &amp; Postfix Products!</h3><h3>Intuition</h3><p>For each element nums[i], the product of all elements except itself can be split into two parts:</p><ol><li><strong>Prefix Product</strong>: Product of all elements <strong>before</strong> i.</li><li><strong>Postfix Product</strong>: Product of all elements <strong>after</strong> i.</li></ol><p><strong>Final Product</strong> = Prefix * Postfix.</p><h3>🛠️ Step-by-Step Solution</h3><h4>Step 1: Compute Prefix Products (Left to Right)</h4><ul><li>Traverse the array from left to right.</li><li>For each index i, store the prefix product (product of all elements before i) in res[i].</li></ul><p><strong>Example</strong>: nums = [1, 2, 3, 4]</p><ul><li>res after prefix pass: [1, 1, 2, 6]</li><li>res[0] = 1 (no elements before 1).</li><li>res[1] = 1 (product of elements before 2: 1).</li><li>res[2] = 1*2 = 2.</li><li>res[3] = 1*2*3 = 6.</li></ul><h4>Step 2: Compute Postfix Products (Right to Left)</h4><ul><li>Traverse the array from right to left.</li><li>For each index i, multiply res[i] by the postfix product (product of all elements after i).</li></ul><p><strong>Example</strong>: nums = [1, 2, 3, 4]</p><ul><li>Postfix starts at 1 (no elements after 4).</li><li>res[3] = 6 * 1 = 6 ✅</li><li>Postfix becomes 1*4 = 4.</li><li>res[2] = 2 * 4 = 8 ✅</li><li>Postfix becomes 4*3 = 12.</li><li>res[1] = 1 * 12 = 12 ✅</li><li>Postfix becomes 12*2 = 24.</li><li>res[0] = 1 * 24 = 24 ✅</li></ul><p><strong>Final Result</strong>: [24, 12, 8, 6] 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>💻 Code Breakdown</h3><pre>def productExceptSelf(nums: List[int]) -&gt; List[int]:<br>    res = [1] * len(nums)  # Initialize result array with 1s<br>    <br>    # Step 1: Compute Prefix Products (Left to Right)<br>    prefix = 1<br>    for i in range(len(nums)):<br>        res[i] = prefix  # Store prefix product for index i<br>        prefix *= nums[i]  # Update prefix to include nums[i]<br>    <br>    # Step 2: Compute Postfix Products (Right to Left)<br>    postfix = 1<br>    for i in range(len(nums)-1, -1, -1):<br>        res[i] *= postfix  # Multiply prefix with postfix<br>        postfix *= nums[i]  # Update postfix to include nums[i]<br>    <br>    return res</pre><h3>Code Explanation</h3><ol><li><strong>Initialize </strong><strong>res</strong>: Start with [1, 1, ..., 1] to store prefix and postfix products.</li><li><strong>Prefix Pass</strong>: Calculate products of all elements to the left of each index.</li><li><strong>Postfix Pass</strong>: Calculate products of all elements to the right and combine with prefix.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🧪 Edge Cases</h3><h4>Case 1: Array with Zero</h4><p><strong>Input</strong>: [0, 1, 2, 3]</p><p><strong>Output</strong>: [6, 0, 0, 0]</p><ul><li>Prefix for index 0: 1 → Postfix: 1*2*3 = 6 → 1*6 = 6.</li><li>For other indices, prefix or postfix includes 0, making the product 0.</li></ul><h4>Case 2: Single Element</h4><ul><li><strong>Input</strong>: [5] → <strong>Output</strong>: [1]</li><li>Product of elements except self (if only one element is in the array) is considered as 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>⏱️ Time &amp; Space Complexity</h3><ul><li><strong>Time Complexity</strong>: <strong>O(n)</strong> → Two passes over the array.</li><li><strong>Space Complexity</strong>: <strong>O(1)</strong> (excluding output array) → Only variables prefix and postfix are used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🎓 Key Takeaways</h3><ol><li><strong>Split the Problem</strong>: Divide into prefix (left) and postfix (right) products.</li><li><strong>Two-Pass Technique</strong>: Compute prefix in one pass, postfix in another.</li><li><strong>No Division Needed</strong>: Avoids division and handles zeros gracefully.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><p>If you found the post to be useful, consider <strong>following</strong> me here on <a href="https://medium.com/@coderNitesh101"><strong>Medium</strong></a> to never miss any new blog posts and updates.</p><p>Follow and connect with me on <a href="https://www.linkedin.com/in/nitesh-kumar-ojha/">Linkedin</a> and <a href="https://x.com/coderNitesh">X</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d303d2a27b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode 189 : Rotate Array | by NKO]]></title>
            <link>https://medium.com/@coderNitesh101/leetcode-189-rotate-array-by-nko-03e935eeacad?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/03e935eeacad</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 12:32:35 GMT</pubDate>
            <atom:updated>2025-01-29T12:32:35.347Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode 189 : Rotate Array | by Nitesh Kumar Ojha</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQdw4gD6wOgaWu7tb-yWaw.png" /></figure><p><strong>Problem Statement</strong>: Given an array, rotate it to the right by k steps. <strong>Do this in-place</strong> (modify the original array without using extra space).</p><p><strong>Example</strong>:</p><ul><li><strong>Input</strong>: nums = [1, 2, 3, 4, 5, 6, 7], k = 3</li><li><strong>Output</strong>: [5, 6, 7, 1, 2, 3, 4]<br><em>(The last 3 elements </em><em>[5, 6, 7] move to the front, and the rest shift right.)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🚫 Why Not Just Move Elements One by One?</h3><p>A naive approach might rotate the array by shifting elements one step at a time, repeated k times.</p><pre>def rotate_naive(nums: List[int], k: int) -&gt; None:<br>    n = len(nums)<br>    <br>    for _ in range(k):  # Repeat k times<br>        # Store the last element<br>        last_element = nums[-1]<br>        <br>        # Shift all elements to the right by one<br>        for i in range(n - 1, 0, -1):<br>            nums[i] = nums[i - 1]<br>        <br>        # Place the last element at the beginning<br>        nums[0] = last_element</pre><p>But this is <strong>inefficient</strong> for large k or large arrays.</p><ul><li><strong>Time Complexity</strong>: O(n * k) → Slow for k = 10^5 and n = 10^5!</li><li><strong>Space Complexity</strong>: O(1) ✅, but time is terrible ❌.</li></ul><p><strong>We need a smarter way!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🧠 Optimal Approach: The Three-Step Reversal Magic! ✨</h3><h4>Intuition</h4><p>Imagine cutting the array into two parts:</p><ol><li>The last k elements.</li><li>The remaining elements.</li></ol><p>To rotate the array, we need to move the last k elements to the front while preserving their order. Here’s how we do it <strong>in O(n) time</strong> using reversals:</p><h4>Steps</h4><ol><li><strong>Reverse the entire array</strong> → Last k elements move to the front but in reverse order.</li><li><strong>Reverse the first </strong><strong>k elements</strong> → Restore their original order.</li><li><strong>Reverse the remaining elements</strong> → Restore the original order of the rest.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🛠️ Step-by-Step Example Walkthrough</h3><p>Let’s rotate nums = [1, 2, 3, 4, 5, 6, 7] with k = 3.</p><h3>Step 1: Reverse the Entire Array</h3><ul><li>Original: [1, 2, 3, 4, 5, 6, 7]</li><li>After reversal: [7, 6, 5, 4, 3, 2, 1]<br>🔁 <em>The last </em><em>k elements (</em><em>5, 6, 7) are now at the front but reversed.</em></li></ul><h3>Step 2: Reverse the First k Elements</h3><ul><li>Focus on first k=3 elements: [7, 6, 5]</li><li>After reversal: [5, 6, 7, 4, 3, 2, 1]<br>🔁 <em>The first </em><em>k elements are now in their original order!</em></li></ul><h3>Step 3: Reverse the Remaining Elements</h3><ul><li>Focus on elements from index k=3 to end: [4, 3, 2, 1]</li><li>After reversal: [5, 6, 7, 1, 2, 3, 4]<br>🔁 <em>The remaining elements are restored to their original order!</em></li></ul><p><strong>Final Result</strong>: [5, 6, 7, 1, 2, 3, 4] ✅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>⚙️ Handling Edge Cases</h3><h4>Case 1: k is Larger Than or Equal to Array Length</h4><p>If k = 8for an array of length 7, rotating by 8 steps is equivalent to rotating by 1 step!</p><ul><li><strong>Solution</strong>: Compute k = k % len(nums).</li></ul><p>Example: k = 8→ 8 % 7 = 1→ Only 1 rotation needed!</p><h4>Case 2: k = 0</h4><p>No rotation required. The array stays the same.</p><h4>Case 3: Single-Element Array</h4><p>Rotating [5] by any k will always be [5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>💻 Code Breakdown</h3><pre>def rotate(nums: List[int], k: int) -&gt; None:<br>    n = len(nums)<br>    k = k % n  # Handle large k values<br>    <br>    # Step 1: Reverse the entire array<br>    left, right = 0, n - 1<br>    while left &lt; right:<br>        nums[left], nums[right] = nums[right], nums[left]<br>        left += 1<br>        right -= 1<br>    <br>    # Step 2: Reverse the first k elements<br>    left, right = 0, k - 1<br>    while left &lt; right:<br>        nums[left], nums[right] = nums[right], nums[left]<br>        left += 1<br>        right -= 1<br>    <br>    # Step 3: Reverse the remaining elements<br>    left, right = k, n - 1<br>    while left &lt; right:<br>        nums[left], nums[right] = nums[right], nums[left]<br>        left += 1<br>        right -= 1</pre><h3>Code Explanation</h3><ol><li><strong>Adjust </strong><strong>k</strong>: k = k % n ensures k is within the array’s bounds.</li><li><strong>Reverse Entire Array</strong>: Swaps elements from the outermost indices inward.</li><li><strong>Reverse First </strong><strong>k Elements</strong>: Corrects the order of the first k elements.</li><li><strong>Reverse Remaining Elements</strong>: Corrects the order of the rest.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>⏱️ Time &amp; Space Complexity</h3><ul><li><strong>Time Complexity</strong>: O(n) → Each reversal step takes O(n).</li><li><strong>Space Complexity</strong>: O(1) → No extra space used!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>🎓 Key Takeaways</h3><ol><li><strong>Modulo is Magic</strong>: Always handle k with k = k % n to avoid redundant rotations.</li><li><strong>Reversal Technique</strong>: Breaks the problem into three simple steps.</li><li><strong>In-Place Operation</strong>: Modifies the array directly without extra memory.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><p>If you found the post to be useful, consider <strong>following</strong> me here on <a href="https://medium.com/@coderNitesh101"><strong>Medium</strong></a> to never miss any new blog posts and updates.</p><p>Follow and connect with me on <a href="https://www.linkedin.com/in/nitesh-kumar-ojha/">Linkedin</a> and <a href="https://x.com/coderNitesh">X</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03e935eeacad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 41 : First Missing Positive | by NKO]]></title>
            <link>https://medium.com/@coderNitesh101/leetcode-41-first-missing-positive-by-nko-d4adbfac7348?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4adbfac7348</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 13:32:20 GMT</pubDate>
            <atom:updated>2025-01-28T13:02:48.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 41 : First Missing Positive | by Nitesh Kumar Ojha</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O5ya9LkOPYX_qaPcDRw1g.png" /></figure><p>Have you ever wondered how to find the smallest positive integer that’s missing from an array? This problem, known as <strong>First Missing Positive</strong>, might sound tricky at first, but with the right approach, it becomes manageable even for beginners.</p><p>Let’s break it down with examples:</p><ul><li><strong>Example 1</strong>: For [3, 4, -1, 1], the answer is 2 because 1 and 3 are present, but 2 is missing.</li><li><strong>Example 2</strong>: For [1, 2, 0], the answer is 3 since all numbers 1, 2, and 3 are missing after 0.</li></ul><p>The challenge is to solve this efficiently, even for large arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Naive Approach: Sorting and Scanning</h3><p>A straightforward way is to sort the array and scan for the first missing positive. For example:</p><ul><li>Sort [3, 4, -1, 1] → [-1, 1, 3, 4].</li><li>Scan from 1 upwards: 1 exists, 2 is missing.</li></ul><p><strong>Problem</strong>: Sorting takes <strong>O(n log n)</strong> time. Can we do better?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Optimal Approach: In-Place Hashing (Cyclic Sort)</h3><h3>Intuition</h3><p>The smallest missing positive must be between <strong>1</strong> and <strong>n+1</strong> (where n is the array length). Why?</p><ul><li>If the array contains all numbers from 1 to n, the answer is n+1.</li><li>Otherwise, the answer is the first missing number in 1 to n.</li></ul><p><strong>Key Idea</strong>: Rearrange the array so each number x (if between 1 and n) is placed at index x-1. This way, we can check which number is missing in one scan.</p><h3>Step-by-Step Explanation</h3><p>Let’s use <strong>cyclic sort</strong> to place numbers in their correct positions:</p><ol><li><strong>Iterate through the array</strong>:</li></ol><ul><li>For each number, if it’s between 1 and n, swap it to its correct index (num - 1).</li><li>Repeat until the current number is in the correct place or out of range.</li></ul><p><strong>2. Scan the rearranged array</strong>:</p><ul><li>The first index i where nums[i] != i + 1 is the missing number.</li><li>If all positions are correct, the answer is n + 1.</li></ul><h3>Example Walkthrough</h3><p><strong>Input</strong>: [3, 4, -1, 1] (Length n = 4)</p><p><strong>Step 1: Rearrange the array</strong></p><ul><li><strong>i=0</strong>: nums[0] = 3. Swap with index 2 (since 3 belongs at index 2).<br>Array becomes [-1, 4, 3, 1].</li><li><strong>i=1</strong>: nums[1] = 4. Swap with index 3.<br>Array becomes [-1, 1, 3, 4].</li><li>Now, nums[1] = 1. Swap with index 0.<br>Array becomes [1, -1, 3, 4].</li><li><strong>i=2</strong> and <strong>i=3</strong> are already in place.</li></ul><p><strong>Step 2: Scan for the missing number</strong><br>Check each index:</p><ul><li>nums[0] = 1 ✅</li><li>nums[1] = -1 ❌ → Missing number is 2 (since 1 + 1 = 2).</li></ul><h3>Code Breakdown</h3><pre>def firstMissingPositive(nums):<br>    n = len(nums)<br>    # Step 1: Cyclic sort to place numbers in their correct positions.<br>    for i in range(n):<br>        # Keep swapping until the number is in the correct place or out of range.<br>        while 1 &lt;= nums[i] &lt;= n and nums[nums[i] - 1] != nums[i]:<br>            nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]<br>    <br>    # Step 2: Find the first missing positive.<br>    for i in range(n):<br>        if nums[i] != i + 1:<br>            return i + 1<br>    return n + 1</pre><h3><strong>Explanation</strong>:</h3><ol><li><strong>Cyclic Sort Loop</strong>:</li></ol><ul><li>For each index i, if nums[i] is between 1 and n, swap it to index nums[i] - 1.</li><li>The while loop ensures numbers are placed correctly even after swaps.</li></ul><p><strong>2. Scan for Missing Number</strong>:</p><ul><li>After sorting, the first index i where nums[i] != i + 1 gives the missing number.</li></ul><h3>Complexity Analysis</h3><ul><li><strong>Time</strong>: <strong>O(n)</strong>. Each element is swapped at most once.</li><li><strong>Space</strong>: <strong>O(1)</strong>. No extra space is used.</li></ul><h3>Practice and dry run these Edge Cases</h3><ul><li><strong>All negatives</strong>: e.g., [-5, -3, -1] → Missing 1.</li><li><strong>Duplicates</strong>: e.g., [1, 1] → Missing 2.</li><li><strong>Single element</strong>: [1] → Missing 2.</li></ul><h3>Conclusion</h3><p>By leveraging cyclic sort, we efficiently rearrange the array in-place and find the missing positive in linear time. This approach is optimal and widely applicable to similar problems. Practice this pattern to master array manipulation techniques!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><p>If you found the post to be useful, consider <strong>following</strong> me here on <a href="https://medium.com/@coderNitesh101"><strong>Medium</strong></a> to never miss any new blog posts and updates.</p><p>Follow and connect with me on <a href="https://www.linkedin.com/in/nitesh-kumar-ojha/">Linkedin</a> and <a href="https://x.com/coderNitesh">X</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4adbfac7348" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Search Algorithm in C++: Step-by-Step Guide with Code]]></title>
            <link>https://medium.com/@coderNitesh101/linear-search-algorithm-in-c-step-by-step-guide-with-code-fec5cdf81749?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/fec5cdf81749</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[sad]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 06:20:52 GMT</pubDate>
            <atom:updated>2024-08-18T06:20:52.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJMJK7wNAiaWE4RyPODQCA.png" /></figure><p>When you’re coding, one of the first challenges you might face is figuring out how to find a specific element in an array. It’s a fundamental problem that opens the door to understanding more complex algorithms and data structures. But don’t worry — this isn’t just another dry tutorial. We’re going to explore this problem in an engaging way, breaking down the logic and building our solution from the ground up. By the end of this post, you’ll be equipped to handle not just this problem, but a whole host of similar challenges with ease.</p><h4>What We’ll Cover</h4><ol><li>What’s the Problem?</li><li>Building the Logic, Brick by Brick</li><li>Coding It Up in C++</li><li>Crunching the Numbers: Time and Space Complexity</li><li>Pro Tips for Optimization</li><li>Wrapping It Up</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>1. What’s the Problem?</h3><p>Imagine you’re at a party, and you’ve got a list of everyone who’s there. Now, you want to find out if your best friend made it to the party. You have to check each name on the list until you find them — or realize they didn’t show up. In coding terms, this is what we call searching for an element in an array.</p><p><strong>Input</strong>:</p><ul><li>The size of the array (how many people are at the party).</li><li>The actual array (the list of names).</li><li>The element to search for (your best friend’s name).</li></ul><p><strong>Output</strong>:</p><ul><li>A message that either says “Element is present” (your friend is here) or “Element is not present” (they’re a no-show).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>2. Building the Logic, Brick by Brick</h3><p>Let’s think this through. You have an array (the guest list) and you need to find a specific element (your friend’s name). The most straightforward way to do this is to go through the list, one name at a time, until you either find your friend or reach the end of the list.</p><p>Here’s how you can break it down:</p><ol><li><strong>Take the Array and Element</strong>: First, get the size of the array and the elements from the user.</li><li><strong>Search the Array</strong>: Start at the beginning of the array and compare each element with the one you’re looking for.</li><li><strong>Flag It</strong>: If you find the element, set a flag (like waving to your friend across the room).</li><li><strong>Output the Result</strong>: Finally, based on the flag’s status, let the user know if the element was found.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>3. Coding It Up in C++</h3><p>Now that we’ve nailed down the logic, it’s time to get our hands busy with some code. Here’s how you can implement this in C++:</p><pre>#include &lt;bits/stdc++.h&gt; // This includes all standard C++ library headers.<br>using namespace std; // This allows us to use standard library names without prefixing them with &#39;std::&#39;.<br><br>int main()<br>{<br>    int n; // Declare an integer variable &#39;n&#39; to store the size of the array.<br>    cout &lt;&lt; &quot;Enter size of array: &quot;; // Prompt the user to enter the size of the array.<br>    cin &gt;&gt; n; // Read the input from the user and store it in &#39;n&#39;.<br><br>    int arr[n]; // Declare an array &#39;arr&#39; of size &#39;n&#39;.<br>    cout &lt;&lt; &quot;Enter array elements: &quot;; // Prompt the user to enter the elements of the array.<br>    for (int i = 0; i &lt; n; i++) // Loop to read &#39;n&#39; elements into the array.<br>    {<br>        cin &gt;&gt; arr[i]; // Read each element and store it in the array.<br>    }<br><br>    int x; // Declare an integer variable &#39;x&#39; to store the element to be searched.<br>    cout &lt;&lt; &quot;Enter the element you want to search: &quot;; // Prompt the user to enter the element to be searched.<br>    cin &gt;&gt; x; // Read the input from the user and store it in &#39;x&#39;.<br><br>    bool flag = false; // Declare a boolean variable &#39;flag&#39; and initialize it to false.<br>    for (int i = 0; i &lt; n; i++) // Loop through each element of the array.<br>    {<br>        if (arr[i] == x) // If the current element is equal to &#39;x&#39;,<br>        {<br>            flag = true; // Set &#39;flag&#39; to true indicating the element is found.<br>            break; // Exit the loop since we found the element.<br>        }<br>    }<br><br>    // Check the value of &#39;flag&#39; and print the appropriate message.<br>    flag == true ? cout &lt;&lt; &quot;Element is present&quot; : cout &lt;&lt; &quot;Element is not present&quot;; <br>    // If &#39;flag&#39; is true, print &quot;Element is present&quot;, otherwise print &quot;Element is not present&quot;.<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>4. Crunching the Numbers: Time and Space Complexity</h3><p>You’re at the party, you found your friend — great! But now, let’s take a moment to see how efficient your search was.</p><ul><li><strong>Time Complexity</strong>: The for loop goes through the list one person at a time, so the time complexity is O(n), where n is the number of guests. This means that in the worst-case scenario, you might have to check every single person.</li><li><strong>Space Complexity</strong>: The guest list (array) takes up O(n) space. The other variables (like n, x, and flag) only take up O(1) space. Overall, the space complexity is dominated by the array, so it’s O(n).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>5. Pro Tips for Optimization</h3><p>You’ve nailed the basics, but what if you want to level up your search skills?</p><ol><li><strong>Binary Search</strong>: If the guest list is sorted, you can use a binary search to cut down the search time to O(log n). It’s like knowing exactly where to look on the list, rather than starting at the top.</li><li><strong>Hashing</strong>: If you have a huge list and need to search frequently, consider using a hash table. This can bring down the average time complexity of your search to O(1). It’s like having a bouncer who knows exactly who’s in the party at any moment.</li><li><strong>Parallel Processing</strong>: For an insanely large list, you could divide and conquer by searching different sections of the list simultaneously. This is like having a group of friends help you find someone at the party.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>6. Wrapping It Up</h3><p>Finding an element in an array is a classic problem that every coder should master. But more than just solving the problem, it’s about understanding the process and thinking critically about how to make your code better. Whether you’re just starting out or looking to optimize your solutions, keep experimenting and pushing your boundaries.</p><p>Happy coding, and may you always find what you’re searching for!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fec5cdf81749" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Shaping the Modern Web]]></title>
            <link>https://medium.com/@coderNitesh101/javascript-shaping-the-modern-web-c0964c4c59dc?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0964c4c59dc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Wed, 15 May 2024 13:00:15 GMT</pubDate>
            <atom:updated>2024-05-15T13:00:15.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMPFj8nSRA1lSEnFZbk3nQ.png" /></figure><p>Welcome to a narrative tracing the evolutionary arc of JavaScript, from its nascent days to its current prominence in modern web development. Join me as we explore the inception, growth, and ongoing evolution of this pivotal language that has profoundly shaped the digital landscape.</p><p>In 1995, Netscape Communications Corporation tasked Brendan Eich with the creation of a scripting language for their Navigator browser. Despite a tight deadline, Eich drew upon a range of programming languages, including Java, Scheme, and Self, to craft a prototype known as Mocha. This prototype laid the foundation for what would later become JavaScript. Originally named LiveScript, the language underwent a strategic rebranding to align with the popularity of Java, thus solidifying its identity in the competitive tech sphere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Ew_R-O9mJ6mkD1Mk.jpg" /><figcaption>Brendan Eich</figcaption></figure><p>JavaScript quickly garnered attention for its lightweight nature, simplicity, and ability to introduce dynamic functionality to web pages. From form validation to DOM manipulation, it empowered developers to craft interactive web experiences with ease.</p><p>A significant lot milestone in JavaScript’s journey occurred in 1996 when it was submitted to the Ecma International standards organization for standardization. This process resulted in the establishment of ECMAScript, a standardized specification that ensured JavaScript’s compatibility across various browsers and platforms. This standardization played a pivotal role in JavaScript’s widespread adoption and its integration into the fabric of web development.</p><p>In recent years, JavaScript has undergone notable advancements with the emergence of modern frameworks and libraries such as React, Angular, and Vue.js. These tools have revolutionized web development by providing developers with powerful abstractions and tools for building scalable and interactive applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ABgwiy2lhU4lE2jT93Xqw.jpeg" /><figcaption>Image Credit: youtube.com/@csscoder8892</figcaption></figure><p>Additionally, the introduction of ECMAScript 2015 (ES6) brought forth a wealth of enhancements to the language, including arrow functions, template literals, classes, and modules. These features have facilitated cleaner and more expressive code, driving further innovation within the JavaScript ecosystem.</p><p>JavaScript’s versatility extends beyond client-side scripting, with the advent of server-side frameworks and runtime environments like Node.js enabling developers to utilize JavaScript for full-stack development. This seamless integration across the entire stack has streamlined the development process and facilitated the creation of robust web applications and services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AzAKLfkH7vxsrTld.png" /><figcaption>Image Credit: Wikipedia</figcaption></figure><p>JavaScript continues to dominate modern web development thanks to the relentless creativity of developers around the world. Its enduring popularity is a testament to the transformative power of technology and the never-ending quest for digital innovation.</p><p>JavaScript embodies the power of adaptation in a rapidly changing technological landscape. As we turn towards the future, it will undoubtedly remain a cornerstone of web development, paving the way for groundbreaking advancements and exciting possibilities yet to be discovered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0964c4c59dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web 3: A Decentralized Future Powered by Blockchain]]></title>
            <link>https://medium.com/@coderNitesh101/web-3-a-decentralized-future-powered-by-blockchain-04ad3071920b?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/04ad3071920b</guid>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Fri, 10 May 2024 13:35:54 GMT</pubDate>
            <atom:updated>2024-05-10T13:48:39.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDWOospojNTnRYY6eA_dxw.png" /></figure><p>Imagine a world where you, not some corporation, own your data. Where every transaction is transparent and tamper-proof. This isn’t science fiction, it’s the promise of blockchain technology.</p><p>But what exactly is blockchain, and why is it hailed as a game-changer?</p><p>At its heart, blockchain is a decentralized and immutable ledger, a dynamic sequence of records, or blocks, each containing a bundle of transactions securely linked together. This cryptographic backbone ensures that once data is recorded, it remains tamper-proof, safeguarding its integrity and permanence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qpTsyGVDptKqvajE.png" /><figcaption>Image Credit: c-sharpcorner.com</figcaption></figure><p>While the genesis of blockchain traces back to the visionary work of Nick Szabo in the early 1990s, it wasn’t until the advent of cryptocurrencies, notably Bitcoin in 2009, that blockchain surged into the mainstream. Bitcoin introduced the concept of a decentralized digital currency, underpinned by blockchain technology, enabling peer-to-peer transactions without intermediaries.</p><p>Yet, blockchain’s potential transcends finance. Its decentralized architecture lends itself to myriad applications, from supply chain management to healthcare and voting systems. By sidestepping centralized control, blockchain fosters trustless interactions, mitigating the risk of fraud or manipulation.</p><p>Blockchain’s resilience against tampering or hacking is a cornerstone of its appeal. The cryptographic hashing algorithms, like SHA-256, create an indelible seal around each block. Any attempt to alter the data would disrupt the block’s hash value, signalling foul play. Moreover, the distributed nature of blockchain means that compromising the network would require overpowering the majority of its computing power — a Herculean feat known as the “51% attack.”</p><p>Mining, the backbone of blockchain, plays a pivotal role in upholding its integrity. Miners compete to crack complex mathematical puzzles, racing to add new blocks to the chain. This process not only incentivizes participation but also fortifies the network’s decentralization and security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKQ5GTSaZp2yrIpVjomEbQ.png" /><figcaption>Image credit: edureka.co</figcaption></figure><p>In the grand scheme of the internet’s evolution, blockchain heralds the dawn of Web 3.0 — a decentralized frontier where users wield greater sovereignty over their data and interactions. Unlike the prevailing client-server model, Web 3.0 embraces peer-to-peer (P2P) connections, with blockchain as its bedrock infrastructure, enabling individuals to reclaim control over their digital identities and assets.</p><p>However, the widespread adoption of blockchain still faces significant challenges, including scalability, interoperability, and regulatory hurdles. As the technology continues to evolve, addressing these challenges will be crucial in unlocking its full potential.</p><p>In conclusion, blockchain offers a transformative solution to the trust and ownership issues plaguing the digital landscape. By providing a decentralized, immutable, and transparent ledger, blockchain empowers individuals and organizations to take control of their data and transactions. As we navigate on the journey towards Web 3.0, blockchain stands as a beacon of hope for a more secure, equitable, and decentralized future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04ad3071920b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero to Hero in Arrays (Level 2)]]></title>
            <link>https://medium.com/@coderNitesh101/zero-to-hero-in-arrays-level-2-0e7be8026e63?source=rss-45c4e092579------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e7be8026e63</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Nitesh Kumar Ojha]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 10:41:03 GMT</pubDate>
            <atom:updated>2023-10-15T10:41:03.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKX3DG13ASPGSuW35MRhwg.png" /></figure><p>Welcome back to the fifth installment of our blog series, “<strong>Mastering Data Structures and Algorithms</strong>.” In this blog post, we’re continuing our journey into the remarkable world of arrays, building on the foundation we laid in the previous blog post, “Zero to Hero in Arrays (Level 1).” If you’ve been following along, you’re already well on your way to becoming an array maestro.</p><p>In this blog post, titled “<strong>Zero to Hero in Arrays (Level 2)</strong>,” we’ll explore advanced topics that will further solidify your understanding of arrays and their applications. We’re diving deep into the concept of <strong>vectors</strong>, a versatile and dynamic data structure that expands upon the fundamental array. You’ll discover the basic operations of vectors and learn how they can be used to handle data more efficiently.</p><p>But that’s not all! I am also introducing you to the powerful “<strong>two pointers</strong>” approach, an indispensable technique for solving a wide range of algorithmic problems efficiently.</p><p>By the end of this blog post, you’ll be familiar with advanced array concepts and equipped with the skills to tackle more complex programming challenges. From <strong>Zero to Hero</strong>, your array mastery continues to grow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Vectors in C++</h3><p>A vector in C++ is a dynamic array-like container provided by the Standard Template Library (STL). It is part of the C++ Standard Library and offers several advantages over traditional arrays.</p><p>Vector is like a magic container that can change its size whenever you want. Imagine having a bag that can hold stuff, and you can add or remove things from it as needed. Vectors are just like that bag.</p><p>Here are a few simple reasons why vectors are cool:</p><ol><li><strong>Dynamic Size</strong>: Vectors can dynamically grow or shrink in size. Regular arrays are like boxes with a fixed number of slots, but vectors can keep adding more slots or taking them away.</li><li><strong>Random Access</strong>: Elements in a vector can be accessed using an index, just like an array. This allows for efficient random access, making vectors suitable for a wide range of applications.</li><li><strong>Automatic Memory Management</strong>: Vectors automatically manage memory. They allocate memory as needed, and you don’t need to worry about manually resizing or deallocating memory. This makes them less error-prone and more convenient.</li><li><strong>STL Algorithms Compatibility</strong>: Vectors work seamlessly with various Standard Template Library algorithms like sorting, searching, and manipulation functions, which simplifies common tasks.</li><li><strong>Type Safety</strong>: Vectors are type-safe. They store elements of a single data type. This means that the compiler can catch type-related errors at compile time.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Vector Syntax</h3><pre>#include &lt;vector&gt;  // Include the vector library<br><br>vector&lt;DataType&gt; vectorName;  // Declare an empty vector</pre><ul><li><strong>DataType</strong>: Replace this with the type of data you want to store in the vector (e.g., int, double, string).</li><li><strong>vectorName</strong>: Choose a name for your vector.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Vector Basic Operations</h3><ol><li>Pushing Elements into a Vector: The push_back function adds an element to the end of the vector.</li><li>Popping Elements from a Vector: The pop_back function removes the last element from the vector.</li><li>Getting the Size of a Vector: The size function returns the number of elements in the vector.</li><li>Getting the Capacity of a Vector: The capacity function returns the current capacity of the vector (how many elements it can hold without resizing).</li><li>Accessing Elements in a Vector: You can access elements using the square brackets and the index (0-based).</li><li>Sorting a Vector: To sort a vector, you can use the sort function from the &lt;algorithm&gt; library. This function rearranges the elements in ascending order.</li></ol><p>Implementation of all these basic operations through one example code:</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br><br>using namespace std;<br><br>int main() {<br>    vector&lt;int&gt; numbers;  // Declare an empty integer vector<br><br>    // Pushing elements into the vector<br>    numbers.push_back(3);<br>    numbers.push_back(1);<br>    numbers.push_back(2);<br><br>    // Accessing elements<br>    cout &lt;&lt; &quot;Element at index 1: &quot; &lt;&lt; numbers[1] &lt;&lt; endl;<br><br>    // Sorting the vector<br>    sort(numbers.begin(), numbers.end());<br><br>    // Popping the last element<br>    numbers.pop_back();<br><br>    // Getting size and capacity<br>    int size = numbers.size();<br>    int capacity = numbers.capacity();<br><br>    cout &lt;&lt; &quot;Size: &quot; &lt;&lt; size &lt;&lt; &quot; Capacity: &quot; &lt;&lt; capacity &lt;&lt; endl;<br><br>    return 0;<br>}</pre><pre>OUTPUT<br><br>Element at index 1: 1<br>Size: 2 Capacity: 4</pre><ul><li>We add three elements to the vector (3, 1, and 2).</li><li>We access and print the element at index 1, which is 1.</li><li>We sort the vector, so it becomes [1, 2, 3].</li><li>We removed the last element, so the size is now 2.</li><li>The capacity is 4 because vectors allocate more space than is currently needed for performance reasons.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Size vs Capacity</h3><ol><li><strong>size</strong></li></ol><ul><li>This function returns the number of elements that the vector currently contains.</li><li>It represents the actual count of elements within the vector.<br>The value returned by size() changes when elements are added or removed from the vector.</li><li>It is typically used when you need to know the exact number of elements in the vector for iterations or other operations.</li></ul><p>2. <strong>capacity</strong></p><ul><li>capacity() returns the number of elements that the vector currently has memory allocated to hold.</li><li>It reflects the maximum number of elements the vector can accommodate without resizing.</li><li>In general, a vector doubles its capacity when it becomes full.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h3>Two Pointers Approach</h3><h4>Program 1: Write a program to reverse the array without using any extra array.</h4><p>Sample Input: {1, 5, 2, 7, 8, 5, 3, 0, 10}<br>Sample Output: {10, 0, 3, 5, 8, 7, 2, 5, 1}</p><h4>Algorithm</h4><ol><li>Calculate the size of the array <strong>n</strong> using the <strong>sizeof</strong> operator, which gives you the total number of bytes occupied by the array and then dividing it by the size of an individual element (in this case, the size of an integer).</li><li>Initialize a loop that prints the original array <strong>arr</strong> using a <strong>for loop</strong>. This loop runs from<strong> i = 0</strong> to <strong>i &lt; n</strong>, printing each element of the array with a space in between.</li><li>Initialize two variables, <strong>i</strong> and <strong>j</strong>, to <strong>0</strong> and<strong> n — 1</strong> respectively. These variables will be used to swap elements from the beginning and end of the array.</li><li>Start a while loop that continues as long as <strong>i</strong> is less than <strong>j</strong>. This loop will reverse the array.</li><li>Inside the loop, swap the elements <strong>arr[i]</strong> and <strong>arr[j] </strong>using a temporary variable <strong>temp</strong>. This effectively reverses the order of elements at positions <strong>i</strong> and <strong>j</strong>.</li><li>Increment <strong>i</strong> and decrement <strong>j</strong> by 1 in each iteration of the loop, moving towards the center of the array.</li><li>After the loop, print a newline character to separate the original and reversed array in the output.</li><li>Finally, print the reversed array using another for loop.</li></ol><pre>#include &lt;bits/stdc++.h&gt;<br>using namespace std;<br>int main()<br>{<br>  int arr[] = {1, 5, 2, 7, 8, 5, 3, 0, 10};<br>  int n = sizeof(arr) / sizeof(int);<br><br>  for (int i = 0; i &lt; n; i++)<br>  {<br>    cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>  }<br><br>  int i = 0;<br>  int j = n - 1;<br>  while (i &lt; j)<br>  {<br>    int temp = arr[i];<br>    arr[i] = arr[j];<br>    arr[j] = temp;<br>    i++;<br>    j--;<br>  }<br><br>  cout &lt;&lt; endl;<br>  for (int i = 0; i &lt; n; i++)<br>  {<br>    cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>  }<br>}</pre><pre>OUTPUT<br><br>1 5 2 7 8 5 3 0 10 <br>10 0 3 5 8 7 2 5 1 </pre><p>The two-pointer approach used in this program is a technique commonly employed to solve various array manipulation problems efficiently. In this specific case, the two-pointer approach is used to reverse an array. Here’s how it works:</p><ol><li><strong>Initialization</strong>: Two pointers, i and j, are initialized. i starts from the beginning of the array, and j starts from the end of the array.</li></ol><pre>int i = 0;<br>int j = n - 1;</pre><p>i is the left pointer starting at index 0, and j is the right pointer starting at the last index (n — 1).</p><p>2. <strong>Swapping Elements</strong>: Inside the while loop, elements at the positions indicated by i and j are swapped. The temporary variable temp is used for this purpose. The purpose of this swapping is to reverse the elements in the array.</p><pre>int temp = arr[i];<br>arr[i] = arr[j];<br>arr[j] = temp;</pre><p>This swapping step effectively reverses the order of elements at positions i and j.</p><p>3. <strong>Moving Pointers</strong>: After the swap, i is incremented by 1, and j is decremented by 1. This movement of pointers is important because it shifts the focus to the next pair of elements that need to be swapped to continue the reversal.</p><pre>i++;<br>j--;</pre><p>4. <strong>Loop Termination</strong>: The while loop continues as long as i is less than j. When i crosses over or becomes equal to j, it means that all elements in the array have been processed and swapped to reverse the order. At this point, the loop terminates.</p><blockquote>The two-pointer approach is efficient for reversing an array or solving many other array manipulation problems because it processes elements from both ends simultaneously, and it only needs to iterate through the array once. This approach has a time complexity of O(n/2), which simplifies to O(n), where “n” is the number of elements in the array. It’s a much more efficient solution than other methods that require creating a separate array or using additional data structures to reverse the array.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><h4>Program 2: Sort the array of 0’s and 1’s</h4><p>Sample Input: {1, 1, 0, 1, 0, 1, 1, 0}<br>Sample Output: {0, 0, 0, 1, 1, 1, 1, 1}</p><h4>Algorithm</h4><ol><li>Initialize two pointers, <strong>i</strong> and <strong>j</strong>, where <strong>i </strong>points to the beginning of the vector, and <strong>j</strong> points to the end of the vector.</li><li>Use a while loop that runs as long as <strong>i</strong> is less than <strong>j</strong>.</li><li>Inside the loop, perform the following checks:</li></ol><ul><li>If <strong>v[j]</strong> is equal to 1, decrement the <strong>j</strong> pointer.</li><li>If <strong>v[i]</strong> is equal to 0, increment the<strong> i </strong>pointer.</li><li>If <strong>i </strong>becomes greater than or equal to<strong> j</strong>, break out of the loop.</li></ul><p>4. If <strong>v[i] </strong>is greater than <strong>v[j]</strong>, swap the elements at positions <strong>i</strong> and <strong>j</strong>, effectively putting 0s to the left of 1s. After the swap, increment <strong>i</strong> and decrement <strong>j</strong>.</p><p>5. Continue this process until <strong>i</strong> is no longer less than <strong>j</strong>.</p><pre>#include&lt;bits/stdc++.h&gt;<br>using namespace std;<br>void sort01(vector&lt;int&gt; &amp;v)<br>{<br>  int size = v.size();<br>  int i = 0; int j = size-1;<br>  while(i&lt;j)<br>  {<br>    if(v[j]==1) j--;<br>    if(v[i]==0) i++;<br>    if(i&gt;j) break;<br>    if(v[i]&gt;v[j])<br>    {<br>      //write the swapping logic or simply just make v[i] = 0 and v[j] = 1<br>      v[i] = 0;<br>      v[j] = 1;<br>      i++;<br>      j--;<br>    }<br>  }<br>}<br><br>int main()<br>{<br>  vector&lt;int&gt; v;<br>  v.push_back(1);<br>  v.push_back(1);<br>  v.push_back(0);<br>  v.push_back(1);<br>  v.push_back(0);<br>  v.push_back(1);<br>  v.push_back(1);<br>  v.push_back(0);<br>  for(int i=0; i&lt;v.size(); i++)<br>  {<br>    cout&lt;&lt;v[i]&lt;&lt;&quot; &quot;;<br>  }<br>  cout&lt;&lt;endl;<br>  sort01(v);<br>  for(int i=0; i&lt;v.size(); i++)<br>  {<br>    cout&lt;&lt;v[i]&lt;&lt;&quot; &quot;;<br>  }<br>}</pre><pre>OUTPUT<br><br>1 1 0 1 0 1 1 0 <br>0 0 0 1 1 1 1 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcwtLkBzJD_u5RsubA9eug.png" /></figure><p>I hope you have enjoyed your journey from Zero to Hero in Arrays with our Level 2 tutorial.</p><p>If you have any doubts or questions about the topics we have discussed, please feel free to get in touch — I am available to assist you.</p><p>In Level 2, we dived into more complex array concepts like vectors and two pointers approach and tackled two problems based on the two pointers approach. But guess what? This is just the midpoint. Level 3 is right around the corner, and we’re gearing up to explore even more challenging and fascinating array topics.</p><p>So, stay tuned, keep coding, and keep learning. Your engagement, whether through comments, shares, or claps, is highly appreciated.</p><p>Consider<strong> </strong>following me here on <a href="https://medium.com/@coderNitesh101"><strong>Medium</strong></a> to never miss any new blog posts.</p><p>Follow and connect with me on <a href="https://www.linkedin.com/in/nitesh-kumar-ojha/">Linkedin</a> and <a href="https://twitter.com/coderNitesh">Twitter</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e7be8026e63" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>