<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Abhinandan Sharma</title>
    <description>The latest articles on DEV Community by Abhinandan Sharma (@abhi824).</description>
    <link>https://dev.to/abhi824</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F587732%2F4e30305d-745a-4fb2-b4e1-54a3fcebe131.jpeg</url>
      <title>DEV Community: Abhinandan Sharma</title>
      <link>https://dev.to/abhi824</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/abhi824"/>
    <language>en</language>
    <item>
      <title>Cursor for PPT | MCP Exploration</title>
      <dc:creator>Abhinandan Sharma</dc:creator>
      <pubDate>Wed, 11 Jun 2025 18:37:14 +0000</pubDate>
      <link>https://dev.to/abhi824/cursor-for-ppt-mcp-server-176k</link>
      <guid>https://dev.to/abhi824/cursor-for-ppt-mcp-server-176k</guid>
      <description>&lt;p&gt;I was chilling out with a friend(who is in big 4), he complaining about the work life balance and booking tickets to Goa for onsite trip(after visiting Thailand last month), the usual. We kind of got into discussions on AI and the general belief that it will eat dev jobs, like that will scare me(I make excellent tea, so my backup plan is always there) where he discussed a crucial problem many consultants, bankers and all suit people face: &lt;strong&gt;PPT automation&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Companies have internal tools connected with internal data sources which help in automating much of the task in hand but there is more to it. Small consulting firms, compliance firms, analytics firms need powerpoint presentations automated with a fixed suite of components and consistent design. And that's where it hit me. &lt;/p&gt;

&lt;p&gt;I did some market research on perplexity and found out that there exists:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Beautiful.ai who are focussed on automating with their own set of templates.&lt;/li&gt;
&lt;li&gt;Slidebean: Who helps founders make their flashy decks to loot on investors.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But I couldn't find a proper enterprise level product who can intake the styles proposed by the tenant(client) and data sources fixed by them and produce the decks accordingly.&lt;br&gt;
Generating everything in one go is kind of risky as AI can hallucinate. If prompted to create from scratch, we are bound to get inconsistent designs, wrong detailing, no org level styling and most of all: loss of control.&lt;/p&gt;

&lt;p&gt;As a software developer with no experience in building businesses, I started implementing.(Obviously didn't reach out any clients if there is a need, or what's the need because I am a cutie devootie)&lt;/p&gt;

&lt;p&gt;Anyways, I started reading about AI agentic things and once famous, buzzing keyword I stumbled on pretty quickly was: MCP.&lt;/p&gt;

&lt;p&gt;Now, MCP is Model Context Protocol and here is an awesome course explaining everything about it: &lt;a href="https://huggingface.co/learn/mcp-course/en/unit0/introduction" rel="noopener noreferrer"&gt;Hugging Face MCP Course&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Some key concepts, just for a brush up:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Host, Client and Server: The Host is the user-facing AI application that end-users interact with directly. The Client is a component within the Host application that manages communication with a specific MCP Server. The Server is an external program or service that exposes capabilities to AI models via the MCP protocol. A single Host can connect to multiple Servers simultaneously via different Clients. Each Client maintains a 1:1 connection with a single Server. New Servers can be added to the ecosystem without requiring changes to existing Hosts. Capabilities can be easily composed across different Servers.&lt;/li&gt;
&lt;li&gt;MCP works on JSON-RPC: JSON-RPC is a lightweight remote procedure call protocol encoded in JSON. A Request message includes a unique identifier (id), the method name to invoke (e.g., tools/call) and parameters for the method (if any).&lt;/li&gt;
&lt;li&gt;Transport Mechanisms: JSON-RPC defines the message format, but MCP also specifies how these messages are transported between Clients and Servers. . There are two: stdio and HTTP + SSE/Streamable HTTP. The stdio transport is used for local communication where the Client and Server run on the same machine. The HTTP+SSE transport is used for remote communication. Communication happens over HTTP, with the Server using Server-Sent Events (SSE) to push updates to the Client over a persistent connection.&lt;/li&gt;
&lt;li&gt;Tools are executable functions or actions that the AI model can invoke through the MCP protocol.&lt;/li&gt;
&lt;li&gt;Resources provide read-only access to data sources, allowing the AI model to retrieve context without executing complex logic.&lt;/li&gt;
&lt;li&gt;Prompts are predefined templates or workflows that guide the interaction between the user, the AI model, and the Server’s capabilities.&lt;/li&gt;
&lt;li&gt;Sampling allows Servers to request the Client (specifically, the Host application) to perform LLM interactions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now we have knowledge of the MCP servers, time to layout a plan. &lt;br&gt;
This is what I came up at first(and implemented it!).&lt;/p&gt;

&lt;p&gt;The first problem is the lost control and inconsistent styling when we ask AI to generate the whole thing. So, I came up with the concept of components. Like in React, we have a css framework which can provide existing &lt;strong&gt;components&lt;/strong&gt; which not only ease the dev work but make the whole styles consistent and abstract us from the intricacies like padding a specific element. So, why not have components in PPT as well.&lt;/p&gt;

&lt;p&gt;For the first MVP, I set these requirements:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;There is a Component list which AI can generate from. Maybe some small components like textbox, bullet points etc.&lt;/li&gt;
&lt;li&gt;There should be atleast two themes which will define the overall color scheme of the document. &lt;/li&gt;
&lt;li&gt;The PPT generation part is handled by our server.&lt;/li&gt;
&lt;li&gt;Saving the ppt in local.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Claude happens to have excellent MCP server connectivity. So, I started with this simple architecture:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ladxixyydvapecklvh1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ladxixyydvapecklvh1.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Claude here will connect to my MCP server. The MCP server would contain different tools for each component which will connect to Fast API server through a REST protocol. The server itself will do the changes in the PPT. Keep in mind that we are just building it for local right now and this is the first iteration. &lt;/p&gt;

