Saturday, December 26, 2015

Digital Electronics Quick Notes:


Digital Counters are of 2 Types:


(i) Synchronous Counters:

    - A Clock is attached to all the FF’s
    - The input to the FF is a function of output(s) of other FF’s
    - D Type FF is used in Synchronous Counters
    - Its faster than Asynchronous Counters
    - Synchronous counters are also called Shift Counters.


    Types of Shift Counters (Synchronous Counters):

    (i) Ring Counter :
        - The output Q of the last FF is connect to the input of first FF.
        - Mod 2 counter have 2 FF’s , can count 2 states.
        - Mod 3 counter have 3 FF’s , can count 3 states.

        Counting States:
        ———————
        For ’N’ FF’s ,  counting states are ’N’
        Ex:  A ring counter with 4 FF’s can counter 4 states.

       

    (ii) Johnson Counter ( or Twisted Ring Counter ) :
        - The output Q” of the last FF is connected to the input of the first FF.
        - Mod 4 counter have 2 FF’s , can count 4 states.
        - Mod 6 counter have 3 FF’s , can count 6 states.

   
        Counting States:
        ———————
        For ’N’ FF’s ,  counting states are ’2N’
        Ex:  A Johnson counter with 3 FF’s can counter 6 states.



(ii)Asynchronous Counters:

    - Asynchronous counters are also called Ripple Counters.
    - A Clock is attached to the first FF.
    - The output of each FF is given as clock signal to the next FF.
    - T Type FF is used in Asynchronous Counters
    - Its slower than Synchronous Counters due to the propagation delay in the FF’s
    - It can be used as Up Counter or Down Counter.
    - Mod 8 counter have 3 FF’s , can count 8 states.


    Counting States:
    ———————
    For ’N’ FF’s ,  counting states are power(2,N)
    Ex:  An Asynchronous counter with 3 FF’s can counter 8 states.

Sunday, December 13, 2015

Compiler Design Quick Notes:



We have seen that a lexical analyser can identify tokens with the help of regular expressions and pattern rules. But a lexical analyser cannot check the syntax of a given sentence due to the limitations of the regular expressions. Regular expressions cannot check balancing tokens, such as parenthesis. Therefore, this phase uses context-free grammar (CFG), which is recognised by push-down automata.

CFG, on the other hand, is a superset of Regular Grammar, as depicted below:






It implies that every Regular Grammar is also context-free, but there exists some problems, which are beyond the scope of Regular Grammar. CFG is a helpful tool in describing the syntax of programming languages.
Context-Free Grammar

In this section, we will first see the definition of context-free grammar and introduce terminologies used in parsing technology.

A context-free grammar has four components:

    A set of non-terminals (V). Non-terminals are syntactic variables that denote sets of strings. The non-terminals define sets of strings that help define the language generated by the grammar.

    A set of tokens, known as terminal symbols (Σ). Terminals are the basic symbols from which strings are formed.

    A set of productions (P). The productions of a grammar specify the manner in which the terminals and non-terminals can be combined to form strings. Each production consists of a non-terminal called the left side of the production, an arrow, and a sequence of tokens and/or on- terminals, called the right side of the production.

    One of the non-terminals is designated as the start symbol (S); from where the production begins.

The strings are derived from the start symbol by repeatedly replacing a non-terminal (initially the start symbol) by the right side of a production, for that non-terminal.









Top Down Parsers:
===============


a) Recursive Descent Parser:
    - There is a recursive function for every Variable.
    - Terminals have a match function



b) LL(1) Parser:

    - Left Recursive grammars are not allowed
    - Ambiguous grammars are not allowed
    - Productions are atomic (i.e not more than one production is allowed in the table rows)
    - First and Follow techniques are used to place productions in the rows of the (Variables , Terminals) table.



Shift-Reduce Parsing
==================

Shift-reduce parsing uses two unique steps for bottom-up parsing. These steps are known as shift-step and reduce-step.

    Shift step: The shift step refers to the advancement of the input pointer to the next input symbol, which is called the shifted symbol. This symbol is pushed onto the stack. The shifted symbol is treated as a single node of the parse tree.

    Reduce step : When the parser finds a complete grammar rule (RHS) and replaces it to (LHS), it is known as reduce-step. This occurs when the top of the stack contains a handle. To reduce, a POP function is performed on the stack which pops off the handle and replaces it with LHS non-terminal symbol.





Bottom Up Parsers:
================

a) Operator Precedence Parser:

    - Can accept Ambiguous grammars
    - Productions have to be in the form of Operand-operator-Operand
    - Operation relations table and Operation function table are used for Operator precedence and associativity.
    - Operation relations table has space complexity of O(n^2)
    - Operation functions table has space complexity of O(2n)



b) SR Parsers: (Shift Reduce Parsers : Stack is used)

    - All the parsers differ only by their parsing table entries.
    - All the productions uses items i,e (.) in the beginning of the RHS productions.
        Ex. S —> .AA
    - All the parsers use Canonical Collection of LR(0) items (i.e S’ -> .S production)
    - Productions are grouped to represent “Shift” (Transition Production) and “Reduce” (Completed Productions) states.
    - SR (Shift/Reduce) and RR (Reduce/Reduce) issues may appear in Parsing table.



    Types of LR Parsers:

    LR(0) and SLR(1) rely on the canonical LR(0) items

    (i) LR(0) Parser :
            - The reduce step is present across all the entries in the table.

    (ii) SLR(1) Parser :
            - The reduce step is only present for the First of the Left hand side production entry.


    - LALR(1) and CLR(1) rely on the LR(1) item i.e LR(0) + Look head ($) symbols
    - Have more number of entries and statues than the LR(0) items due to the look ahead symbols.
    - Along with each production there is an Look ahead symbol associated, which is computed as First of items after . in each production for each step.
    - CLR(1) parsing table size can be reduced by merging the Shift steps (State numbers), which will make the look aheads irrelevant.  
    - CLR(1) parsing table can be converted to LALR(1) parsing table by joining the States thereby ignoring the look ahead symbols.


    (iii) LALR(1) Parser :
        - The states and look aheads in CLR(1) are merged .
        - May results in RR (reduce/reduce) conflict due to merging of look aheads.

    (iv) CLR(1) Parser :



    Notes:
    =====
    - Number of steps in CLR(1) >= Number of states in LR(0), SLR(1) & LALR(1) parsing table.
    i.e CLR(1)  >=  LR(0) = SLR(1) = LALR(1)  
  


=====================================================================


SDTs : Syntax Directed Translations are of 2 types

