<?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 Manikandan Kandili Sivaraj on Medium]]></title>
        <description><![CDATA[Stories by Manikandan Kandili Sivaraj on Medium]]></description>
        <link>https://medium.com/@Manikandan.K.S?source=rss-38cabb480b31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NvzapouunHiG5npO.jpg</url>
            <title>Stories by Manikandan Kandili Sivaraj on Medium</title>
            <link>https://medium.com/@Manikandan.K.S?source=rss-38cabb480b31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:46:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Manikandan.K.S/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[What Really Happens When You Enter the Wrong Input?]]></title>
            <link>https://medium.com/@Manikandan.K.S/what-really-happens-when-you-enter-the-wrong-input-113bb302b2ed?source=rss-38cabb480b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/113bb302b2ed</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Manikandan Kandili Sivaraj]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 11:28:13 GMT</pubDate>
            <atom:updated>2026-04-20T03:52:55.823Z</atom:updated>
            <content:encoded><![CDATA[<p>When you first start learning programming, you probably learn to write something like this:</p><pre>// Program to read an integer from the user and display it<br>#include &lt;iostream&gt;<br>int main() {<br>    int n;<br>    std::cout &lt;&lt; &quot;Enter a number\n&quot;;<br>    std::cin &gt;&gt; n;<br>    std::cout &lt;&lt; &quot;Entered number is &quot; &lt;&lt; n &lt;&lt; std::endl;<br>}</pre><p>You enter a number, and everything works as expected. But have you ever wondered what happens if you enter a character or a string instead of a number? Or what if you try to print the variable n before the user enters anything?</p><h3>The Curious Case of Uninitialized Variables</h3><p>If you print n before the user inputs a value, you’ll likely see a <strong>garbage value</strong> — whatever happened to be in memory at that location. This is because local variables in C++ are not automatically initialized.</p><h3>What If You Enter a Character Instead of a Number?</h3><p>Try running the above code and enter a letter like a or a word like hello. You might see the output:</p><pre>Entered number is 0</pre><p><strong>Why?</strong> When std::cin tries to read an integer but gets a non-numeric input, the extraction fails. The variable n is left uninitialized (or sometimes appears as 0 depending on your environment), and the input stream enters a <strong>fail state</strong>. Any further input attempts will silently fail unless you handle this situation.</p><h3>How to Handle Invalid Input Gracefully</h3><p>To robustly prompt the user for an integer and discard any invalid input, you need to clear the error state and ignore the bad input. Here’s how you do it:</p><pre>#include &lt;iostream&gt;<br>int main() {<br>    int n;<br>    std::cout &lt;&lt; &quot;Enter a number\n&quot;;<br>    while (!(std::cin &gt;&gt; n)) {<br>        std::cout &lt;&lt; &quot;Invalid input. Please enter a number\n&quot;;<br>        std::cin.clear();                // Clear the error flag<br>        std::cin.ignore(1000, &#39;\n&#39;);     // Discard invalid input<br>    }<br>    std::cout &lt;&lt; &quot;Entered num is &quot; &lt;&lt; n &lt;&lt; std::endl;<br>}</pre><p><strong>Note:</strong><br>There is no need to read input with std::cin &gt;&gt; n before the while loop. The loop itself handles input and validation, so a separate scan is unnecessary.</p><h4>Why Are These Two Lines Mandatory?</h4><ul><li>std::cin.clear(); clears the error flag on cin (set when invalid input is entered).</li><li>std::cin.ignore(1000, ‘\n’); discards the invalid input left in the buffer, so the next input attempt works correctly.</li></ul><p><strong>Without these lines:</strong><br>The input stream remains in a failed state, and your loop will run infinitely, never accepting new input.</p><h3>Summary</h3><p>Whenever you are taking input in C++, always validate and sanitize it. Handling invalid input gracefully is a hallmark of robust programs. So next time you write a simple input statement, remember what’s happening under the hood and make your code bulletproof!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113bb302b2ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Array Reversal: From Logic to STL]]></title>
            <link>https://medium.com/@Manikandan.K.S/mastering-array-reversal-from-logic-to-stl-5f3aa20607f6?source=rss-38cabb480b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3aa20607f6</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[logic]]></category>
            <dc:creator><![CDATA[Manikandan Kandili Sivaraj]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 04:24:32 GMT</pubDate>
            <atom:updated>2025-11-16T04:24:32.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reversing an Array in C++: Three Efficient Methods Explained</h3><p>When I first learned about array manipulation in C++, one of the simplest yet most enlightening problems was reversing an array. It is a classic logic exercise that demonstrates the power of iteration, swapping, and the Standard Template Library (STL). In this article, I will explain three effective ways to reverse an array. Each method serves the same purpose but approaches the problem differently in terms of style and implementation.</p><h3>Understanding the Goal</h3><p>Reversing an array means that the first element becomes the last, the second becomes the second-last, and so on. For instance, if I start with the array {1, 2, 3, 4, 5}, the output after reversing should be {5, 4, 3, 2, 1}.</p><p>Let us now go through three primary methods to achieve this efficiently.</p><h3>1. Two-Pointer Technique (Most Common Method)</h3><p>This is one of the most fundamental and intuitive methods to reverse an array. The idea is simple: use two pointers, one starting from the beginning and the other from the end, and swap their values while moving toward the center.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main() {<br>    int arr[] = {1, 2, 3, 4, 5};<br>    int n = sizeof(arr) / sizeof(arr[0]);<br><br>    // reverse using two-pointer method<br>    int start = 0, end = n - 1;<br><br>    while (start &lt; end) {<br>        int temp = arr[start];<br>        arr[start] = arr[end];<br>        arr[end] = temp;<br><br>        start++;<br>        end--;<br>    }<br><br>    // print reversed array<br>    for (int i = 0; i &lt; n; i++) {<br>        cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>    }<br><br>    return 0;<br>}</pre><p>Time Complexity: O(n)<br>Space Complexity: O(1)</p><p>This method executes in linear time with constant space. It is both memory efficient and easy to understand, making it ideal for beginners.</p><h3>2. Using a For Loop and std::swap</h3><p>In modern C++, the std::swap function simplifies element swapping. The core logic remains similar to the two-pointer approach, but using std::swap makes the implementation cleaner and safer.</p><pre>#include &lt;iostream&gt;<br>#include &lt;utility&gt;  // for std::swap<br><br>int main() {<br>    int arr[] = {10, 20, 30, 40, 50};<br>    int n = sizeof(arr) / sizeof(arr[0]);<br><br>    // Swap symmetric elements<br>    for (int i = 0; i &lt; n / 2; i++) {<br>        std::swap(arr[i], arr[n - i - 1]);<br>    }<br><br>    for (int i = 0; i &lt; n; i++)<br>        std::cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>    return 0;<br>}</pre><p>Time Complexity: O(n)<br>Space Complexity: O(1)</p><p>This version is concise and relies on a standard utility function, reducing the chance of logical errors during swapping.</p><h3>3. Using std::reverse from the Standard Library</h3><p>The most elegant solution is to use the built-in std::reverse function available in the &lt;algorithm&gt; header. It abstracts away the pointer logic and provides a ready-to-use, optimized implementation.</p><pre>#include &lt;iostream&gt;<br>#include &lt;algorithm&gt; // for std::reverse<br><br>int main() {<br>    int arr[] = {3, 1, 4, 1, 5, 9};<br>    int n = sizeof(arr) / sizeof(arr[0]);<br><br>    // STL reverse function<br>    std::reverse(arr, arr + n);<br><br>    for (int i = 0; i &lt; n; i++)<br>        std::cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br>    return 0;<br>}</pre><p>You can also write this as:</p><pre>reverse(&amp;arr[0], &amp;arr[n]);  </pre><p>Time Complexity: O(n)<br>Space Complexity: O(1)</p><p>This is the most concise and professional approach, especially for production code where readability and reliability matter.</p><h3>Choosing the Right Method</h3><p>All three methods perform equally well in terms of efficiency, so the choice depends on the context:</p><ul><li>Use the two-pointer method when explaining or practicing core logic.</li><li>Use std::swap for clearer and safer code, rather than implementing the swap logic yourself.</li><li>Use std::reverse for professional projects where simplicity and maintainability are priorities.</li></ul><p>Reversing an array might seem like a basic exercise, but it strengthens understanding of loops, indexing, and how algorithms work in place without extra memory. Mastering such small logic-based problems builds confidence for tackling more complex algorithmic challenges later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3aa20607f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Transfer GitHub Copilot Chat History in VSCode Between Devices]]></title>
            <link>https://medium.com/@Manikandan.K.S/how-to-transfer-github-copilot-chat-history-in-vscode-between-devices-97edf082c160?source=rss-38cabb480b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/97edf082c160</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Manikandan Kandili Sivaraj]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 13:41:22 GMT</pubDate>
            <atom:updated>2025-11-15T13:41:22.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*ckc81XYhE3Ax_RNNqXZ8gA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dpQE0q0v-YiZZSug" /><figcaption>Photo by <a href="https://unsplash.com/@akurakuu?utm_source=medium&amp;utm_medium=referral">kuu akura</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working on multiple machines, developers often wish to retain their previous GitHub Copilot chat sessions, especially when those sessions contain valuable insights or troubleshooting records. In this article, I explain how to locate, export, and import Copilot chat history in Visual Studio Code across different laptops assuming a Windows environment.</p><h3>Understanding Where Copilot Chat History Is Stored</h3><p>In Visual Studio Code, chat history for Copilot is saved locally in a hidden workspace directory. Each project or workspace receives a unique folder name within the main storage path.</p><p>On Windows, the storage location is:</p><pre>C:\Users\&lt;your-username&gt;\AppData\Roaming\Code\User\workspaceStorage</pre><p>Inside the workspaceStorage directory, you will notice several folders with long, alphanumeric names such as:</p><pre>5560a56aeb07ed07a0a2be92b28c7e01<br>7927a352490752d89d45d86565940562<br>8eaa784b66d94dd648b400aea44dcd96</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWTl82jWEgxZwDfbbI1OLg.png" /></figure><p>Each folder represents a different workspace in VS Code.</p><h3>Finding and Exporting Your Chat Sessions</h3><p>Within each workspace folder, look for a directory named chatSessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zng3HwiqRzHxactSVlMcMg.png" /></figure><p>This is where your Copilot chat sessions are saved. Inside the chatSessions folder, you will find JSON files that hold the entire conversation history for that workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2l2xP5DPNoXz_vLX6GOVQ.png" /></figure><p>To export a chat session, you can either use VS Code’s interface commands like “Chat: Export Session…” or “Chat: Export Chat…” from the command palette (Ctrl+Shift+P), or you can simply copy the relevant JSON files directly.</p><h3>Importing Chats to Another Laptop</h3><p>If you want to access your older Copilot chats on a new laptop, just copy the desired chatSessions JSON files into the same location in your new workspace folder. Make sure the workspace you are working on is the same, otherwise, you may need to locate or create the appropriate workspace directory first.</p><p>After copying the JSON files, open VS Code and you will be able to read and continue from your old Copilot chats within the correct workspace context.</p><h3>Common Issues and Troubleshooting</h3><ul><li>If your chat does not appear as expected, double-check that you placed the JSON files into the right workspaceStorage subfolder corresponding to your current project.</li><li>If the “Import Chat” option is unavailable in your version of VS Code, copying the JSON files directly is still effective.</li></ul><h3>Example File Paths</h3><ul><li>On Laptop A (where chat history exists):</li></ul><pre>C:\Users\Alice\AppData\Roaming\Code\User\workspaceStorage\7927a352490752d89d45d86565940562\chatSessions\session.json</pre><ul><li>Copy to Laptop B (to access the same workspace’s chats):</li></ul><pre>C:\Users\Bob\AppData\Roaming\Code\User\workspaceStorage\7927a352490752d89d45d86565940562\chatSessions\session.json</pre><p>This method is reliable and does not require any special export or cloud sync features at present.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97edf082c160" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The #1 Mistake Beginners Make with For Loops and Time Complexity]]></title>
            <link>https://medium.com/@Manikandan.K.S/the-1-mistake-beginners-make-with-for-loops-and-time-complexity-578e8ae88437?source=rss-38cabb480b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/578e8ae88437</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Manikandan Kandili Sivaraj]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 13:16:54 GMT</pubDate>
            <atom:updated>2025-06-04T13:20:42.810Z</atom:updated>
            <content:encoded><![CDATA[<p>As an interviewer and mentor, I have seen many freshers struggle with calculating time complexity when dealing with multiple for loops, especially when these loops are either consecutive or nested. Understanding the difference between these scenarios is crucial for writing efficient code and for acing technical interviews. Let me break down the most common mistakes and clarify the right approach.</p><h3>Consecutive vs. Nested Loops: The Key Difference</h3><p>A frequent misconception is assuming that any two for loops in a function automatically result in a quadratic time complexity, O(n²). This is not always true. The actual complexity depends on whether the loops are <strong>consecutive</strong> (one after another) or <strong>nested</strong> (one inside the other).</p><h3>Consecutive Loops</h3><p>Consider this code:</p><pre>for (int i = 0; i &lt; n; ++i) {<br>    // some O(1) operation<br>}<br>for (int j = 0; j &lt; n; ++j) {<br>    // some O(1) operation<br>}</pre><p>Here, the first loop runs n times, and then the second loop runs n times. The total number of operations is n + n = 2n, which simplifies to O(n). In Big O notation, constant factors (like 2) are ignored as they do not affect the growth rate for large <em>n</em>. Thus, 2n simplifies to O(n).</p><p>The key is that the loops are independent and do not multiply their iterations.</p><h3>Nested Loops</h3><p>Now, look at this:</p><pre>for (int i = 0; i &lt; n; ++i) {<br>    for (int j = 0; j &lt; n; ++j) {<br>        // some O(1) operation<br>    }<br>}</pre><p>In this case, for every iteration of the outer loop, the inner loop runs n times. So, the total number of operations is n * n = n², which is O(n²). This is where the multiplication comes in, and the complexity increases much faster as n grows.</p><h3>Common Mistake #1: Multiplying When You Should Add</h3><p>Many beginners see two for loops and immediately multiply their counts. Remember:</p><ul><li><strong>Consecutive loops:</strong> Add their complexities (O(n) + O(n) = O(n))</li><li><strong>Nested loops:</strong> Multiply their complexities (O(n) * O(n) = O(n²))</li></ul><h3>Common Mistake #2: Ignoring Loop Dependencies</h3><p>Some nested loops are not as straightforward. For example:</p><pre>for (int i = 0; i &lt; n; ++i) {<br>    for (int j = i; j &lt; n; ++j) {<br>        // some O(1) operation<br>    }<br>}</pre><p>Here, the number of inner loop iterations depends on the value of i. For i = 0, j runs n times; for i = 1, n - 1 times, and so on. The total number of operations is the sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*u0-cmTXQQgwjKksSi8G1Iw.png" /></figure><p>This still simplifies to O(n²), but it is important to recognize the pattern and not just blindly multiply.</p><h3>Practical Tips for Beginners</h3><ul><li><strong>Write out small examples:</strong> If you are unsure, try running your loops with small values of n and count the number of operations.</li><li><strong>Break down each loop:</strong> Ask yourself: Is this loop independent, or does it depend on another variable?</li><li><strong>Remember the difference:</strong> Addition for consecutive, multiplication for nested.</li><li><strong>Look for dependencies:</strong> If the inner loop’s range depends on the outer loop variable, sum up the iterations for each value of the outer variable.</li></ul><h3>Conclusion</h3><p>Calculating time complexity is a fundamental skill for any programmer. The most common mistakes stem from not distinguishing between consecutive and nested loops, and from not analyzing loop dependencies carefully. By practicing with different loop structures and always questioning how many times each line of code executes, you will build a strong intuition for algorithm analysis.</p><p>Happy coding, and remember; clarity in your analysis leads to clarity in your code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=578e8ae88437" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Print Boolean Values as true/false Instead of 1/0 in C++?]]></title>
            <link>https://medium.com/@Manikandan.K.S/how-to-print-boolean-values-as-true-false-instead-of-1-0-in-c-1742c96435b9?source=rss-38cabb480b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/1742c96435b9</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[Manikandan Kandili Sivaraj]]></dc:creator>
            <pubDate>Tue, 20 May 2025 11:15:37 GMT</pubDate>
            <atom:updated>2025-05-20T11:20:05.672Z</atom:updated>
            <content:encoded><![CDATA[<h4>C++ Tip: Printing Boolean Values as true/false Instead of 1/0</h4><p>As programmers, we often encounter situations where we want to print boolean values. By default, C++ prints true as 1 and false as 0 when you use std::cout. While this is perfectly valid, sometimes it’s more readable and user-friendly to print the actual words &quot;true&quot; and &quot;false&quot;.</p><p>Here’s a quick tip: C++ provides a handy stream manipulator called std::boolalpha that tells the output stream to print boolean values as true or false instead of 1 or 0.</p><p>Let me demonstrate with a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCUu8WCiUK58wp4W_lG79g.png" /></figure><p>When you use std::boolalpha, the stream converts the boolean values to their textual representation. If you want to revert back to printing 1 and 0, you can use std::noboolalpha.</p><p>This small feature can make debugging output or user-facing messages much clearer. It’s a simple trick but very useful in practice.</p><p>I hope this helps you write clearer C++ code when dealing with boolean outputs! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1742c96435b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Mistake Many Beginners Make About std::set Lookup Time]]></title>
            <link>https://medium.com/@Manikandan.K.S/the-mistake-many-beginners-make-about-std-set-lookup-time-dba5f6c91181?source=rss-38cabb480b31------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba5f6c91181</guid>
            <dc:creator><![CDATA[Manikandan Kandili Sivaraj]]></dc:creator>
            <pubDate>Mon, 19 May 2025 13:57:57 GMT</pubDate>
            <atom:updated>2025-05-19T13:57:57.974Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning about C++ data structures, I made a common mistake that many beginners often make — underestimating the time complexity of lookups in certain containers. Specifically, I wrongly assumed that the <strong>lookup</strong> operation in std::set had <strong>O(1)</strong> time complexity, just like it does in <strong>unordered_map</strong> or <strong>unordered_set</strong>. Little did I know, this assumption was far from accurate, and I ended up learning the hard way why understanding time complexities is crucial for efficient programming.</p><p>Let me walk you through this learning journey and explain the correct behavior of std::set and why understanding the differences in time complexities is important.</p><h3>What is a std::set?</h3><p>Before diving into time complexities, let me clarify what std::set is. In C++, std::set is a collection that stores unique elements in sorted order. std::setis <strong>not a key-value pair structure</strong> like std::map; rather, it stores <strong>only keys</strong>, and each key is treated as both the key and the value. Internally, it is implemented as a <strong>binary search tree (BST)</strong>—more specifically, usually a <strong>red-black tree</strong>, which is a type of self-balancing BST. This underlying structure is what gives std::set its specific performance characteristics.</p><h3>The Key Mistake: Assuming O(1) Lookup</h3><p>As I started learning about different <strong>key-value</strong> data structures, I became familiar with <strong>hash maps</strong> (or <strong>unordered_map</strong> in C++). These data structures are known for their <strong>O(1)</strong> average time complexity for lookup operations, thanks to their use of hash tables. So, naturally, I assumed that lookup in std::set would behave similarly because, after all, it’s also used to store elements.</p><p>However, this assumption was wrong, and it wasn’t until I started measuring the performance of my programs that I realized why. In reality, the <strong>lookup operation in a </strong><strong>std::set has a time complexity of O(log n)</strong>, not O(1).</p><h3>Why is Lookup O(log n) in std::set?</h3><p>The main reason the lookup in a std::set is <strong>O(log n)</strong> is because it is backed by a <strong>binary search tree (BST)</strong>. Here’s a quick rundown of how binary search trees work:</p><ol><li><strong>Elements are ordered</strong> in the tree. This means that for each node, all the elements in the left subtree are smaller, and all the elements in the right subtree are larger.</li><li><strong>Searching</strong> involves traversing the tree from the root, following either the left or right child based on comparisons with the current node. This process effectively <strong>splits the search space in half</strong> at each step.</li><li>Because the tree is <strong>balanced</strong> (in the case of a red-black tree), the maximum height of the tree is <strong>log(n)</strong>, where <strong>n</strong> is the number of elements.</li></ol><p>Thus, to find an element, you traverse the tree in a way that’s <strong>logarithmic</strong> in relation to the number of elements. This gives the <strong>O(log n)</strong> time complexity for <strong>search</strong>, <strong>insertion</strong>, and <strong>deletion</strong> operations in a std::set.</p><h3>Contrast with unordered_set</h3><p>If you’re familiar with unordered_set, it’s important to note the difference between the two. <strong>unordered_set</strong> is backed by a <strong>hash table</strong> and typically provides <strong>O(1)</strong> average time complexity for lookup, insertion, and deletion. This is because hash tables can access elements in constant time using hash functions to directly access the memory location of the element.</p><p>However, <strong>std::set</strong> is different. Its underlying structure (a balanced binary search tree) guarantees <strong>sorted order</strong> but sacrifices the fast lookup speed of a hash table for it.</p><p>So while <strong>unordered_set</strong> is faster for lookups on average, <strong>std::set</strong> maintains an ordered collection, which can be an important factor depending on the problem you&#39;re trying to solve.</p><h3>Why Understanding Time Complexities Matters</h3><p>One of the most important lessons I learned was that <strong>understanding time complexities</strong> is crucial for writing efficient code. The time complexity tells you how the performance of your algorithm or data structure scales as the input size grows.</p><p>For example, if I had continued assuming that lookups in std::set were O(1), I might have used it in situations where speed was critical—only to discover later that my program was slower than expected, especially as the number of elements increased.</p><p>Instead, once I understood that std::set uses a <strong>logarithmic</strong> time complexity for lookups, I became more intentional in choosing the right data structure for the right problem. If I needed fast lookups and didn’t care about ordering, I would use <strong>unordered_set</strong>. If I needed elements sorted or wanted to perform range queries efficiently, then <strong>std::set</strong> would be the right choice.</p><h3>Time Complexities for std::set Operations:</h3><p>Here’s an overview of the time complexities for common operations on std::set in C++:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*q-c3eODGaUF5yp7menu-5A.png" /></figure><h3>Conclusion</h3><p>The key takeaway from my mistake is simple: <strong>always check the time complexities of the data structures you’re using</strong>. It’s easy to assume that certain operations will be faster than they are, especially when working with collections that seem similar. By understanding the underlying data structures and their performance characteristics, you’ll be much better equipped to make decisions that lead to more efficient and scalable code.</p><p>So, next time you’re choosing between std::set and unordered_set, remember that while both store unique elements, the time complexity for lookup is <strong>O(log n)</strong> for std::set and <strong>O(1)</strong> for unordered_set.</p><p>I hope this post helps you avoid the mistake I made early on. Stay curious and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dba5f6c91181" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>