&lt;p&gt;The server will look like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcs91rtt2xs767lrm6z89.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcs91rtt2xs767lrm6z89.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have a single endpoint(/slide/{id}/component) for adding each component in a particular, with simple request body mapping to the component class. Pretty straightforward. &lt;br&gt;
We have a different endpoint for saving and setting a theme. Since we right now are thinking of having it in local, I haven't added a ppt id. We will improve on the current code only to make it better and better overtime. &lt;/p&gt;

&lt;p&gt;This is how it worked:&lt;/p&gt;

&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/gmdh_tEMJEo"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Github URL for the first MVP version: &lt;/p&gt;
&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://assets.dev.to/assets/github-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/abhi-824" rel="noopener noreferrer"&gt;
        abhi-824
      &lt;/a&gt; / &lt;a href="https://github.com/abhi-824/mcp-ppt-automation" rel="noopener noreferrer"&gt;
        mcp-ppt-automation
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      
    &lt;/h3&gt;
  &lt;/div&gt;
&lt;/div&gt;


&lt;p&gt;Now we have built a foundation, let's build on this and see the requirements now. &lt;/p&gt;

&lt;h2&gt;
  
  
  Final Idea
&lt;/h2&gt;

&lt;p&gt;Cursor-like software for Powerpoint. An add in which acts as a chat interface. Then for each change, accept/reject changes component-wise and having the previous changes in memory. Accessing any other file as reference, like "From @analysis.excel get the data and convert it into chart data and add it as a pie chart."   &lt;/p&gt;

&lt;p&gt;This is a strong vision but is feasible. So, let's start with the requirements:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Powerpoint add in for chatbot interface&lt;/li&gt;
&lt;li&gt;Accepting/rejecting changes done component wise&lt;/li&gt;
&lt;li&gt;Accessing any other files as reference&lt;/li&gt;
&lt;li&gt;Generation of charts possible&lt;/li&gt;
&lt;li&gt;Expanding and beautifying the component library&lt;/li&gt;
&lt;li&gt;Tenant decide the component library. For each component, there may exist a suite of styles available to pick from.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The next blogs would be in phases and by each blog we will get a step closer to the final goal. &lt;/p&gt;




&lt;h2&gt;
  
  
  Connect with me
&lt;/h2&gt;

&lt;p&gt;I post about AI tools, coding challenges, and product experiments.&lt;/p&gt;

&lt;p&gt;🧵 Follow me on Twitter: &lt;a href="https://x.com/abhinandan824" rel="noopener noreferrer"&gt;@abhinandan824&lt;/a&gt;&lt;br&gt;&lt;br&gt;
💼 Let’s connect on LinkedIn: &lt;a href="https://www.linkedin.com/in/abhinandan-sharma-dtu/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/abhinandan-sharma-dtu/&lt;/a&gt;  &lt;/p&gt;

</description>
      <category>ai</category>
      <category>mcp</category>
      <category>learning</category>
      <category>showdev</category>
    </item>
    <item>
      <title>Operating Systems Interview Preparation Notes</title>
      <dc:creator>Abhinandan Sharma</dc:creator>
      <pubDate>Sun, 15 Aug 2021 19:08:10 +0000</pubDate>
      <link>https://dev.to/abhi824/operating-systems-interview-preparation-notes-408l</link>
      <guid>https://dev.to/abhi824/operating-systems-interview-preparation-notes-408l</guid>
      <description>&lt;p&gt;If you are struggling with the right track and a 10-min read for Operating systems from begin to end, you're at right place. Even I am not sure where to start, but we would figure it and if you are reading this, I have successfully completed these notes or at least am on right track.&lt;/p&gt;

&lt;p&gt;Let's start our struggle for OS:&lt;/p&gt;

&lt;h3&gt;
  
  
  The Track
&lt;/h3&gt;