(i) S - Attributed SDT :

    - If an SDT uses only synthesised attributes, it is called as S-attributed SDT.
    - These attributes are evaluated using S-attributed SDTs that have their semantic actions     written after the production (right hand side).









(ii) L - Attributed SDT :

    - This form of SDT uses both synthesised and inherited attributes with restriction of not taking values from right siblings.
    - In L-attributed SDTs, a non-terminal can get values from its parent, child, and sibling nodes.
  
    As in the following production
    S → ABC
    S can take values from A, B, and C (synthesised). A can take values from S only. B can take     values from S and A. C can get values from S, A, and B. No non-terminal can get values     from the sibling to its right.



Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.






We may conclude that if a definition is S-attributed, then it is also L-attributed as L-attributed definition encloses S-attributed definitions.




  - SDTs are used for evaluating an arithmetic expression based on arithmetic precedence and associativity.
   - SDTs are also used for infix to postfix translations
Ex. A+B —> AB+

   
=====================================================================









Sunday, December 6, 2015

For NEW students joining IISc


Joining IISc

Bring
  • at least 6 passport size photos and 6 stamp size photos.
  • Original mark sheets and at least two copies of each sheet.
  • Offer letter, fees paid, train tickets for attending interview and joining
  • PAN card and its photocopy for a bank account. For student accounts, there is no need for a PAN card, but if you want a regular account, you need a pan card.
It might be a good idea to arrive a day or two before the reporting date and avail the hostel accommodation (does not apply to UG admissions).
 
Getting to IISc


IISc is 6 km away from the main railway station and bus stand (commonly called Majestic, though the official name is Kempe Gowda Bus stand) and 38 km from the airport. Autos cost Rs 13 per km while taxis cost Rs 18 per km. Prepaid taxis from the railway station and airport cost Rs 300 and Rs 750, respectively. If you are coming for the first time to Bangalore by train or bus, you can take a prepaid auto for Rs. 90 and come to IISc. If you do not have any luggage, you can take a local bus from Majestic (use the overbridge/subway) to cross to the local bus stand. Go to platform 23/24/25 and take any of the 252, 271 series buses. The frequency of the buses is one per two min during peak hours, one per five min during non-peak hours and one per ten min during odd hours (11 pm - 5 am). Ask for Tata Institute (that's what IISc. is commonly known as); that'll get you to 18th cross, Malleswaram or the Yeshwantpur bus stand.

Remember always to ask for Tata Institute, whether it is a bus, auto or taxi. People usually land up at IIM if they ask for IISc.

If you are coming on July 27/28/29/30, then the student council of IISc will pick you up from the Bangalore city station and Yeshwanthpur station. Buses with IISc banners will be there in the parking lot. The main Majestic bus stand is adjacent to the Bangalore city station.

If you are coming from the airport, you can take the Vajra Vayu service (a/c buses) and ask for Mekhri Circle. There are buses almost every 15 minutes from the airport. They will charge you Rs. 150 per person. Get down in Mekhri Circle and ask for Tata Institute. It is 2-3 km and you can take an auto.
First day at IISc

On the date of reporting, go to the faculty hall in the main building. Tokens will be issued as soon as you come and there will be a long queue. You will be called based on this admission number and then your marks sheets, GATE score card etc will be verified. Your photo will be taken and you will be issued an identity card. A 16 digit student registration number (SRN) will be alloted to you. Your first job in IISc is to memorize this number because you will require it everywhere. Please take your photographs with you and you may have to stick it in many places.

Next, visit the hostel office. Pay the hostel fees and show the proof of hostel fees paid and ask for a room allotment. There is a lucky dip and you will be allotted a room. You will be given a room allotment letter, which will serve as your proof of residence.

If you are aware of who will be your research supervisor, be sure to visit his/her office and say hello. Then visit your department office and get all the course registration forms. Each department will hold an orientation program and make sure you get those dates and times.

Next, visit either SBI or Canara Bank and get a new account.

Purchase a SIM card. The BSNL office is near the main building. Private vendors also sell different private phone operators near the hostel office. Many will not sell postpaid options.

Purchase mattresses, pillows etc from the vendors near the hostel office. These vendors are available only during this period. Many other small items like buckets, hangers etc. can be purchased in the stores on IISc campus.

Campus
IISc is a huge residential colony and has all facilities within the campus obviating a need to leave the campus for anything. Take a look at the campus map. 
Here are some places on the campus that you might wish to visit during the next few days. There's the Main Library, the Campus Bookstore (near the Cafe, open noon to 7 pm, except Sundays), the Xerox centres (in the library, near the Cafe and near TMC, open 8:30 am to 8:30 pm), two banks (Canara bank and SBI on your map), and a Health Centre (marked Hospital on your map). For outgoing phones, you may go to the STD/ISD booth west of Canara bank, or to the Telecom Centre (7 am to 10 pm, except Sundays).  The Post office (open 9-5 Mon-Sat) is approached from Prof. CNR Rao circle. It handles registered, speed post, money order etc. in addition to regular mail. The Janatha bazaar (called the Cosmetic Center on your map) is open Mon-Sat and houses a small shop (7-1l am, 5-8 pm), a tailor (10 am-6 pm), a launderer (10 am-8 pm), a cobbler (8 am-8 pm), and a men's hairdresser (7 am-noon, 4-7:30 pm). The launderer, cobbler and hairdresser are also available Sunday mornings. Effective June, 2007, a cycle shop has been opened here. There is a watch repair shop in E-Block (between 4-6 pm on all days except Sunday) and a cycle repair shop near U-Block. There is also a small shopping area at the north end of campus, which has a tailor, travel agent and bookbinder. On the south side of the highway is the Gymkhana. Please do NOT cross the road but use the yellow over-bridge to cross the highway. Inside is a large hall for badminton, table tennis, and movies. In addition there is a carrom room and a TV room; upstairs is a small Library and a music room. Outside is a large playground, a running track and the Students Auditorium. At the Gymkhana, you can obtain permission to use the swimming pool located at the other end of campus (near the guest house). 

Prakurthi (marked Cafe on your map) offers chats, various kinds of food, snacks and coffee/tea from 7:30 am to 3 am  on all days.  Kabini (marked TMC on your map) offers snacks, tea and coffee from 7 am to 6 pm on all days. A good restaurant near Kabini called Nesara is open from 8 am to 11 pm and is slightly more expensive than other eating places on campus but it may be worth it. There is Snacks shop in side of CEDT (opens on week days between 10:45 & 11:30 AM and 3 & 3:45 PM). The small shopping area at the far north end of the campus near the ECE department has a bakery and a fruit/vegetable shop. In addition, vendors seated on the road near TMC, SBI and NCSI offer fresh fruit, groundnuts, etc. in the daytime (but not on Sundays). 



You can learn more about the campus.
Accommodation nearby
If you are coming with your parents, your parents may need to stay in a hotel. A few hotels are listed below

Akshara Regency
No4/20, Mathekere First Main Road, Gokula First stage
Bangalore.
Phone 080 2337 7746, 09036970369
Rate ~ 550-950 Rs for 2 persons


Ujwal Residency
#50, Yeswathpur-Mathikere Main Road
Bangalore
Phone 080 40974573, 09986131989
Rate - 750-1000 Rs for 2 persons

Sree Nandanam Residency
#11 Gokul First Stage
Mathikere Main Road
Bangalore
Phone : 080 40926908, 40926909
Rate: 550-1000 Rs for two persons

Sri Akshaya Deluxe Lodges
#4 Mathikere Main Road
Bangalore
Phone 080 2347 0128, 09731925513
Rate Rs 500- 800 for two persons

Krishinton Suites
# 993, M.S. Ramaiah Main Road, Near IISc
D-Gate, Mathikere, Bangalore - 560 054,
+91 80 4259 5959
Rate 1200-2000 for 2 persons

The Basil
8, Sampige Road, Malleshwaram, Bangalore - 560 003
080- 40402323
Rate 2000 for 2 persons

New Sagar Comforts & Banquets
No.5 & 6-8, 11th Mn Rd, 2nd Phs, 1st STG,
Yeshwanthpur Mn Rd, Gokula Extension, Bangalore - 560054
+(91)-(80)-40084999, 41273453
Rate 400-800

Disclaimer: The above is based on my experience and is personal advice. It does not represent IISc's opinion or represent any commercial interest.

Friday, December 4, 2015

DataStructures Quick Notes:


Complete Binary Tree:
==================

Total number of Nodes :
2pow(n+1)-1


Internal Nodes:
1 to [n/2]


Leaf nodes:
[n/2]+1 to n


Max no. of nodes at a level or height:
n/[2pow(h+1)]


====================================================


How many distinct binary search trees can be created out of 4 distinct keys?
Ans:
No. of BST= 2nCn/(n+1)
Therefore 8C4/5 =14

=======================================================

A binary tree T has 20 leaves. The number of nodes in T having two children is ______.

Ans:
In Binary tree If there are N leaf nodes then the number of Nodes having two children will be N-1. So in this case answer will be 20-1, means 19.

=======================================================

*** A complete graph Kn has  power(n, n-2) spanning trees.

=======================================================


Simple Graph
A graph with no loops and no parallel edges is called a simple graph.
* The maximum number of edges possible in a single graph with ‘n’ vertices is nC2 where nC2 = n(n – 1)/2.

* The number of simple graphs possible with ‘n’ vertices = 2nc2 = 2n(n-1)/2.




The maximum number of edges with n=3 vertices −
nC2 = n(n–1)/2
   = 3(3–1)/2
   = 6/2
   = 3 edges

The maximum number of simple graphs with n=3 vertices −
2nC2 = 2n(n-1)/2
   = 23(3-1)/2
   = 23
   = 8


=======================================================

Example 1:
Let ‘G’ be a simple graph with nine vertices and twelve edges, find the number of edges in 'G-'.

You have, |E(G)| + |E('G-')| = |E(Kn)|

12 + |E('G-')| =  9(9-1) / 2 = 9C2
12 + |E('G-')| = 36

|E('G-')| = 24


=======================================================

Example 2:
‘G’ is a simple graph with 40 edges and its complement 'G−' has 38 edges. Find the number of vertices in the graph G or 'G−'.

Let the number of vertices in the graph be ‘n’.

We have, |E(G)| + |E('G-')| = |E(Kn)|

40 + 38 = n(n-1)/2

156 = n(n-1)

13(12) = n(n-1)

n = 13

=======================================================


Circuit Rank
Let ‘G’ be a connected graph with ‘n’ vertices and ‘m’ edges. A spanning tree ‘T’ of G contains (n-1) edges.
Therefore, the number of edges you need to delete from ‘G’ in order to get a spanning tree = m-(n-1), which is called the circuit rank of G.


Example 1:

For the graph given in the above example, you have m=7 edges and n=5 vertices.

Then the circuit rank is

G = m – (n – 1)
  = 7 – (5 – 1)
  = 3

=======================================================


Example 2:

Let ‘G’ be a connected graph with six vertices and the degree of each vertex is three. Find the circuit rank of ‘G’.

By the sum of degree of vertices theorem,

n

i=1 deg(Vi) = 2|E|

6 × 3 = 2|E|

|E| = 9

Circuit rank = |E| – (|V| – 1)

= 9 – (6 – 1) = 4

=======================================================


Euler’s Path
An Euler’s path contains each edge of ‘G’ exactly once and each vertex of ‘G’ at least once. A connected graph G is said to be traversable if it contains an Euler’s path.
Example

Euler’s Path = d-c-a-b-d-e.


=======================================================


Example 3:

Let ‘G’ be a connected planar graph with 20 vertices and the degree of each vertex is 3. Find the number of regions in the graph.

Solution:

By the sum of degrees theorem,

20

i=1 deg(Vi) = 2|E|

20(3) = 2|E|

|E| = 30


By Euler’s formula,

|V| + |R| = |E| + 2

20+ |R| = 30 + 2

|R| = 12

Hence, the number of regions is 12.

=======================================================

A self-complementary graph is a graph which is isomorphic to its graph complement.

All self-complementary graphs have graph diameter 2 or 3
A disconnected graph has infinite diameter


By definition, a self-complementary graph must have exactly half the total possible number of edges, i.e., n(n-1)/4 edges for a self-complementary graph on n vertices. Since n(n-1) must be divisible by 4, it follows that n=0 or 1 (mod 4).


=======================================================


Red-Black Tree

An extended rooted binary tree satisfying the following conditions:
1. Every node has two children, each colored either red or black.
2. Every tree leaf node is colored black.
3. Every red node has both of its children colored black.
4. Every path from the root to a tree leaf contains the same number (the "black-height") of black nodes.

=======================================================


Sunday, November 29, 2015

Code Snippets


#include <stdio.h>
#include <math.h>

int main(){

  printf("\n");
 
  if(0) {
 
  //Divide by 2
          int i = 1024;
          while(i>0){
                  printf("%d,", i);
                i >>= 1;
          }
          printf("\b ");   

  } else {
 
    //Multiply by 2
          int j = 0;
          for(j=0; j < 10; j++){
              //printf("%d,", (int)pow(2, j));
             
              printf("%d,", 1 << j);

          }
          printf("\b ");   
  }
  printf("\n\n");

  return 0;
}

Monday, November 23, 2015

Properties of Complete Binary Tree


Total number of Nodes :
2pow(n+1)-1

Internal Nodes:
1 to [n/2]

Leaf nodes:
[n/2]+1 to n

Max no. of nodes at a level or height:
n/[2pow(h+1)]

 

Saturday, November 21, 2015

GATE Reference Books


Programming in C : Dennis ritche, Schaum’s series, pointers in c by Yashwant kanetkar



Data structures and Algorithms:

   1. Data structure: A. S. Tanenbaum, J.D. Ullman
   2. Algorithm analysis and design: T.h.cormen, Anne levitin



Theory of computation: Peter linz, Ullman



Compiler design: Principles of Compiler Design: Jeffrey D. Ullman, Alfred V. Aho



Operating system:

    1. Operating system: W. stallings, Galvin
    2. Operating Systems – Silberschatz



DIGITAL LOGIC: 1. Digital Design – Morris Mano     2. Malvino, Leach



Computer organization and architecture:

   1. Computer Architecture and Organisation – J.P. Hayes
   2. Computer System Architecture- Morris Mano
   3. Computer organization and architecture-William Stallings

 GATE BOOK References:

=====================



Databases:

   1. H.H. Korth, Navathe, Raghu Ramakrishnan and Johannes Gehrke



Computer networks:

   1. A. S. Tanenbaum, W.Stallings
   2. Forouzan



Information systems and software engineering:  1. Software Engineering – Pressman



Discrete Mathematics: Kenneth Rosen, Coleman , C.L. Liu



Graph theory: Nar Singh Deo



Numerical Methods: V. Rajaraman



Engineering Mathematics : By Eii Publication

General Aptitude : By Eii Publication



=====================================================

http://computernetworks5e.org/cover02.html

http://gatecse.in/wiki/Best_books_for_CSE

https://robot.bolink.org/ebooks/



How to get 1st Rank in GATE ?

Subjects Priority:
----------------------

Algorithm
Data Structures
Programming in C


Theory of Computing
Compiler Design 
Digital Electronics


Computer Networking
Operating Systems
DBMS

Computer Organisation

Maths
Aptitude

Algorithms Quick Notes


Greedy Algorithm to find Minimum number of Coins

Given a value V, if we want to make change for V Rs, and we have infinite supply of each of the denominations in Indian currency, i.e., we have infinite supply of { 1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, what is the minimum number of coins and/or notes needed to make the change?

Examples:

Input: V = 70
Output: 2
We need a 50 Rs note and a 20 Rs note.

Input: V = 121
Output: 3
We need a 100 Rs note, a 20 Rs note and a
1 Rs coin.
We strongly recommend you to minimize your browser and try this yourself first.
The idea is simple Greedy Algorithm. Start from largest possible denomination and keep adding denominations while remaining value is greater than 0. Below is complete algorithm.

1) Initialize result as empty.
2) find the largest denomination that is
   smaller than V.