&lt;p&gt;I found many resources to learn, let's just list all:&lt;br&gt;
[Galvin Concise PPTs)[&lt;a href="https://www.os-book.com/OS9/slide-dir/index.html%5D:" rel="noopener noreferrer"&gt;https://www.os-book.com/OS9/slide-dir/index.html]:&lt;/a&gt; These were great but I felt that these are a little bit too much, so here are the chapters we would do:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Processes&lt;/li&gt;
&lt;li&gt;Threads&lt;/li&gt;
&lt;li&gt;Process Synchronization&lt;/li&gt;
&lt;li&gt;CPU Scheduling Algorithms&lt;/li&gt;
&lt;li&gt;Deadlocks&lt;/li&gt;
&lt;li&gt;Main memory&lt;/li&gt;
&lt;li&gt;Virtual memory&lt;/li&gt;
&lt;li&gt;Virtual Machines&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;I am skipping introduction of OS for now as it was not that important, this is going to be a fast article which works like a last night dose.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  Processes
&lt;/h4&gt;

&lt;p&gt;Processes are a program in execution. It has its own memory which is divided into four parts: Text, Data, Heap and Stack.&lt;/p&gt;

&lt;p&gt;Brief explanation about these &lt;br&gt;
Text: Stores the compiled program code. &lt;/p&gt;

&lt;p&gt;Data: stores global and static variables&lt;/p&gt;

&lt;p&gt;Heap: Stores dynamically allocated data&lt;/p&gt;

&lt;p&gt;Stack: Stores local variables.&lt;/p&gt;

&lt;p&gt;Process, as the name suggests, have different states (just like making a joint). Here is a diagram which says it all:&lt;/p&gt;

&lt;p&gt;Diagram&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcrkkcao6l865874kz3sw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcrkkcao6l865874kz3sw.png" alt="alt text" width="658" height="388"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Process Control Block(PCB)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is a data structure that stores all information about a process. &lt;/p&gt;

&lt;p&gt;It contains these:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Process State: We already saw these&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Process ID: self-explanatory&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;CPU registers and Program Counter: It is basically a pointer to next instruction to be executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;CPU scheduling information: priority and pointers to scheduling queues(will see later)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Memory management information: self-explanatory&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Accounting Information: CPU time consumed, limits, etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;I/o Status information: Devices allocated, open file tables, etc.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Process Scheduling Queues&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This handles the order of execution of the process. We have different queues for different states. When the state of a process is changed, it is simply detached from the current queue and added to it's new state's queue. &lt;/p&gt;

&lt;p&gt;This says it all&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqqewgpq5wacqfg6eaz1v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqqewgpq5wacqfg6eaz1v.png" alt="alt text" width="744" height="443"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Please note that we are not actually studying scheduling algorithms, we are just assuming that we have some given order and how the processes are executed.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Schedulers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are three types of schedulers, long term, short term and mid term schedulers. &lt;/p&gt;

&lt;p&gt;Brief explanation&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Long term Schedulers: These are responsible for sending a process from new to ready queue. It has to maintain degree of multi programming which is simply this: Average rate of incoming = average rate of outgoing. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Short term schedulers/ CPU schedulers: From ready queue to running queue. (I think it's clear)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Mid term schedulers: These are special type of schedulers with a unique functionality: when a process is paused(maybe it needs some input) it, &lt;strong&gt;swaps in&lt;/strong&gt; the process and allocates this position to some other process and when it arrives again, &lt;strong&gt;swaps out&lt;/strong&gt; the other process and resume the previous process.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Scheduling Algorithms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Terminology&lt;br&gt;
&lt;strong&gt;Arrival Time&lt;/strong&gt;: Time at which process arrives in ready queue&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Completion Time&lt;/strong&gt;: Time at which process completes its execution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Burst Time&lt;/strong&gt;: Time required by process for CPU execution&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Turn Around Time&lt;/strong&gt;: Time difference between completion and arrival time.(How it's different from burst time?)(Add waiting time here as well)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Waiting Time&lt;/strong&gt;: Turnaround time-burst time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Throughput&lt;/strong&gt;: Total number of processes completed per unit time. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Non-preemptive Algorithms&lt;/strong&gt;: Once a processes is in ready queue we cannot pause it's execution until it's completely executed. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Preemptive Algorithms&lt;/strong&gt;: Opposite of non-preemptive. Period.&lt;/p&gt;

&lt;p&gt;Let's start with algorithms.&lt;/p&gt;

&lt;p&gt;First Come First Serve(FCFS)&lt;br&gt;
Widely used in college admissions, this algorithm is just what it says. Whichever process arrives first, it will execute the process first and then jump to second process. (Non-preemptive Algorithm)&lt;/p&gt;

&lt;p&gt;Here is a simple C++ code&lt;br&gt;
You seriously opened this? Please try this yourself. It is very simple just a sort will do the work.&lt;/p&gt;

&lt;p&gt;This gag diagram will help you understand FCFS:&lt;/p&gt;

&lt;p&gt;Gag diagram&lt;br&gt;
Processes:&lt;br&gt;
Processes  | Burst Time&lt;/p&gt;

&lt;p&gt;P1         | 7&lt;/p&gt;

&lt;p&gt;P2         | 3&lt;/p&gt;

&lt;p&gt;P3         | 10&lt;/p&gt;

&lt;p&gt;P4         | 5&lt;/p&gt;

&lt;p&gt;Gag Diagram:&lt;/p&gt;

&lt;p&gt;Average waiting time:&lt;/p&gt;

&lt;p&gt;Average turnaround time:&lt;/p&gt;

&lt;p&gt;Why FCFS is not that good?&lt;br&gt;
It's kind of obvious. If the arrival time of a process which takes a lot of time than others is less, it will slow down the operating system. &lt;/p&gt;

&lt;p&gt;Shortest Job First(SJS)&lt;br&gt;
Just sort the jobs according to their burst times. And we schedule the jobs according to that order only. It is a non-preemptive algorithm but there does exists a preemptive algorithm for SJS as well.&lt;/p&gt;

&lt;p&gt;C++ Code for non-preemptive SJS&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include&amp;lt;bits/stdc++.h&amp;gt;
using namespace std;
#define int long long int
int32_t main()
{
    int n;cin&amp;gt;&amp;gt;n;
    vector&amp;lt;pair&amp;lt;int,int&amp;gt;&amp;gt; times(n);
    vector&amp;lt;pair&amp;lt;int,int&amp;gt;&amp;gt; duration(n);
    // vector&amp;lt;Time&amp;gt;a;
    for(int i=0;i&amp;lt;n;i++)
    {
        cin&amp;gt;&amp;gt;times[i].first&amp;gt;&amp;gt;times[i].second;
        duration[i].second=i;
        duration[i].first=times[i].second-times[i].first;
    }

    sort(duration.begin(),duration.end());

    // Order of jobs is the duration.second order
    // Now we need to find turnaround time, waiting time and
    // Completion time for every process
    int total_waiting_time=0;
    int total_turnaround_time=0;
    int t=0;
    for(int i=0;i&amp;lt;n;i++)
    {
        cout&amp;lt;&amp;lt;"Process "&amp;lt;&amp;lt;duration[i].second+1&amp;lt;&amp;lt;" in ready queue now!\n";
        t=max(times[duration[i].second].first,t);
        t+=duration[i].first;
        int turnaround_time=t-times[duration[i].second].first;
        total_turnaround_time+=turnaround_time;
        cout&amp;lt;&amp;lt;"Turn Around Time: "&amp;lt;&amp;lt;turnaround_time&amp;lt;&amp;lt;"\n";
        int waiting_time=turnaround_time-duration[i].first;
        total_waiting_time+=waiting_time;
        cout&amp;lt;&amp;lt;"Waiting Time: "&amp;lt;&amp;lt;waiting_time&amp;lt;&amp;lt;"\n";
    }
    double avg_turnaround_time=(double)total_turnaround_time/n;
    double avg_waiting_time=(double)total_waiting_time/n;
    cout&amp;lt;&amp;lt;"Average Waiting Time: "&amp;lt;&amp;lt;avg_waiting_time&amp;lt;&amp;lt;"\n";
    cout&amp;lt;&amp;lt;"Average Turn Around Time: "&amp;lt;&amp;lt;avg_turnaround_time&amp;lt;&amp;lt;"\n";


    return 0;
}
~~~~~


This gag diagram will help you understand SJS:

Gag diagram
Processes:
Processes  | Burst Time

P1         | 7

P2         | 3

P3         | 10

P4         | 5

Gag Diagram:

Average waiting time:

Average turnaround time:





Disadvantages of SJS
Here we have certain time when our CPU is idle. Being idle is the worst thing we can have!(In general as well, that's why I am writing this).


It has a preemptive way also. In this, the trick is to fill those gaps which we were making. Whenever we are idle, we assign computer another process which can be filled.

C++ code for preemptive code
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To be updated&lt;br&gt;
~&lt;del&gt;&lt;/del&gt;&lt;/p&gt;

&lt;p&gt;This gag diagram will help you understand preemptive version of SJS:&lt;/p&gt;

&lt;p&gt;Gag diagram&lt;br&gt;
Processes:&lt;br&gt;
Processes  | Burst Time&lt;/p&gt;

&lt;p&gt;P1         | 7&lt;/p&gt;

&lt;p&gt;P2         | 3&lt;/p&gt;

&lt;p&gt;P3         | 10&lt;/p&gt;

&lt;p&gt;P4         | 5&lt;/p&gt;

&lt;p&gt;Gag Diagram:&lt;/p&gt;

&lt;p&gt;Average waiting time:&lt;/p&gt;

&lt;p&gt;Average turnaround time:&lt;/p&gt;

&lt;p&gt;Round Robin Algorithm&lt;/p&gt;

&lt;p&gt;In this algorithm, we have fixed time slots and we execute the processes sequentially in the order given and switch between processes after every fixed time. This gag diagram will help you understand:&lt;/p&gt;

&lt;p&gt;Gag diagram&lt;br&gt;
Processes:&lt;br&gt;
Processes  | Burst Time&lt;/p&gt;

&lt;p&gt;P1         | 7&lt;/p&gt;

&lt;p&gt;P2         | 3&lt;/p&gt;

&lt;p&gt;P3         | 10&lt;/p&gt;

&lt;p&gt;P4         | 5&lt;/p&gt;

&lt;p&gt;Gag Diagram:&lt;/p&gt;

&lt;p&gt;Average waiting time:&lt;/p&gt;

&lt;p&gt;Average turnaround time:&lt;/p&gt;

&lt;p&gt;C++ Code&lt;br&gt;
TBU&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Process synchronization&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Processes categorized on basis of synchronization &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Independent Process : Execution of one process does not affects the execution of other processes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cooperative Process : Execution of one process affects the execution of other processes.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Process synchronization problem arises in the case of Cooperative process also because resources are shared in Cooperative processes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Race Condition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When more than one processes are executing the same code or accessing the same memory or any shared variable in that condition there is a possibility that the output or the value of the shared variable is wrong so for that all the processes doing the race to say that my output is correct this condition known as a race condition. Several processes access and process the manipulations over the same data concurrently, then the outcome depends on the particular order in which the access takes place.&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
Suppose we have two operations, cnt++ and cnt--, from two different processes acting on a global variable cnt.&lt;/p&gt;

&lt;p&gt;++ Operation :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int reg=cnt;
reg=reg-1;
cnt=reg;
~~~~~

-- Operation:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;int reg2=cnt;&lt;br&gt;
reg2=reg2-1;&lt;br&gt;
cnt=reg2;&lt;br&gt;
~&lt;del&gt;&lt;/del&gt;&lt;/p&gt;

&lt;p&gt;Now, we need to do these operation in this order:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int reg=cnt;
reg=reg-1;
cnt=reg;
int reg2=cnt;
reg2=reg2-1;
cnt=reg2;
~~~~~

But as the resource is shared, it can happen in any order, maybe this one as well:

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;int reg=cnt;&lt;br&gt;
reg=reg-1;&lt;br&gt;
int reg2=cnt;&lt;br&gt;
cnt=reg;&lt;br&gt;
reg2=reg2-1;&lt;br&gt;
cnt=reg2;&lt;br&gt;
~&lt;del&gt;&lt;/del&gt;&lt;/p&gt;

&lt;p&gt;This will lead to cnt's final value as 4 if initial value is 5.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Critical Section&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Critical section is a code segment which can be accessed by only one process at a time. This code segment is common in many processes and if many processes run simultaneously, we would have a hard time finding the process containing the error, if it happens.&lt;/p&gt;

&lt;p&gt;Any solution to critical section should must satisfy these rules.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Mutual Exclusion : If a process is executing in its critical section, then no other process is allowed to execute in the critical section.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Progress : If no process is executing in the critical section and other processes are waiting outside the critical section, then only those processes that are not executing in their remainder section can participate in deciding which will enter in the critical section next, and the selection can not be postponed indefinitely.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Bounded Waiting : A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is what critical section looks like&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F20dzuo5i1gsw809rffs3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F20dzuo5i1gsw809rffs3.png" alt="alt text" width="409" height="431"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Peterson's Solution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we saw earlier, we need a solution for critical section of code, as it can lead to anomalies. This solution should satisfy the rules we mentioned before.&lt;/p&gt;

&lt;p&gt;Simple Psuedo code&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int turn;
bool flag[2];
do{
    flag[i]=1;
    turn=j;
    while(flag[j]&amp;amp;&amp;amp;turn==j);
    /////////////////////
    // Critical section//
    /////////////////////
    flag[i]=0;
    ///////////////////////
    // Remainder section///
    ///////////////////////

}
while(1)
~~~~~ 



How it works
Before actually seeing how it works, please have another look of the things we want it to satisfy.
These 3 rules:

1. Mutual exclusion
2. Progress
3. Bounded Waiting

Peterson solution simply assigns a turn and a flag to each process. Initially flag is 0 in all processes and turn is either 0 or 1. Flag array's on index means that this process is waiting for its turn now. And would work only if the initial process has completed it's execution. We have the while loop for this in the code. Please have a look at the code now and if you still find any difficulty, please post in comments.



**Semaphores**

Semaphore is nothing but an integer variable, and this can be changed by using only these two operations:

1. Wait: It is like a decrement operation. 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;wait(S){&lt;br&gt;
   while(S&amp;lt;=0);&lt;br&gt;
   S--;&lt;br&gt;
} &lt;br&gt;
~&lt;del&gt;&lt;/del&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Signal:&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Signal(S){
   S++
} 
~~~~~

Semaphores can be counting or binary(0 or 1). 

Binary Semaphores are generally called **mutex locks** as they provide mutual exclusion.  

Counting Semaphores are used to control access to given resource for multiple processes.

Use of semaphores in handling critical section of N processes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Shared data: semaphore mutex// Initially mutex=1&lt;br&gt;
Process p[i]:&lt;br&gt;
do{&lt;br&gt;
   wait(mutex);&lt;br&gt;
   ////////////////////////&lt;br&gt;
   ////critical section////&lt;br&gt;
   ////////////////////////&lt;br&gt;
   signal(mutex);&lt;br&gt;
   ////////////////////////&lt;br&gt;
   ////remainder section///&lt;br&gt;
   ////////////////////////&lt;br&gt;
}while(1);&lt;br&gt;
~&lt;del&gt;&lt;/del&gt;&lt;/p&gt;

&lt;p&gt;How does this work?&lt;br&gt;
Whenever a process arrives we wait for the semaphore to turn to 1. Initially semaphore is 1 already so Process P1 has no wait and executes the critical section. But if second process comes now, wait function runs a while loop which kind of halt the process. Now when the first process finishes, second process continues and so on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Busy Waiting problem's solution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;problem with semaphores&lt;br&gt;
Unbounded Wait time is the main problem here.&lt;/p&gt;

&lt;p&gt;How we achieve busy waiting problem&lt;br&gt;
What we do is simple to achieve bounded wait time. We are currently holding suppose n processes due to 1 process which is running. We simply can just block the processes which are in waiting. Like, we can contain them in a list. Okay, to be very honest, I truly don't understand how blocking the processes make them bounded. Would update this when I find this. Please write on comments if you know this.&lt;/p&gt;

&lt;h4&gt;
  
  
  Deadlocks
&lt;/h4&gt;

&lt;p&gt;Perfect Example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm4gjseg5l6sm50pb190j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm4gjseg5l6sm50pb190j.png" alt="alt text" width="450" height="435"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Okay, Serious example:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frd6i77akbida8dmqj79l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frd6i77akbida8dmqj79l.png" alt="alt text" width="521" height="380"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn5kflb4dv5c2koi41uk2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn5kflb4dv5c2koi41uk2.png" alt="alt text" width="252" height="159"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqnvv0uasstduy2zueqo2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqnvv0uasstduy2zueqo2.png" alt="alt text" width="380" height="214"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffrkirfhdunkx3lmxuc5e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffrkirfhdunkx3lmxuc5e.png" alt="alt text" width="800" height="613"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpags6m4fmnsfbphg3w2i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpags6m4fmnsfbphg3w2i.png" alt="alt text" width="366" height="475"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxhlijgfy0lo2kf3stuj7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxhlijgfy0lo2kf3stuj7.png" alt="alt text" width="356" height="476"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F44evkkqid3k1u2o6r8p5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F44evkkqid3k1u2o6r8p5.png" alt="alt text" width="790" height="589"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Threads
&lt;/h4&gt;

&lt;p&gt;To be updated&lt;/p&gt;

&lt;h4&gt;
  
  
  Memory Management
&lt;/h4&gt;

&lt;p&gt;To be updated&lt;/p&gt;

</description>
      <category>operatingsystem</category>
    </item>
    <item>
      <title>Bitsets, Bit Manipulations and Bitmasks Problems</title>
      <dc:creator>Abhinandan Sharma</dc:creator>
      <pubDate>Fri, 06 Aug 2021 10:15:20 +0000</pubDate>
      <link>https://dev.to/abhi824/bitsets-bit-manipulations-and-bitmasks-questions-p2g</link>
      <guid>https://dev.to/abhi824/bitsets-bit-manipulations-and-bitmasks-questions-p2g</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;If you have come to this post, I bet you are struggling with all those bit operations and tricks as there are two many of them! These bit operations are not only useful in competitive programming questions but also in Dynamic Programming (where we have to save the current state), and reducing time complexities in certain scenarios. &lt;/p&gt;

&lt;p&gt;Before heading to discuss the questions let's just get a glimpse of why you should learn bitsets and type of questions which you can't do if you don't have enough knowledge of bit manipulation.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Maximum AND/OR/XOR value of a pair in an array&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Queries for bitwise AND of the range [L, R] of the given array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/" rel="noopener noreferrer"&gt;Find Longest substring containing vowels in even counts&lt;/a&gt;, &lt;a href="https://leetcode.com/problems/find-longest-awesome-substring/" rel="noopener noreferrer"&gt;Find Longest awesome substring&lt;/a&gt;, &lt;a href="https://leetcode.com/problems/number-of-wonderful-substrings/" rel="noopener noreferrer"&gt;Number of wonderful sub-strings&lt;/a&gt;, &lt;a href="https://leetcode.com/problems/maximum-product-of-word-lengths/" rel="noopener noreferrer"&gt;Maximum Product of Word Lengths&lt;/a&gt; These type of questions are typically solved using bitsets easily.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Bitmasks on trees/graphs and with Dynamic Programming problems and some binomials.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will be discussing each of the above questions and in the end, I would be sharing some of the questions from codeforces, Leetcode, etc. If you have any doubts in those questions, feel free to discuss in the comments.&lt;/p&gt;

&lt;h3&gt;
  
  
  First Type of Questions
&lt;/h3&gt;

&lt;p&gt;Questions asking you to compute the maximum AND/XOR/OR of any pair in an array, directly or indirectly, are actually based on a rather simple trick. Let's First discuss the questions.&lt;/p&gt;

&lt;h4&gt;
  
  
  Q1. Find Maximum Binary AND pair from an array.
&lt;/h4&gt;

&lt;p&gt;Codeforces Link of the problem:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Input: arr=[2,6,4,5,12,14,15]
Output: Max And pair: 14
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is rather a difficult problem to solve but this will let you think much. &lt;/p&gt;

&lt;p&gt;Hint 1: First convert all the numbers to their binary forms and see if you see a pattern in finding the answer&lt;/p&gt;

&lt;p&gt;Hint 2: The size of the numbers can be at most 32 bits. &lt;/p&gt;

&lt;p&gt;Solution: Read Hint 2 one more time. We know that total digits in binary representation can't be more than 32 for int datatype. Now, think this way: We have to see if a bit can be set or unset in our answer. That means we are actually constructing our answer bit by bit. &lt;/p&gt;

&lt;p&gt;We would do a simple iteration here starting from leftmost bit and then we would search for the elements in array having this bit as set (And also the all the bits in our current answer). If the number of such elements is greater than or equal to 2, we would add this bit in our answer. &lt;/p&gt;

&lt;p&gt;Dry Run:&lt;/p&gt;

&lt;p&gt;arr[]={2,6,4,5,12,14,15}&lt;/p&gt;

&lt;p&gt;Binary form of these numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0010
0110
0100
0101
1100
1110
1111
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now Our max answer can't be more than the maximum of these numbers(It's binary AND). So our max answer can be 15. We would start by setting the leftmost bit.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Initial Answer : 0000
First bit set: 1000 which is 8 in decimal. Fourth bit set in 12, 
15 and 14. (Greater than 2) So, we add this bit to our answer

Second Bit: 1100 which is 12 in decimal. The number of elements 
in which both first and second bit is set is 3(12,14 and 15). So,
we add this bit.

Third Bit: 1110 which is 14 in decimal. The number of elements in
which all of the set bits of 14 are present is 2(14 and 15). So,
we add this bit as well.

Fouth bit: 1111 which is 15 in decimal. the number of elements in
which all of the set bits of 15 are present is 1 only(15 
itself). So, we would not add this bit and reset our answer to 
1110.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Why does this work?&lt;/strong&gt;&lt;br&gt;
A very frequent doubt which comes in mind is, how this algorithm differentiates between two numbers added in the answer. Like, I am first considering 12, 14 in for the second bit but there can be some number which actually satisfies our conditions but 12 don't. So the set bits of 12 would be removed! This would cause "some error". First of all, see the conditions clearly, the condition to add a number is that it should have bits added so far, so 12 won't be contributing any unique bit...&lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include&amp;lt;bits/stdc++.h&amp;gt;
using namespace std;
#define int long long int
bool isValid(int x, vector&amp;lt;int&amp;gt; &amp;amp;arr, int n)
{
    int cnt = 0;
    for(int i = 0; i &amp;lt; n; i++)
    {
        // How do I check if all bits set in answer is set in the element as well?
        // Just do an AND operation!
        if((x &amp;amp; arr[i]) == x)
            cnt++;
    }
    return cnt &amp;gt;= 2;
}
int findMaxAndPair(vector&amp;lt;int&amp;gt; &amp;amp;arr, int n)
{
    int ans = 0;
    // Here I am starting from 63 as it is long long
    // You can actually compute the maximum number
    // and start from it's rightmost set bit
    for(int i = 31; i &amp;gt;= 0; i--)
    {
        // How do I set a specific bit? Just do an OR operation on shifted bit!
        if(isValid(ans | (1 &amp;lt;&amp;lt; i), arr, n))
        {
            ans = ans | (1 &amp;lt;&amp;lt; i);
        }
    }
    return ans;
}
int32_t main()
{
    int n;
    cin &amp;gt;&amp;gt; n;
    vector&amp;lt;int&amp;gt; arr (n);
    for(int i = 0; i &amp;lt; n; i++)
        cin &amp;gt;&amp;gt; arr[i];

    cout &amp;lt;&amp;lt; findMaxAndPair(arr, n);

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Second Type
&lt;/h3&gt;

&lt;p&gt;Querying inside a specific range. To be continued...&lt;/p&gt;

&lt;h3&gt;
  
  
  Third Type
&lt;/h3&gt;

&lt;p&gt;Using bitsets for storing information effectively.&lt;/p&gt;

&lt;p&gt;These problems may look sliding window technique problems at first! So be patient and see why we can't use sliding technique in such problems.&lt;/p&gt;

&lt;p&gt;See &lt;a href="https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/" rel="noopener noreferrer"&gt;this&lt;/a&gt; problem.&lt;br&gt;
We have to find the size of the largest substring containing vowels in even counts. &lt;/p&gt;

&lt;p&gt;So, how can it be solved using bitsets? Here we only have two options for any vowel, either it appears even number of times or odd number of times. So we can represent state of a vowel by a binary digit. And we have just 5 vowels, so the size of the bitset would not exceed 5. Now again stop reading and think!!!&lt;/p&gt;

&lt;p&gt;I' m assuming you have given at least 10-15 min( if you haven't solved the problem yet). Here are the observations you should have with you by now:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;If we store each bit in form of string or bitset(Yep, that's a STL container in C++), we want state of the string/bitset as 00000 where each 0 represents a vowel and off state(0) of this vowel represents that it occurred even number of times.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This observation is a bit trickier as it actually solves the problem. If we are at suppose ith character in string and bitset state till now is 01011, we need to have the exact bitset state at some other index to make the difference as 00000. For example, consider this string : eleetminicoworoep&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;At 1st iteration: Bitset: 10000
At 2nd iteration: Bitset: 10000
At 3rd iteration: Bitset: 00000( we reached perfect state here, 
so our current length would be i+1-0=3)
At 4th iteration: Bitset: 10000 ( Wait here! We have encountered 
the same state earlier as well, subtracting these two will make 
perfect state, i-prevIndex+1=2-0+1=3)
....

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;So, long story short, just store the bitsets in an array or something where you store the index they are first found. If the bitset is repeating, the length formed by this bitset would be i-previousIndex+1. Note that we set perfect state's index to be -1.&lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// You may see this also: https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1357104/solution-using-map-of-bitset-and-position-c

class Solution {
public:
    int findTheLongestSubstring(string s) {
        int cnt[32];
        memset(cnt,-1,sizeof cnt);
        int mask=0;
        // Pos map stores indices for flipping certain vowel bits
        map&amp;lt;char,int&amp;gt;pos;
        pos.insert({'a',0});
        pos.insert({'e',1});
        pos.insert({'i',2});
        pos.insert({'o',3});
        pos.insert({'u',4});
        int ans=0;
        for(int i=0;i&amp;lt;s.size();i++)
        {   
            // Our character should be a vowel
            if(pos.find(s[i])!=pos.end())
                mask^=(1&amp;lt;&amp;lt;pos[s[i]]);
            if(cnt[mask]!=-1||!mask)
            {
                ans=max(ans,i-cnt[mask]);
            }
            else{
                cnt[mask]=i;
            }
        }
        return ans;

    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Next Problem&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, let's do &lt;a href="https://leetcode.com/problems/number-of-wonderful-substrings" rel="noopener noreferrer"&gt;this&lt;/a&gt; one. Here we have to find the &lt;strong&gt;number&lt;/strong&gt; of wonderful substrings where wonderful string is a string in which at most one element appears odd number of times. &lt;/p&gt;

&lt;p&gt;First of all, let's discuss how it's different from previous problem? Here we have to find the &lt;strong&gt;number&lt;/strong&gt; instead of the length of the string and second, we have at most 10 characters in the string(which actually gives a hint to solve this problem using bitsets). &lt;/p&gt;

&lt;p&gt;We again start off by creating a 10 length bitset. 0 for even frequencies and 1 for odd frequencies. But here we don't have just one perfect bitset, instead we have these 10 perfect bitsets:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0000000001
0000000010
0000000100
0000001000
0000010000
0000100000
0001000000
0010000000
0100000000
1000000000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if we have some bitset, say 1011011001, we need the exact same bitset along with all the bitsets which when subtracted from current bitset, gives you one of the said 10 "perfect" bitsets. &lt;br&gt;
So, what we do is simple, for each ith character in string, calculate the bitset, and then iterate on the bitset itself and turn off one bit at a time and then search for the new bitset occurence in cnt array. If the occurence exists, you increase the answer by 1, else make a new entry in the cnt array. Also, here we do not store the indices in the cnt array, rather we store the number of occurences. &lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class Solution {
public:
    long long wonderfulSubstrings(string s) {
        long long cnt[1024]={1};
        long long  mask=0;
        long long  ans=0;
        for(int i=0;i&amp;lt;s.size();i++)
        {
            mask=mask^(1&amp;lt;&amp;lt;(s[i]-'a'));
            ans+=cnt[mask];
            for(int j=0;j&amp;lt;10;j++)
            {
                ans+=cnt[mask^(1&amp;lt;&amp;lt;j)];
            }
            cnt[mask]++;
        }
        return ans;

    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Type 4: Bitmasks with DP and Graphs, along with some binomial calculations.
&lt;/h3&gt;

&lt;p&gt;This is perhaps the coolest form of bitmasks. Here the intuition is all it takes. You just need to think if you need the exact previous state for current dp or not.&lt;/p&gt;

&lt;p&gt;Here are some good problems:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href="https://leetcode.com/problems/shortest-path-visiting-all-nodes/" rel="noopener noreferrer"&gt;Shortest Path Visiting All Nodes&lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is a combination of Bitmasks used along with BFS and DP. This is a hard problem to start off with but I chose this as it includes a simple bitmask. Also, if you have no clue to solve this problem in about 30 min, please just look at the solutions and hints as it is not a very simple problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint 1&lt;/strong&gt;: You need a BFS for sure, but if you keep track of visited nodes, you won't be able to visit that node again(See the example test case given in leetcode) So, you need to find a condition where you may get stuck in an infinite loop if you do not maintain a visited array. Also, as it can be from any node, you may try a multi-source BFS type of thing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint 2&lt;/strong&gt;: What will be unique for each path? Like in the below example, we have to go to 0 again from 1 but not again to 1 as it is already fully explored. When we should not visit a node? It's simple: when we have already explored all the nodes of the subgraph of that child and are entering again with the same child. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Okay, that's a heavy question. There are many ways to solve it, but let's first discuss the problems we have while doing a BFS:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;We can have our path started from any node.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We can visit a node multiple times.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We can have cycles, and we need to detect them without actually using the visited array.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Okay, we got our problems, let's start step by step to solve them.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Starting from any node&lt;/strong&gt;: It's simple to solve. What we do in a usual BFS? We push the source node first. But here as we can have many sources, we push all of them initially.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Visiting a node multiple times&lt;/strong&gt;: Here comes the most difficult part. Actually if we just remove the visited array from the standard BFS, it would do half the work. Now we can visit a node multiple times, but we still have to figure out some way to detect cycles.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Detecting cycles without having a visited node&lt;/strong&gt;: This was the crux of the problem. So, let's discuss this in detail. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example in the figure below, our queue looks like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0 1 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjxziv0hwd7nsswj2gewk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjxziv0hwd7nsswj2gewk.png" alt="graph" width="435" height="292"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But really, do we only have to store the nodes in the queue? How do we know that all nodes are now visited? Yeah, you guessed it right! We use bitmasks here! The first hint was actually in the constraints only. N can be upto 12 which is quite less. You can use a set here but that's a little slow than bitsets. &lt;/p&gt;

&lt;p&gt;So, we store the bitsets along with the current node in the queue. Also, we have to just return the longest path, so we need a variable to store that as well. You can use a pair of pair of bitsets and int and int, but I would prefer using a user-defined data structure to store it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct info{
    int bitmask;
    int cnode;
    int path;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our initial queue would look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{0001,0,1},{0010,1,1},{0100,2,1}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we have our visited nodes for each source, current nodes, and the length of the path as well. Now, we need to tackle the problem of cycles. &lt;/p&gt;

&lt;p&gt;If a cycle occurs, we are sure that the exact same path with same current node would have occurred before as well. That means, if we the same bitmask &lt;strong&gt;and&lt;/strong&gt; node are repeated again, there exists a cycle. In this example only, when we go from 0 to 1 and go back from 1 to 0, now we again can start with 1 but bitmask configuration looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0 : 0001 and 0(current node)
0-&amp;gt;1 : 0011 and 1(current node)
0-&amp;gt;1-&amp;gt;0: 0011 and 0(current node)
Now, if we go from 0 to 1 again
0-&amp;gt;1-&amp;gt;0-&amp;gt;1: 0011 and 1(current node) : This is the exact configuration before, which is obvious, as we are storing the visited nodes and current node and they can't be same.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, we will store these 2 in a set of pair of bitmask(in form of int) and current node.&lt;/p&gt;

&lt;p&gt;All in all, here is the brief: Just do a BFS with queue initially filled with every node and each queue element would store a user defined structure containing a bitmask, a current node, and length of the current path. We would be storing the bitmask and current nodes in a set of pair and skip the exact same configuration already in set. We will break when all nodes are visited at least once.&lt;/p&gt;

&lt;p&gt;Here is the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct info{
    int bitmask;
    int cnode;
    int path;
};
class Solution {
public:
    int shortestPathLength(vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt;&amp;amp; adj) {
        int n=adj.size();
        queue&amp;lt;info&amp;gt;q;
        set&amp;lt;pair&amp;lt;int,int&amp;gt;&amp;gt; vis;
        // initializing queue and vis set
        for(int i=0;i&amp;lt;n;i++)
        {
            info node;
            node.bitmask=1&amp;lt;&amp;lt;i;
            node.cnode=i;
            node.path=1;
            q.push(node);
            vis.insert({node.bitmask,node.cnode});
        }
        while(!q.empty())
        {
            info curr=q.front();
            q.pop();
            int cnode=curr.cnode;
            if(curr.bitmask==(1&amp;lt;&amp;lt;n)-1)
                return curr.path-1;
            for(auto it:adj[cnode])
            {
                int bitmask=curr.bitmask|(1&amp;lt;&amp;lt;it);
                pair&amp;lt;int,int&amp;gt; x={bitmask,it};
                if(vis.find(x)==vis.end())
                {
                    info node;
                    node.bitmask=bitmask;
                    node.cnode=it;
                    node.path=curr.path+1;
                    q.push(node);
                    vis.insert(x);
                }
            }
        }
        return -1;

    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, I think you might have had the feel of solving these type of problems. So here is a list of problems solvable by the above knowledge you had till now:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/find-longest-awesome-substring/" rel="noopener noreferrer"&gt;Find Longest Awesome Substring&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/contiguous-array/" rel="noopener noreferrer"&gt;Contiguos Array&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/binary-subarrays-with-sum/" rel="noopener noreferrer"&gt;Binary Subarrays with sum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/subarray-sums-divisible-by-k/" rel="noopener noreferrer"&gt;Subarray Sums Divisible by K&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/" rel="noopener noreferrer"&gt;Number of Sub-arrays With Odd Sum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/bitwise-and-of-numbers-range/" rel="noopener noreferrer"&gt;Bitwise AND of Numbers Range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/count-pairs-with-xor-in-a-range/" rel="noopener noreferrer"&gt;Count Pairs With XOR in a Range&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/" rel="noopener noreferrer"&gt;Count Subtrees With Max Distance Between Cities&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>algorithms</category>
      <category>bits</category>
      <category>cpp</category>
      <category>codeforces</category>
    </item>
  </channel>
</rss>