3) Add found denomination to result. Subtract
   value of found denomination from V.
4) If V becomes 0, then print result. 
   Else repeat steps 2 and 3 for new value of V
Below is C++ implementation of above algorithm.

// C++ program to find minimum number of denominations
#include <bits/stdc++.h>
using namespace std;

// All denominations of Indian Currency
int deno[] = {1, 2, 5, 10, 20, 50, 100, 500, 1000};
int n = sizeof(deno)/sizeof(deno[0]);

// Driver program
void findMin(int V)
{
    // Initialize result
    vector<int> ans;

    // Traverse through all denomination
    for (int i=n-1; i>=0; i--)
    {
        // Find denominations
        while (V >= deno[i])
        {
           V -= deno[i];
           ans.push_back(deno[i]);
        }
    }

    // Print result
    for (int i = 0; i < ans.size(); i++)
           cout << ans[i] << "  ";
}

// Driver program
int main()
{
   int n = 93;
   cout << "Following is minimal number of change for " << n << " is ";
   findMin(n);
   return 0;
}
Output:

Following is minimal number of change for 93 is 50  20  20  2  1
Note that above approach may not work for all denominations. For example, it doesn’t work for denominations  {9, 6, 5, 1} and V = 11. The above approach would print 9, 1 and 1. But we can use 2 denominations 5 and 6.
For general input, we use below dynamic programming approach.

Find minimum number of coins that make a given value

Thanks to Utkarsh for providing above solution here.


===========================================================================


Find the largest three elements in an array

Given an array with all distinct elements, find the largest three elements. Expected time complexity is O(n) and extra space is O(1).

Examples:

Input: arr[] = {10, 4, 3, 50, 23, 90}
Output: 90, 50, 23
Source: http://qa.geeksforgeeks.org/1019/array-number-elements-given-largest-numbers-array-sorting

We strongly recommend you to minimize your browser and try this yourself first.
Below is algorithm:

1) Initialize the largest three elements as minus infinite.
    first = second = third = -∞

2) Iterate through all elements of array.
   a) Let current array element be x.
   b) If (x > first)
      {
          // This order of assignment is important
          third = second
          second = first
          first = x  
       }
   c)  Else if (x > second)
      {
          third = second
          second = x
      }
   d)  Else if (x > third)
      {
          third = x 
      }

3) Print first, second and third.
Below is C implementation of above algorithm.

#include <stdio.h>
#include <limits.h> /* For INT_MIN */
 
/* Function to print three largest elements */
void print2largest(int arr[], int arr_size)
{
    int i, first, second, third;
 
    /* There should be atleast two elements */
    if (arr_size < 3)
    {
        printf(" Invalid Input ");
        return;
    }
 
    third = first = second = INT_MIN;
    for (i = 0; i < arr_size ; i ++)
    {
        /* If current element is smaller than first*/
        if (arr[i] > first)
        {
            third = second;
            second = first;
            first = arr[i];
        }
 
        /* If arr[i] is in between first and second then update second  */
        else if (arr[i] > second)
        {
            third = second;
            second = arr[i];
        }
 
        else if (arr[i] > third)
            third = arr[i];
    }
 
    printf("Three largest elements are %d %d %d\n", first, second, third);
}
 
 
/* Driver program to test above function */
int main()
{
    int arr[] = {12, 13, 1, 10, 34, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
    print2largest(arr, n);
    return 0;
}
Output:

Three largest elements are 34 13 12
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

==============================================================================

Find if a point lies inside a Circle

Given a circle (coordinates of centre and radius) and a point (coordinate), find if the point lies inside or on the circle, or not.

Examples:

Input: x = 4, y = 4 // Given Point
       circle_x = 1, circle_y = 1, rad = 6; // Circle
Output: Inside

Input: x = 3, y = 3 // Given Point
       circle_x = 0, circle_y = 1, rad = 2; // Circle
Output: Outside
We strongly recommend you to minimize your browser and try this yourself first.
The idea is compute distance of point from center. If distance is less than or equal to radius. the point is inside, else outside.

Below is C++ implementation of above idea.

// C++ program to check if a point lies inside a circle or not
#include<iostream>
using namespace std;

bool isInside(int circle_x, int circle_y, int rad, int x, int y)
{
    // Compare radius of circle with distance of its center from
    // given point
    if ((x - circle_x)*(x - circle_x) +
        (y - circle_y)*(y - circle_y) <= rad*rad)
        return true;
    else
        return false;
}

// Driver function
int main()
{
   int x = 1, y = 1;
   int circle_x = 0, circle_y = 1, rad = 2;
   isInside(circle_x, circle_y, rad, x, y)?
                      cout << "Inside": cout << "Outside";
}
Outside:

Inside
Thanks to Utkarsh Trivedi for suggesting above solution

================================================================================

Check if a sorted array can be divided in pairs whose sum is k

Given a sorted array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair k.

Expected time complexity O(n) and extra space O(1). This problem is a variation of below problem, but has a different interesting solution that requires only O(1) space.

Check if an array can be divided into pairs whose sum is divisible by k

Examples:

Input: arr[] = {1, 3, 3, 5}, k = 6
Output: True
We can divide array into (1, 5) and (3, 3).
Sum of both of these pairs is 6.

Input: arr[] = {2, 5, 5, 5, 5, 8}, k = 10
Output: True
We can divide array into (2, 8), (5, 5) and
(5, 5). Sum of all these pairs is 10.
We strongly recommend you to minimize your browser and try this yourself first.

A Simple Solution is to iterate through every element arr[i]. Find if there is another not yet visited element with value (k – arr[i]). If there is no such element, return false. If a pair is found, then mark both elements as visited. Time complexity of this solution is O(n2 and it requires O(n) extra space.

A Better Solution is to use Hashing. Solution given on this post can be easily modified to work. Time complexity of this solution is O9n) but it requires extra space for hash table.

An Efficient Solution is to use Meet in the Middle algorithm discussed in method 1 here.

1) Initialize two index variables
  (a) Initialize first to the leftmost index: l = 0
  (b) Initialize second  the rightmost index:  r = n-1
2) Loop while l < r.
  (a) If (A[l] + A[r] != k)  then return false
  (b) Else r--, l++
Below is C++ implementation of above algorithm.

// A C++ program to check if arr[0..n-1] can be divided
// in pairs such that every pair has sum k.
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if arr[0..n-1] can be divided into pairs
// with sum equal to k.
bool canPairsSorted(int arr[], int n, int k)
{
   // An odd length array cannot be divided into pairs
   if (n & 1)
       return false; 

   // Traverse from both sides of array
   int l = 0, r = n-1;
   while (l < r)
   {
       // If array can be divided, then sum of current
       // elements must be sum
       if (arr[l] + arr[r] != k)
          return false;

       // Move index variables
       l++; r--;
   }

   return true;
}

/* Driver program to test above function */
int main()
{
    int arr[] = {1, 2, 3, 3, 3, 3, 4, 5};
    int n = 6;
    int n = sizeof(arr)/sizeof(arr[0]);
    canPairs(arr, n, k)? cout << "True": cout << "False";
    return 0;
}
Output:

 True
Time Complexity: O(n)
Auxiliary Space: O(1)

This article is contributed by Priyanka.

==================================================================================

Remove recurring digits in a given number

Given a number as string, remove recurring digits from the given string. The changes must be made in-place. Expected time complexity O(n) and auxiliary space O(1).

Examples:

Input:  num[] = "1299888833"
Output: num[] = "12983"

Input:  num[] = "1299888833222"
Output: num[] = "129832"
We strongly recommend you to minimize your browser and try this yourself first

This problem is similar to Run Length Encoding.

Let num[] be input number represented as character array

1) Initialize index of modified string 'j' as 0.
2) Traverse input string and do following for every digit num[i].
   a) Copy current character 'num[i]' to 'num[j]' and increment i & j.
   b) Keep incrementing i while num[i] is same as previous digit.
3) Add string termination character at 'num[j]'
Below is C++ implementation of above algorithm.

// C++ program to remove recurring digits from
// a given number
#include <bits/stdc++.h>
using namespace std;

/* Removes recurring digits in num[]  */
void removeRecurringDigits(char num[])
{
    int len = strlen(num);

    int j = 0; // Index in modified string

    /* Traverse digits of given number one by one */
    for (int i=0; i<len; i++)
    {
        /* Copy the first occurrence of new digit */
        num[j++] = num[i];

        /* Remove repeating occurrences of digit */
        while (i + 1 < len && num[i] == num[i+1])
            i++;
    }

    /* terminate the modified string */
    num[j] = '\0';
}

/* Driver program to test above function */
int main()
{
    char num[] = "1299888833";
    removeRecurringDigits(num);
    cout << "Modified number is " << num;
    return 0;
}
Output:

Modified number is 12983
This article is contributed by Priyanka.

==================================================================================


Add two numbers using ++ and/or —

Given two numbers, return sum of them without using operators + and/or -, and using ++ and/or –.

Examples:

Input: x = 10, y = 5
Output: 15

Input: x = 10, y = -5
Output: 10
We strongly recommend you to minimize your browser and try this yourself first
The idea is to do y times x++, if y is positive and do y times x– if y is negative.

// C++ program to add two numbers using ++
#include<bits/stdc++.h>
using namespace std;
 
// Returns value of x+y without using +
int add(int x, int y)
{  
    // If y is positive, y times add 1 to x
    while (y > 0 && y--)
         x++;
  
    // If y is negative, y times subtract 1 from x
    while (y < 0 && y++)
         x--;

    return x;
}
 
int main()
{
    cout << add(43, 23) << endl;
    cout << add(43, -23) << endl;
    return 0;
}
Output:

76
20
Thanks to Gaurav Ahirwar and human for suggesting above solution here.

============================================================================

Check if two numbers are equal without using arithmetic and comparison operators

Following are not allowed to use
1) Arithmetic and Comparison Operators
2) String functions

We strongly recommend you to minimize your browser and try this yourself first

The ide is to use XOR operator. XOR of two numbers is 0 if the numbers are same, otherwise non-zero.

#include <iostream>
using namespace std;

void areSame(int a, int b)
{
   if (a^b) cout << "Not Same";
   else cout << "Same";
}

int main()
{
   areSame(10, 20);
}
Output:

Not Same

==========================================================================

Program to check if a given number is Lucky (all digits are different)           

A number is lucky if all digits of the number are different. How to check if a given number is lucky or not.


Examples:

Input: n = 983
Output: true
All digits are different

Input: n = 9838
Output: false
8 appears twice

We strongly recommend you to minimize your browser and try this yourself first.


The idea is to traverse through every digit of given number and mark
the traversed digit as visited.  Since total number of digits is 10, we
need a boolean array of size only 10 to mark visited digits.


Below is C++ implementation of above idea.


// C++ program to check if a given number is lucky
#include<iostream>
using namespace std;

// This function returns true if n is lucky
bool isLucky(int n)
{
    // Create an array of size 10 and initialize all
    // elements as false. This array is used to check
    // if a digit is already seen or not.
    bool arr[10];
    for (int i=0; i<10; i++)
        arr[i] = false;

    // Traverse through all digits of given number
    while (n > 0)
    {
        // Find the last digit
        int digit = n%10;

        // If digit is already seen, return false
        if (arr[digit])
           return false;

        // Mark this digit as seen
        arr[digit] = true;

        // REmove the last digit from number
        n = n/10;
    }
    return true;
}

// Driver program to test above function.
int main()
{
    int arr[] = {1291, 897, 4566, 1232, 80, 700};
    int n = sizeof(arr)/sizeof(arr[0]);

    for (int i=0; i<n; i++)
        isLucky(arr[i])? cout << arr[i] << " is Lucky \n":
                         cout << arr[i] << " is not Lucky \n";
    return 0;
}

Output:

1291 is not Lucky
897 is Lucky
4566 is not Lucky
1232 is not Lucky
80 is Lucky
700 is not Lucky

Time Complexity: O(d) where d is number of digits in input number.

Auxiliary Space: O(1)


This article is contributed by Himanshu.

============================================================================


Program to check if a given number is prime or not

Solution 1:

============



int result = -1;



for(i = 2; i < n-1; i++)

{

    if(n/i){

        result = 1;

        break;

    }

}

if(result == 1) { printf(“Number is prime”);

else { printf(“Number is not prime”}







Solution 2:

===========

int result = -1;

for(i = 2; i < sqrt(n); i++)

{

    if(n/i){

        result = 1;

        break;

    }

}

if(result == 1) { printf(“Number is prime”);

else { printf(“Number is not prime”}



============================================================================

Program for prime factorisation of a number


PrimeFactorisation(n) {

    for(int i=2; i <= sqrt(n) ; i++) {
       
        if( n%i == 0) {

            int count = 0;
            while( n%i == 0) {
                n = n/i;
                count++;
            }
       
            printf(“ i : %d, count : %d”, i , count);
        }
    }
}

==============================================================================

Calculate GCD using Euclid's Algorithm:

int euclid_gcd(int a, int b) {



    int dividend = (a >= b) ? a : b;

    int divisor = (a <= b ) ? a : b;

    while (divisor != 0){   

        int remainder = dividend % divisor;

        dividend = divisor;

        divisor = remainder;

    }

    return dividend;

}



====================================================


How many distinct binary search trees can be created out of 4 distinct keys?
Ans:
No. of BST= 2nCn/(n+1)
Therefore 8C4/5 =14

=======================================================

A binary tree T has 20 leaves. The number of nodes in T having two children is ______.

Ans:
In Binary tree If there are N leaf nodes then the number of Nodes having two children will be N-1. So in this case answer will be 20-1, means 19.

=======================================================

*** A complete graph Kn has  power(n, n-2) spanning trees.

=======================================================


Simple Graph
A graph with no loops and no parallel edges is called a simple graph.
* The maximum number of edges possible in a single graph with ‘n’ vertices is nC2 where nC2 = n(n – 1)/2.

* The number of simple graphs possible with ‘n’ vertices = 2nc2 = 2n(n-1)/2.




The maximum number of edges with n=3 vertices −
nC2 = n(n–1)/2
   = 3(3–1)/2
   = 6/2
   = 3 edges

The maximum number of simple graphs with n=3 vertices −
2nC2 = 2n(n-1)/2
   = 23(3-1)/2
   = 23
   = 8


=======================================================

Example 1:
Let ‘G’ be a simple graph with nine vertices and twelve edges, find the number of edges in 'G-'.

You have, |E(G)| + |E('G-')| = |E(Kn)|

12 + |E('G-')| =  9(9-1) / 2 = 9C2
12 + |E('G-')| = 36

|E('G-')| = 24


=======================================================

Example 2:
‘G’ is a simple graph with 40 edges and its complement 'G−' has 38 edges. Find the number of vertices in the graph G or 'G−'.

Let the number of vertices in the graph be ‘n’.

We have, |E(G)| + |E('G-')| = |E(Kn)|

40 + 38 = n(n-1)/2

156 = n(n-1)

13(12) = n(n-1)

n = 13

=======================================================


Circuit Rank
Let ‘G’ be a connected graph with ‘n’ vertices and ‘m’ edges. A spanning tree ‘T’ of G contains (n-1) edges.
Therefore, the number of edges you need to delete from ‘G’ in order to get a spanning tree = m-(n-1), which is called the circuit rank of G.


Example 1:

For the graph given in the above example, you have m=7 edges and n=5 vertices.

Then the circuit rank is

G = m – (n – 1)
  = 7 – (5 – 1)
  = 3

=======================================================


Example 2:

Let ‘G’ be a connected graph with six vertices and the degree of each vertex is three. Find the circuit rank of ‘G’.

By the sum of degree of vertices theorem,

n

i=1 deg(Vi) = 2|E|

6 × 3 = 2|E|

|E| = 9

Circuit rank = |E| – (|V| – 1)

= 9 – (6 – 1) = 4

=======================================================


Euler’s Path
An Euler’s path contains each edge of ‘G’ exactly once and each vertex of ‘G’ at least once. A connected graph G is said to be traversable if it contains an Euler’s path.
Example

Euler’s Path = d-c-a-b-d-e.


=======================================================


Example 3:

Let ‘G’ be a connected planar graph with 20 vertices and the degree of each vertex is 3. Find the number of regions in the graph.

Solution:

By the sum of degrees theorem,

20

i=1 deg(Vi) = 2|E|

20(3) = 2|E|

|E| = 30


By Euler’s formula,

|V| + |R| = |E| + 2

20+ |R| = 30 + 2

|R| = 12

Hence, the number of regions is 12.

=======================================================






Computer Networks Quick Notes


4) In a token ring network the transmission speed is 10^7 bps and the propagation speed is 200 metres/micro second. The 1-bit delay in this network is equivalent to:
(A) 500 metres of cable.
(B) 200 metres of cable.
(C) 20 metres of cable.
(D) 50 metres of cable.

Answer (C)
Transmission delay for 1 bit t = 1/(10^7) = 0.1 micro seconds.
200 meters can be traveled in 1 micro second. Therefore, in 0.1 micro seconds, 20 meters can be traveled.

================================

Series: 1 + x + x2 + x3 + x4 + x5

Sum of Series is in GP = (1-x6)/(1-x)

================================

2) The message 11001001 is to be transmitted using the CRC polynomial x^3 + 1 to protect it from errors. The message that should be transmitted is:
(A) 11001001000
(B) 11001001011
(C) 11001010
(D) 110010010011

Answer (B)
The polynomial x^3+1 corresponds to divisor is 1001.

11001001 000  <--- input right padded by 3 bits
1001          <--- divisor
01011001 000  <---- XOR of the above 2
 1001         <--- divisor
00010001 000
   1001
00000011 000
      10 01
00000001 010
       1 001
00000000 011 <------- remainder (3 bits)
See this for division process.
After dividing the given message 11001001 by 1001, we get the remainder as 011 which is the CRC. The transmitted data is, message + CRC which is 11001001 011.

========================================================================


3) The distance between two stations M and N is L kilometers. All frames are K bits long. The propagation delay per kilometer is t seconds. Let R bits/second be the channel capacity. Assuming that processing delay is negligible, the minimum number of bits for the sequence number field in a frame for maximum utilization, when the sliding window protocol is used, is:


Answer (C)

Distance between stations = L KM
Propogation delay per KM = t seconds
Total propagation delay = Lt seconds

Frame size = k bits
Channel capacity = R bits/second
Transmission Time = k/R

Let n be the window size.

UtiliZation = n/(1+2a) where a = Propagation time / transmission time
            = n/[1 + 2LtR/k]
            = nk/(2LtR+k)
For maximum utilization: nk = 2LtR + k
Therefore, n = (2LtR+k)/k
Number of bits needed for n frames is Log(n).
==================================================================

2) Consider an instance of TCP’s Additive Increase Multiplicative Decrease(AIMD) algorithm where the window size at the start of the slow start phase is 2 MSS and the threshold at the start of the first transmission is 8 MSS. Assume that a time out occurs during the fifth transmission. Find the congestion window size at the end of the tenth transmission.
(A) 8 MSS
(B) 14 MSS
(C) 7 MSS
(D) 12 MSS

Answer (C)

Since Slow Start is used, window size is increased by the number of segments successfuly sent. This happens until either threshold value is reached or time out occurs.
In both of the above situations AIMD is used to avoid congestion. If threshold is reached, window size will be increased linearly. If there is timeout, window size will be reduced to half.

Window size for 1st transmission = 2 MSS
Window size for 2nd transmission = 4 MSS
Window size for 3rd transmission = 8 MSS
threshold reached, increase linearly (according to AIMD)
Window size for 4th transmission = 9 MSS
Window size for 5th transmission = 10 MSS
time out occurs, resend 5th with window size starts with as slow start.
Window size for 6th transmission = 2 MSS
Window size for 7th transmission = 4 MSS
threshold reached, now increase linearly (according to AIMD)
Additive Increase: 5 MSS (since 8 MSS isn’t permissible anymore)
Window size for 8th transmission = 5 MSS
Window size for 9th transmission = 6 MSS
Window size for 10th transmission = 7 MSS

==================================================================

SMTP is an application layer protocol used for e-mail transmission.
TCP is a core transport layer protocol.
BGP is a network layer protocol backing the core routing decisions on the Internet
PPP is a data link layer protocol commonly used in establishing a direct connection between two networking nodes.

==================================================================



1) The address of a class B host is to be split into subnets with a 6-bit subnet number. What is the maximum number of subnets and the maximum number of hosts in each subnet?
(A) 62 subnets and 262142 hosts.
(B) 64 subnets and 262142 hosts.
(C) 62 subnets and 1022 hosts.
(D) 64 subnets and 1024 hosts.

Answer (C)
Maximum number of subnets = 2^6-2 =62.
Note that 2 is subtracted from 2^6. The RFC 950 specification reserves the subnet values consisting of all zeros (see above) and all ones (broadcast), reducing the number of available subnets by two.

Maximum number of hosts is 2^10-2 = 1022.
2 is subtracted for Number of hosts is also. The address with all bits as 1 is reserved as broadcast address and address with all host id bits as 0 is used as network address of subnet.
In general, the number of addresses usable for addressing specific hosts in each network is always 2^N – 2 where N is the number of bits for host id.

==================================================================



2) The message 11001001 is to be transmitted using the CRC polynomial x^3 + 1 to protect it from errors. The message that should be transmitted is:
(A) 11001001000
(B) 11001001011
(C) 11001010
(D) 110010010011

Answer (B)
The polynomial x^3+1 corresponds to divisor is 1001.

11001001 000  <--- input right padded by 3 bits
1001          <--- divisor
01011001 000  <---- XOR of the above 2
 1001         <--- divisor
00010001 000
   1001
00000011 000
      10 01
00000001 010
       1 001
00000000 011 <------- remainder (3 bits)
See this for division process.
After dividing the given message 11001001 by 1001, we get the remainder as 011 which is the CRC. The transmitted data is, message + CRC which is 11001001 011.

==================================================================



3) The distance between two stations M and N is L kilometers. All frames are K bits long. The propagation delay per kilometer is t seconds. Let R bits/second be the channel capacity. Assuming that processing delay is negligible, the minimum number of bits for the sequence number field in a frame for maximum utilization, when the sliding window protocol is used, is:


Answer (C)

Distance between stations = L KM
Propogation delay per KM = t seconds
Total propagation delay = Lt seconds

Frame size = k bits
Channel capacity = R bits/second
Transmission Time = k/R

Let n be the window size.

UtiliZation = n/(1+2a) where a = Propagation time / transmission time
            = n/[1 + 2LtR/k]
            = nk/(2LtR+k)
For maximum utilization: nk = 2LtR + k
Therefore, n = (2LtR+k)/k
Number of bits needed for n frames is Logn.
==================================================================

1) Station A uses 32 byte packets to transmit messages to
Station B using a sliding window protocol. The round trip delay between A
 and B is 80 milliseconds and  the bottleneck bandwidth on the path
between A and B is 128 kbps. What is the  optimal window size that A
should use?

(A) 20

(B) 40

(C) 160

(D) 320


Answer (B)


Round Trip propagation delay = 80ms
Frame size = 32*8 bits
Bandwidth = 128kbps
Transmission Time = 32*8/(128) ms = 2 ms

Let n be the window size.

UtiliZation = n/(1+2a) where a = Propagation time / transmission time
            = n/(1+80/2)

For maximum utilization: n = 41 which is close to option (B)
==================================================================

2) Frames of 1000 bits are sent over a 10^6 bps duplex link
between two hosts. The propagation time is 25ms. Frames are to be
transmitted into this link to maximally pack them in transit (within the
 link).

What is the minimum number of bits (i) that will be required to
represent the sequence numbers distinctly? Assume that no time gap needs
 to be given between transmission of two frames.

(A) i=2

(B) i=3

(C) i=4

(D) i=5


Answer (D)

Transmission delay for 1 frame = 1000/(10^6) = 1 ms

Propagation time = 25 ms

The sender can atmost transfer 25 frames before the first frame reaches the destination.

The number of bits needed for representing 25 different frames = 5





3) Consider the data of previous question. Suppose that the
sliding window protocol is used with the sender window size of 2^i where
 is the number of bits identified in the previous question and
acknowledgments are always piggybacked. After sending 2^i frames, what
is the minimum time the sender will have to wait before starting
transmission of the next frame? (Identify the closest choice ignoring
the frame processing time.)

(A) 16ms

(B) 18ms

(C) 20ms

(D) 22ms


Answer (B)

Size of sliding window = 2^5 = 32

Transmission time for a frame = 1ms

Total time taken for 32 frames = 32ms

The sender cannot receive acknoledgement before round trip time which is 50ms

After sending 32 frames, the minimum time the sender will have to wait
before starting transmission of the next frame = 50 – 32 = 18

==================================================================









Operating System Quick Notes


1) If it takes 100 ns to search TLB and 1000 ns to access main memory. On average 10 hits occur for every 100 references to TLB. What is the effective memory access time with two level page tables and TLB is ?

Ans:
(TLB access time + Main memory access time)*hit ratio + (TLB access time + 3*main memory access time)*miss ratio
(100 + 1000)0.1 + (100 + 3000)0.9 = 2900ns

==================================================================

Consider a system with byte-addressable memory, 32 bit logical addresses, 4 kilobyte page size and page table entries of 4 bytes each. The size of the page table in the system in megabytes is ___________

Ans:

Number of entries in page table = 232 / 4Kbyte 
                                = 232 / 212
                                        = 220

Size of page table = (No. page table entries)*(Size of an entry)
                   = 220 * 4 bytes
                   = 222
                   = 4 Megabytes


=========================================================================

1. Consider a machine with 64 MB physical memory and a 32-bit
 virtual address space. If the page size is 4KB, what is the approximate
 size of the page table? (GATE 2001)

(a)  16 MB

(b)  8 MB

(c) 2 MB

(d) 24 MB


Answer: (c)

Explanation:

A page entry is used to get address of physical memory. Here we assume
that single level of Paging is happening. So the resulting page table
will contain entries for all the pages of the Virtual address space.


Number of entries in page table =
                    (virtual address space size)/(page size) 

Using above formula we can say that there will be 2^(32-12) = 2^20 entries in page table.

No. of bits required to address the 64MB Physical memory = 26.

So there will be 2^(26-12) = 2^14 page frames in the physical memory.
And page table needs to store the address of all these 2^14 page frames.
 Therefore, each page table entry will contain 14 bits address of the
page frame and 1 bit for valid-invalid bit.

Since memory is byte addressable. So we take that each page table entry is 16 bits i.e. 2 bytes long.


Size of page table =
  (total number of page table entries) *(size of a page table entry)
   = (2^20 *2) = 2MB

==================================================================


1. Suppose the time to service a page fault is on the average
 10 milliseconds, while a memory access takes 1 microsecond. Then a
99.99% hit ratio results in average memory access time of (GATE CS 2000)

(a) 1.9999 milliseconds

(b) 1 millisecond

(c) 9.999 microseconds

(d) 1.9999 microseconds


Answer: (d)

Explanation:


Average memory access time =
      [(% of page miss)*(time to service a page fault) +
                  (% of page hit)*(memory access time)]/100

So, average memory access time in microseconds is.

(99.99*1 + 0.01*10*1000)/100 = (99.99+100)/1000 = 199.99/1000 =1.9999 µs

=================================================================


Deadlock :
    - It is a processes which are suspended or blocked state and are not in ready or running state and are waiting for some resources.
   


Spin Lock :
    - It is the condition where two or more processes are not in the deadlock state , one process is dispatched by the CPU scheduler for execution (i.e to enter the Critical Section) while the other process is held by the CS.

    - Process P2 is in the running state and P1 is in the ready state and both of them are locked.
    - Process P1 is inside the Critical Sections and wants the CPU in order to execute and come out of the Critical Section , and Process P2 will not give the CPU unless it enters into the Critical Section.
    - Process P2 can’t enter the critical section due to the lock and Process P1 is preempted by the CPU.


=================================================================

Semaphores:


    (a) Counting Semaphore:

        - It is a structure variable with an integer counter and a queue as list.
        - The Integer counter, which tells how many number of processes can be present in the Critical Section
        - The queue contains the list of processes which are waiting to enter the critical section.
        - Mutual Exclusion is not guaranteed since many processes can be present in the critical section at a time. But Mutual Exclusion can be achieved if the counter is set to 1.



    (b) Binary Semaphore (or Mutex)

        - It is used for Mutual Exclusion
        - It has enum datatype which can take either 0 or 1 value.
        - It similar to counting semaphore whose value is initialised to 1.
        - Using Mutexes there is a chance of deadlock.


=================================================================


Linker:
    - It generates the relocatable address
    - It resolves the symbol table


Loader:
    - It generates the absolute address from relocatable address.


=================================================================