Practice | GeeksforGeeks | A computer science portal for geeks

Popular Company Tags

Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs
show more


Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs


Popular Topic Tags

Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph
show more


Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph

Home
Sahil Manchanda acc
Subjective Answers

Home
Sahil Manchanda acc
Subjective Answers
Stack
Through start call.
Use a circular array of size k
Mark Phase
When an object is created, its mark bit is set to 0(false). In the Mark phase, we set the marked bit for all the reachable objects (or the objects which a user can refer to) to 1(true). Now to perform this operation we simply need to do a graph traversal, a depth first search approach would work for us. Here we can consider every object as a node and then all the nodes (objects) that are reachable from this node (object) are visited and it goes on till we have visited all the reachable nodes.
Sweep Phase
As the name suggests it “sweeps” the unreachable objects i.e. it clears the heap memory for all the unreachable objects. All those objects whose marked value is set to false are cleared from the heap memory, for all other objects (reachable objects) the marked bit is set to false.
Now the mark value for all the reachable objects is set to false, since we will run the algorithm (if required) and again we will go through the mark phase to mark all the reachable objects.
127.0.0.0/8
To test the IPv4 software on the machine
used between the client and server process on the same machine.
By performing normalization
The host file is used to map hostnames to IP addresses. This file is located deep down in Windows folder. It is basically a plain text file and size of the original host default file is around 824 bytes.
The Host file in Windows is located at location
C:\Windows\System32\drivers\etc
Example of typical Host Files:
127.0.0.1  localhost loopback
::1        localhost
Cloud computing is a form of Internet-based computing that provides shared computer processing resources and data to computers and other devices on demand.
 It is a model for enabling ubiquitous, on-demand access to a shared pool of configurable computing resources (e.g., computer networks, servers, storage, applications and services).
 
The NIST's definition of cloud computing defines the service models as follows:[3]
Software as a Service (SaaS). The capability provided to the consumer is to use the provider's applications running on a cloud infrastructure. The applications are accessible from various client devices through either a thin client interface, such as a web browser (e.g., web-based email), or a program interface. The consumer does not manage or control the underlying cloud infrastructure including network, servers, operating systems, storage, or even individual application capabilities, with the possible exception of limited user-specific application configuration settings.
Platform as a Service (PaaS). The capability provided to the consumer is to deploy onto the cloud infrastructure consumer-created or acquired applications created using programming languages, libraries, services, and tools supported by the provider. The consumer does not manage or control the underlying cloud infrastructure including network, servers, operating systems, or storage, but has control over the deployed applications and possibly configuration settings for the application-hosting environment.
Infrastructure as a Service (IaaS). The capability provided to the consumer is to provision processing, storage, networks, and other fundamental computing resources where the consumer is able to deploy and run arbitrary software, which can include operating systems and applications. The consumer does not manage or control the underlying cloud infrastructure but has control over operating systems, storage, and deployed applications; and possibly limited control of select networking components (e.g., host firewalls).
Bridge is used to connect similar LANs. Hence it is an inter networking device
Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. 
 
Copy constructor is used to :

Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from an object.

Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from an object.
Presence of intermediate code called the bytecode
distributes the load among several servers
Error since static nested classes can access members of the outer class only through its object.
2
CREATE TABLE Students (sid CHAR(9), name VARCHAR(20), login CHAR(8), age INTEGER, gpa REAL);
A far pointer is typically 32 bit that can access memory outside current segment.  To use this, compiler allocates a segment register to store segment address, then another register to store offset within current segment.
Like far pointer, huge pointer is also typically 32 bit and can access outside segment. In case of far pointers, a segment is fixed. In far pointer, the segment part cannot be modified, but in Huge it can be
Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine. The limitation is that we can only access 64kb of data at a time.
Simple Stop and Wait
Sender:
Rule 1) Send one data packet at a time.
Rule 2) Send next packet only after receiving acknowledgement for previous.
Receiver:
Rule 1) Send acknowledgement after receiving and consuming of data packet.
Rule 2) After consuming packet acknowledgement need to be sent (Flow Control)
 
Problems :
1. Lost Data
2. Lost Acknowledgement:
3. Delayed Acknowledgement/Data: After timeout on sender side, a long delayed acknowledgement might be wrongly considered as acknowledgement of some other recent packet.
Stop and Wait ARQ (Automatic Repeat Request)
Above 3 problems are resolved by Stop and Wait ARQ (Automatic Repeat Request) that does both error control and flow control.
1. Time Out:

2. Sequence Number (Data)


3. Delayed Acknowledgement:
This is resolved by introducing sequence number for acknowledgement also.
Working of Stop and Wait ARQ:
1) Sender A sends a data frame or packet with sequence number 0.
2) Receiver B, after receiving data frame, sends and acknowledgement with sequence number 1 (sequence number of next expected data frame or packet)
There is only one bit sequence number that implies that both sender and receiver have buffer for one frame or packet only.
Characteristics of Stop and Wait ARQ:
It uses link between sender and receiver as half duplex link
Throughput = 1 Data packet/frame per  RTT
If Bandwidth*Delay product is very high, then stop and wait protocol is not so useful. The sender has to keep waiting for acknowledgements before sending the processed next packet.
It is an example for “Closed Loop OR connection oriented “ protocols
It is an special category of SWP where its window size is 1
Irrespective of number of packets sender is having stop and wait protocol  requires only  2 sequence numbers 0 and 1
The Stop and Wait ARQ solves main three problems, but may cause big performance issues as sender always waits for acknowledgement even if it has next packet ready to send. Consider a situation where you have a high bandwidth connection and propagation delay is also high (you are connected to some server in some other country though a high speed connection). To solve this problem, we can send more than one packet at a time with a larger sequence numbers. We will be discussing these protocols in next articles.
So Stop and Wait ARQ may work fine where propagation delay is very less for example LAN connections, but performs badly for distant connections like satellite connection.
At the very high level, we can think of NULL as null pointer which is used in C for various purposes. Some of the most common use cases for NULL are
a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
b) To check for null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
c) To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
The example of a) is
int * pInt = NULL;
Run on IDE
The example of b) is
if(pInt != NULL) /*We could use if(pInt) as well*/
{ /*Some code*/}
else
{ /*Some code*/}
Run on IDE
The example of c) is
int fun(int *ptr)
{
 /*Fun specific stuff is done with ptr here*/
 return 10;
}
fun(NULL);
Run on IDE
It should be noted that NULL pointer is different from uninitialized and dangling pointer. In a specific program context, all uninitialized or dangling or NULL pointers are invalid but NULL is a specific invalid pointer which is mentioned in C standard and has specific purposes. What we mean is that uninitialized and dangling pointers are invalid but they can point to some memory address that may be accessible though the memory access is unintended.
#include <stdio.h>
int main()
{
 int *i, *j;
 int *ii = NULL, *jj = NULL;
 if(i == j)
 {
  printf("This might get printed if both i and j are same by chance.");
 }
 if(ii == jj)
 {
  printf("This is always printed coz ii and jj are same.");
 }
 return 0;
}
Sorted Merge Algorithm of Linked Lists.
Perform hashing; if the character is seen the first time; then put it in the resultant string; otherwise skip the character.
// Returns true if trees with roots as root1 and root2 are mirror
bool isMirror(struct Node *root1, struct Node *root2)
{
    // If both trees are emptu, then they are mirror images
    if (root1 == NULL && root2 == NULL)
        return true;
 
    // For two trees to be mirror images, the following three
    // conditions must be true
    // 1 - Their root node's key must be same
    // 2 - left subtree of left tree and right subtree
    //      of right tree have to be mirror images
    // 3 - right subtree of left tree and left subtree
    //      of right tree have to be mirror images
    if (root1 && root2 && root1->key == root2->key)
        return isMirror(root1->left, root2->right) &&
               isMirror(root1->right, root2->left);
 
    // if neither of above conditions is true then root1
    // and root2 are not mirror images
    return false;
}
 
// Returns true if a tree is symmetric i.e. mirror image of itself
bool isSymmetric(struct Node* root)
{
    // Check if tre is mirror of itself
    return isMirror(root, root);
}
Corrupted bits cause error in the frames. TYPES:-
Single bit errors
Burst Errors
Framing : - At data link layer , it extracts message from sender and provide it to receiver by providing sender's and receiver's address.
Types:-
1) Fixed Size Framing : - there is no need to provide boundaries to the frame, length of the frame itself acts as delimiter.
2) Variable Size Framing : -  In this there is need to define end of frame as well as beginning of next frame to distinguish. For this character oriented and bit oriented approach is used.
Variable size framing can be of two types:-
1. Character oriented
ASCII characters are sent in this; Byte Stuffing required 
2. Bit oriented
 Bits are sent in this; Bit Stuffing required 
// Java program to print all possible strings of length k
class PrintAllKLengthStrings {
 
    // Driver method to test below methods
    public static void main(String[] args) {             
        System.out.println("First Test");
        char set1[] = {'a', 'b'};
        int k = 3;
        printAllKLength(set1, k);
         
        System.out.println("\nSecond Test");
        char set2[] = {'a', 'b', 'c', 'd'};
        k = 1;
        printAllKLength(set2, k);        
    }    
 
    // The method that prints all possible strings of length k.  It is
    //  mainly a wrapper over recursive function printAllKLengthRec()
    static void printAllKLength(char set[], int k) {
        int n = set.length;        
        printAllKLengthRec(set, "", n, k);
    }
 
    // The main recursive method to print all possible strings of length k
    static void printAllKLengthRec(char set[], String prefix, int n, int k) {
         
        // Base case: k is 0, print prefix
        if (k == 0) {
            System.out.println(prefix);
            return;
        }
 
        // One by one add all characters from set and recursively 
        // call for k equals to k-1
        for (int i = 0; i < n; ++i) {
             
            // Next character of input added
            String newPrefix = prefix + set[i]; 
             
            // k is decreased, because we have added a new character
            printAllKLengthRec(set, newPrefix, n, k - 1); 
        }
    }
}
Output:
First Test
aaa
aab
aba
abb
baa
bab
bba
bbb

Second Test
a
b
c
d
Use Binary search
int findRotation(int* a, int low, int hig){
    if(a[low] < a[hig])    // It is a sorted array.
        return -1;
    int mid;
    while(low < hig){
        mid = low + (hig - low) >>1 ;
        if (a[mid - 1] > a[mid])   // found the index;
            return mid;
        if (a[low] < a [mid]) // left is sorted, check right.
            low = mid - 1;
        else if (a[mid] < a[hig]) // right is sorted, check left.
            hig = mid + 1;
    }
    return  -1;
}
N-ary tree is a tree in node can have any number of child.
 
1. reverse the children pointers of a node
2 Recur for left and right subtrees.
Yes
Two trees are Isomorphic if one of them can be obtained by swapping few left or right sub-tree. Any number of nodes, at any level can be swapped.
Condition for trees to be isomorphic:-
1) Data of both the trees should be same.
2) One of the following should be true:-
a) Left child of tree 1 should be isomorphic to left child of  tree 2 and right child of tree 1 should be isomorphic to right child of tree 2.
b)  Left child of tree 1 should be isomorphic to right child of tree 2 and right child of tree 1 should be isomorphic to left child of tree 2.
Hamming distance between 2 code words a and b is
d(a,b) = a xor b
(number of differences in the corresponding bits).
Sort the array and initialize two pointers
i=0,j=n-1;
if (a[i]+a[j]==s)
  store the pair i++;j--
else if (a[i]+a[j]<s)
   i++;
else
  j--;
 
subtract root data from the sum and recur for left and right subtrees
When we hit the leaf node compare its data with  the remaining sum. If they are equal return true else false;
priority queue
swap left and right pointers of root node and recur for left and right subtrees.
Stop the inorder traversal when counter value equals k
The idea is to store mapping from given tree nodes to clone tree node in hashtable. Following are detailed steps.
1) Recursively traverse the given Binary and copy key value, left pointer and right pointer to clone tree. While copying, store the mapping from given tree node to clone tree node in a hashtable. In the following pseudo code, ‘cloneNode’ is currently visited node of clone tree and ‘treeNode’ is currently visited node of given tree.
   cloneNode->key  = treeNode->key
   cloneNode->left = treeNode->left
   cloneNode->right = treeNode->right
   map[treeNode] = cloneNode 
2) Recursively traverse both trees and set random pointers using entries from hash table.
   cloneNode->random = map[treeNode->random] 
When a process has acquired a write lock on a shared data item, no other process is allowed to access that item.
It is a exclusive mode lock meaning no other process can acquire a read or write lock on the data.
It can be implemented using synchronization primitives like semaphores. 
Host to network layer : Representation of bits, framing
Internet Layer : Internetworking, routing
Transport Layer : End to End Delivery
Application Layer : Access to resources on the network
user space
Using difference of node counts
1) Get count of the nodes in first list, let count be c1.
2) Get count of the nodes in second list, let count be c2.
3) Get the difference of counts d = abs(c1 – c2)
4) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.
5) Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)
 
 
int getIntesectionNode(struct Node* head1, struct Node* head2)
{
  int c1 = getCount(head1);
  int c2 = getCount(head2);
  int d;
 
  if(c1 > c2)
  {
    d = c1 - c2;
    return _getIntesectionNode(d, head1, head2);
  }
  else
  {
    d = c2 - c1;
    return _getIntesectionNode(d, head2, head1);
  }
}
 
/* function to get the intersection point of two linked
   lists head1 and head2 where head1 has d more nodes than
   head2 */
int _getIntesectionNode(int d, struct Node* head1, struct Node* head2)
{
  int i;
  struct Node* current1 = head1;
  struct Node* current2 = head2;
 
  for(i = 0; i < d; i++)
  {
    if(current1 == NULL)
    {  return -1; }
    current1 = current1->next;
  }
 
  while(current1 !=  NULL && current2 != NULL)
  {
    if(current1 == current2)
      return current1->data;
    current1= current1->next;
    current2= current2->next;
  }
 
  return -1;
}
 
take two variables min and s_min.  min=a[0]
and start for loop with i=1 upto n-1.
if we found element which is smaller than min then first update s_min=min and also update min=a[i].
Time Complexity=O(n) time.
It is a situation in which concurrently executing processes accessing the same shared data item may affect the consistency of the data item.
Outcome of the execution depends the particular order in which the statements are executed.
Trie is an efficient retrieval data structure used to store collection of strings.
If 2 strings have same prefix then they have same ancestors in the trie structure.
struct TrieNode
{
    TrieNode* children[256];
    bool isleaf; //to indicate end of the word.
};
Trie is an efficient retrieval data structure used to store collection of strings.
If 2 strings have same prefix then they have same ancestors in the trie structure.
struct TrieNode
{
    TrieNode* children[256];
    bool isleaf; //to indicate end of the word.
};
 
Use a queue data structure and at the end of each level print "$".
void levelOrder(Node* node)
{
  //Your code here
  queue<struct Node*> q;
  q.push(node);
  Node *tmp;
  while(!q.empty()){
      int count=q.size();
      while(count--){
          tmp=q.front();
          q.pop();
          cout<<tmp->data<<" ";
          if(tmp->left){
              q.push(tmp->left);
          }
          if(tmp->right){
              q.push(tmp->right);
          }
      }
      cout<<"$ ";
  }
}
queue and a hashmap
Use a minheap of k elements and replace the root with the current element if it is greater than the root and heapify.
It is an integer variable that apart from initialization is accessed through two operations:-
1. P (to test)
2. V (to increment)
There can be two types of semaphores; binary and counting.
Semaphores is a synchronization primitive that can be used to solve the critical section problem and also solve synchronization problems.
When one process is executing no other process is allowed to enter the critical section. This is done to prevent inconsistency to the shared data item.
A solution for the critical section problem must satisfy the following three conditions:

Mutual Exclusion: If a process Pi is executing in its critical section, then no other process is allowed to enter into the critical section.
Progress: If no process is executing in the critical section, then the decision of a process to enter a critical section cannot be made by any other process that is executing in its remainder section. The selection of the process cannot be postponed indefinitely.
Bounded Waiting: There exists a bound on the number of times other processes can enter into the critical section after a process has made request to access the critical section and before the requested is granted.

Mutual Exclusion: If a process Pi is executing in its critical section, then no other process is allowed to enter into the critical section.
Progress: If no process is executing in the critical section, then the decision of a process to enter a critical section cannot be made by any other process that is executing in its remainder section. The selection of the process cannot be postponed indefinitely.
Bounded Waiting: There exists a bound on the number of times other processes can enter into the critical section after a process has made request to access the critical section and before the requested is granted.
NRCS
Store the index of previous instance of each character.
For every new character:
1. If prev instance is not present; increment the result.
2. else update length and consider new NRCS.
A set of waiting processes is in deadlocked state if one process is waiting for a resource held by another process in the set.
Race condition occurs when multiple concurrently executing process access a shared data item and result of execution depends on the order in which execution takes place . hence data item may lose consistency.
Atomicity
Consistency 
Isolation
Durability
Connection oriented:- TCP (Transmission control protocol) is connection oriented network
1) In this first connection is made before sending the message 
2) It is a stream based transmission
3) In this receiver is first checked for authentication so chances of getting error are very less.
4) It is more reliable network.
5) Exchange of parameters is done before transmission.
Connection less :- UDP(User Datagram Protocol)
1) In this no connection is established prior to sending message.
2) It transmits data as message.
3) There is no need to authenticate, so more likely to have error.
4) It is unreliable network.
When the referenced page number is not in Main Memory, Page fault occurs.
It decreases CPU utilization
Either increase the number of frames or decrease the degree of multi programming or use optimal page replacement strategy. 
When a process is spending more time in paging rather than execution.
It happens when the no. of processes is large or the degree of multi programming is high.Here CPU utilization decreases because of swapping.
Lock acquired by writer ie a user that reads and modifies shared data.
When a write lock is acquired by a process, no other process is allowed to acquire any lock, ie it is an exclusive lock.
Pragma is used to turn on or off certain features.
Uses:-
1. pragma start and pragma exit can be used to call the functions before the execution of main and before the final statement respectively.
2. pragma warn -/+warning code
can be used to suppress or ensure the warnings that are displayed after compilation.
Compile Error as both operands must be integer
QuickSort
The time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the string representing the input. The time complexity of an algorithm is commonly expressed using big O notation, which excludes coefficients and lower order terms.
Example
O(1)
O(lg n)
O(n) etc.
Dynamic Host Configuration Procol.
It provides:-
IP Address of Computer
subnet Mask of a Computer
IP address of a router
IP address of a name server
It can provide IP address both statically and dynamically
It is a advanced version of both RARP and BOOTP.
Implementation of path vector routing
Communication between cooperating processes.
Shared Memory:- Messages written on a memory segment that is shared between the processes.
Sockets: - these are the logical end points where data can be written or read from. It is the combination of Ip address and the port address.
The entity sets that do not have primary key of their own. They depend on primary key of another entity set called the strong entity set.
Implementation of Link state routing
pkill
Find the inorder traversal
Check whether it is sorted.
You can optimize this by keeping track of the previously obtained value and comparing it with the current value.
Undecidable problem
replace the root with the last element
heapify again to preserve min heap property
TCP:- Reliable connection oriented
UDP:- Unreliable connectionless
2 logn
Execution of multiple programs in all of these types is there. 
Multitasking :- Single user system and single processor.
Multiprogramming:- Multi-user system and single processor
Multiprocessor :- Multiuser system and multiple processors.
Min Heap
1. FCFS (First Come First Serve)
2. SJF(Shortest Job First)
3. Round Robin
4. Priority
SRTFS can be implemented using min heap.
 
Shared Memory
Message passing
Sockets
There are numerous techniques and algorithms that can be used to intelligently load balance client access requests across server pools.
A simple method of load balancing servers or for providing simple fault tolerance. Multiple identical servers are configured to provide exactly the same services. All are configured to use the same Internet domain name but each has a unique IP address. A DNS server has a list of all the unique IP addresses that are associated with the Internet domain name. When requests for the IP Address associated with the Internet domain name are received, the addresses are returned in a rotating sequential manner.
Mark and Sweep Algorithm
SELECT name ,department from employee WHERE salary =(SELECT max(salary) from employee);
Maintain a stack to store the elements of the linked list.
Traverse the list again to check whether the elements are same or not in the opposite direction.
Variable storing the address of another variable.
Example:
int a;
int *ip=&a;
Yes
Time to live. Routers discard the packet if it exceeds this limit. This is also called hop limit.
No
Catalan Number :         
t(n)= sum (i=1 to n) t(i-1)*t(n-i)
t(0)=1;t(1)=1
The formula comes by fixing 1 node and then finding t value for left and right subtrees and multiplying them.
t(i-1)= no of BST's with i-1 nodes.
Solving the recurrence gives catalan number.
In left outer join, all the tuples of left relation are covered, filling NULL entries in the fields of right relation if there is no match.
In left outer join, all the tuples of right relation are covered, filling NULL entries in the fields of left relation if there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
Compile time error due to semicolon after j.
Stack which is a last in first out(LIFO) data structure.
fcfs
Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.Hence
0 1 2 3 4 
DELETE: It is a DML command that is used to remove the data from a table. It can be used in conjunction with WHERE to delete only the rows meeting the specified criteria.

TRUNCATE: It is a DDL which is used to remove ALL the rows from a table. However, it does not delete the table.

DROP: It is used t remove the data as well as the table from the database.
A segment tree is a tree data structure for storing intervals, or segments. It allows querying which of the stored segments contain a given point. It is, in principle, a static structure; that is, it's a structure that cannot be modified once it's built. A similar data structure is the interval tree.
For example if the segment tree is used for range minimum query , then  it will be represented as:-
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. 
Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j .
Example:
The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).
IP addresses are unique and universal addresses assigned to a computer system.
Under IPv4 protocol, IP addresses are 32 bit long.
Representations:-
1. Dotted decimal notation e.g. 192.120.40.10
2. Binary Notation : divided into 4 octets.
IPv6 has 128 bits long IP addresses.
1. Less Memory wastage due to dynamic memory allocation.
2. Ease of Insertion/deletion: Only Modification of pointers reqd.
HTTPS uses SSL(Secure Sockets Layer) or TLS(Transport layer Security) to provide security.
Use a map between string and frequency and print those strings whose frequency is 1.
map<string,int> m;
 
Centralized System for overall organization to project an overall view of an organization and to remove inconsistencies between different departments and in turn increase profits of the organization.
Heap has following 2 properties:-
1. Shape property- Almost complete binary tree. All levels except possibly  the last are filled and last level has nodes towards the left.
2. Order property:-
If the value of the parent is greater than its children, it is called MAX HEAP
If the value of the parent is smaller than its children, it is called MIN HEAP
 
APPLICATIONS
Priority queues, sorting, order statistics
 
pre:-previous to the node to be deleted
del:-node to be deleted
pre->next=del->next;
del->next->prev=pre;
delete del;
Processes are  heavyweight  tasks that require their own separate address space whereas threads are light weight tasks that share the same address space.
We can find count in O(n) using a single traversal of input string. Following are steps.
a) Count the number of 1’s. Let the count of 1’s be m.
b) Return m(m-1)/2
The idea is to count total number of possible pairs of 1’s.
3
1st sock/ 2nd sock :-either black or white; if both are black or white, we are done otherwise:
3rd sock:- will complete the pair 
Use level order sum and update max_sum variable after traversing a particular level.
Array:- static memory allocation; Linked list:-dynamic memory allocation
Array:- Insertion/deletion complex O(n) Linked list:- Only pointers need to be changed O(1)
Array:- binary search efficient Linked List:-inefficient
Array types: Single and multidimensional Linked list types:-singly,doubly,circularly
 
  
The tree that is obtained by swapping the left and right pointers of each node.Example:-
Types:-
singly linked list
doubly linked list
circularly linked list
To detect the loop, use floyd cycle detection algorithm. Use 2 pointers, slow and fast that moves 1 step and 2 steps respectively. If they meet there is a loop in the list.
To remove the loop , move the slow pointer to the head of the list and keep the fast pointer where it was after applying the above algorithm. Now move them one step each. The point where they meet is the start point of the loop. Just store NULL in the next pointer of the previous node. 
Quick Sort is better :-
1. Space complexity of merge sort is higher.
2. Although the worst case of quick sort(when array is sorted) is O(n2) but it is rarely encountered.
3. Randomized quick sort performs better than quick sort in worst case as well.
Sequential listing of vertices in an directed acyclic graph.
Either use dfs or a stack to perform topological sort.
ALGORITHM:-
1.Run DFS on the graph to compute finishing times of each vertex.
2.As each vertex is finished, insert it onto the front of the linked list.
3. Output the list.
Iterative:-
Bubble
Selection
Insertion
Divide and Conquer:-
Merge Sort
Quick Sort
Others:-
Shell sort
Radix sort
Heap sort
 
Addition of an extra 0 bit in data after 5 consecutive 1's to differentiate flag and data.This is done at the data link layer.
FLAG:-01111110
(6 X 5 + 3(in sixth ball to retain the strike)) X 49 +6 X 6(50th over)
=33 X 49 +36
=1653
 
Let the minimum number of trials to find the critical floor (from where and above the egg will break)  be x.
We have to drop egg from xth floor in the first attempt since if it breaks, we try remaining (x-1) floors one by one from the bottom as only 2 eggs are present.
So in worst case, we make x trials.
If it doesn’t break, we jump (x-1) floors (Because we have
already made one attempt and we don't want to go beyond
x attempts.  Therefore (x-1) attempts are available),
    Next floor we try is floor x + (x-1)
Similarly, if this drop does not break, next need to jump
up to floor x + (x-1) + (x-2), then x + (x-1) + (x-2) + (x-3)
and so on.
Since the last floor to be tired is 100'th floor, sum of
series should be 100 for optimal value of x.
 x + (x-1) + (x-2) + (x-3) + .... + 1  = 100
 x(x+1)/2  = 100
         x = 13.651
Therefore, we start trying from 14'th floor. If Egg breaks
we one by one try remaining 13 floors.  If egg doesn't break
we go to 27th floor.
If egg breaks on 27'th floor, we try floors form 15 to 26.
If egg doesn't break on 27'th floor, we go to 39'th floor.
An so on...
The optimal number of trials is 14 in worst case.
2 Approaches:-
1. traverse the array and count the no of 1's 2's and 3's using 3 variables and traverse the array again to store these numbers.
2. Dutch National flag algorithm or 3-way partitioning.
1. sort the array.
2.traverse the array from left using loop variable say i;
3.Initialize two variables l=i+1;r=n-1;
while (l<r)
{
  if (a[l]+a[r]+a[i]==sum)
    return;
else if (a[l]+a[r]+a[i]<sum)
   l++;
else
  r--
}
Code Complexity=O(n^2 logn)
Centre
Divide the balls in groups of 3 each.
Compare the first 2 groups. If they are balanced, group 3 has the heavy ball. If not, heavier group has the heavy ball.
Compare any two balls of the heavier group and get the heavier ball.
Minimum numbers of comparisons=2.
19,20,45,46
If we can get 1lt in 5lt Jug then the problem is solved because we can add 3lt to it from 3lt Jug.Solution is as below.  
3 lt      5lt
3         0
0         3
3         3
1         5
1         0
0         1
3         1
0         4 
Make group of 5 horses and run 5 races. Suppose five groups are a,b,c,d,e and next alphabet is its individual rank in tis group(of 5 horses).for eg. d3 means horse in group d and has rank 3rd in his group. [ 5 RACES DONE ]
a1 b1 c1 d1 e1
a2 b2 c2 d2 e2
a3 b3 c3 d3 e3
a4 b4 c4 d4 e4
a5 b5 c5 d5 e5
Now make a race of (a1,b1,c1,d1,e1).[RACE 6 DONE] suppose result is a1>b1>c1>d1>e1
which implies a1 must be FIRST.
b1 and c1 MAY BE(but not must be) 2nd and 3rd.
FOR II position, horse will be either b1 or a2
(we have to find top 3 horse therefore we choose horses b1,b2,a2,a3,c1 do racing among them [RACE 7 DONE].
The only possibilities are :
c1 may be third
b1 may be second or third
b2 may be third
a2 may be second or third
a3 may be third
The final result will give ANSWER. suppose result is a2>a3>b1>c1>b2
then answer is a1,a2,a3,b1,c1.
HENCE ANSWER is 7 RACES
OSI reference model consists of seven layers:-
1) Layer 1:- Physical Layer :-modulation/demodulation, representation of bits, characteristics of interfaces and medium
2) Layer 2:- Data link Layer :-framing ,error control and flow control at node to node basis
3) Layer 3:- Network  Layer:-logical addressing, routing
4) Layer 4 :- Transport Layer:-error control, flow control on end to end basis
5) Layer 5 :- Session Layer:-dialog control, synchronization for entire session
6) Layer 6:- Presentation Layer:-cryptography, stagenography
7) Layer 7:-Application Layer:- interfaces to access the resources on the computer
1 and 2 go cross
2 comes back
7 and 10 go across
1 comes back
1 and 2 go across (done)
Total time = 2 + 2 + 10 + 1 + 2 = 17 mins
Number the bottles from 1 to 1000 and convert the numbers into binary. Each rat is assigned a position in the binary numbers written on bottles. Since log2 1000 =10 (rounded); therefore 10 positions are there in the binary representation, each of which is assigned to a rat starting from LSB.
If a position in the binary representation of a bottle is 1, then  the  rat is given a sip from the bottle otherwise not.
After 1 hour, we check which rats die and note their assigned positions. e.g  if rat 1 and 3 die, (assignment from LSB), then the bottle no. 00000 00101 ie 5th bottle is poisoned.
Divide the balls in groups of 3 each.
Compare the first 2 groups. If they are balanced, group 3 has the heavy ball. If not, heavier group has the heavy ball.
Compare any two balls of the heavier group and get the heavier ball.
Minimum numbers of comparisons=2.
Divide the balls in groups of 3 each.
Compare the first 2 groups. If they are balanced, group 3 has the heavy ball. If not, heavier group has the heavy ball.
Compare any two balls of the heavier group and get the heavier ball.
Minimum numbers of comparisons=2.
since there are 3000 bananas and the camel can carry at most 1000 bananas, at least five trips are needed to carry away all bananas from the plantation P (3 trips away from the plantation and 2 return trips):
 
 
P (plantation)
 ===forth===>
<===back====
===forth===>
<===back====
===forth===> 
 A
 
 
Point A in the above picture cannot be the market. This is because the camel can never travel more than 500 kilometers into the desert if it should return to the plantation (the camel eats a banana every kilometer it travels!). So point A lies somewhere in the desert between the plantation and the market. From point A to the next point, less than five trips must be used to transport the bananas to that next point. We arrive at the following global solution to the problem (P denotes the plantation, M denotes the market):
 
 
P (plantation)
 

===forth===>
<===back====
===forth===>
<===back====
===forth===> 
A
===forth===>
<===back====
===forth===>B===forth===>M (market)
 
 
Hence, 
divide 1000km into three part, first part of 200km, second part of 333km and final 467km.
so in first part it will consume 5*200 = 1000 bananas so remaining are 2000.
In second part it will consume 3*333 = 999 bananas so  remaining are 1001.
and at last it will consume 467*1 = 467 bananas so remaining are 1000-467 = 533
Out of 8 possibilities 2 possibilities are there in which they will not collide
1. when all of them move in anticlockwise direction.
2. when all of them move in clockwise direction.
required probability=6/8=0.75
Number the bottles from 1 to 13 and convert the numbers into binary. Each rat is assigned a position in the binary numbers written on bottles. Since log2 13 =4 (rounded); therefore 4 positions are there in the binary representation, each of which is assigned to a rat starting from LSB.
If a position in the binary representation of a bottle is 1, then  the  rat is given a sip from the bottle otherwise not.
After 24 hours, we check which rats die and note their assigned positions. e.g  if rat 1 and 3 die, (assignment from LSB), then the bottle no. 0101 ie 5th is poisoned.
C++ defines two unary operators new and delete that perform the task of allocating and freeing the memory in a better and easier way than C.Since these operators manipulate memory on fthe free store, they are also known as free store operators.
A data object creates inside a block with new, will remain in existence until it is explicitly destroyed by using delete . Thus, the lifetime of an object is directly under our control and is unrelated to the block structure of the program.
SYNTAX:-
pointer-variable =new data-type;
delete pointer-variable;
EXAMPLE:-
int *p=new int;
delete p;
 
To implement virtual functions, C++ uses a special form of late binding known as the virtual table or vTable. The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.
Every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table.
This table is simply a static array that the compiler creates at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class.
Each entry in this vTable is simply a Function Pointer that points to the most-derived function accessible by that class ie the most Base Class.
The compiler also adds a hidden pointer to the base class, which we will call *__vPtr.
*__vPtr is set (automatically) when a class instance is created so that it points to the virtual table for that class. *__vPtr is inherited by derived classes,
let’s take a look at a simple example

 

class Base
{
public:
virtual void function1() {};
virtual void function2() {};
};
class D1: public Base
{
public:
virtual void function1() {};
};
class D2: public Base
{
public:
virtual void function2() {};
};

class Base
{
public:
virtual void function1() {};
virtual void function2() {};
};
class D1: public Base
{
public:
virtual void function1() {};
};
class D2: public Base
{
public:
virtual void function2() {};
};
Because there are 3 classes here, the compiler will set up 3 virtual tables: one for Base, one for D1, and one for D2.
The compiler also adds a hidden pointer to the most Base class that uses virtual functions.

 

class Base
{
public:
FunctionPointer *__vptr;
virtual void function1() {};
virtual void function2() {};
};
class D1: public Base
{
public:
virtual void function1() {};
};
class D2: public Base
{
public:
virtual void function2() {};
};

class Base
{
public:
FunctionPointer *__vptr;
virtual void function1() {};
virtual void function2() {};
};
class D1: public Base
{
public:
virtual void function1() {};
};
class D2: public Base
{
public:
virtual void function2() {};
};
When a class object is created, *__vPtr is set to point to the virtual table for that class. For example, when a object of type Base is created, *__vPtr is set to point to the virtual table for Base. When objects of type D1 or D2 are constructed, *__vPtr is set to point to the virtual table for D1 or D2 respectively.
Because there are only two virtual functions here, each virtual table will have two entries (one for function1(), and one for function2()).
Base’s virtual table is simple. An object of type Base can only access the members of Base. Base has no access to D1 or D2 functions. Consequently, the entry for function1 points to Base::function1(), and the entry for function2 points to Base::function2().
D1’s virtual table is slightly more complex. An object of type D1 can access members of both D1 and Base. However, D1 has overridden function1(), making D1::function1() more derived than Base::function1(). Consequently, the entry for function1 points to D1::function1(). D1 hasn’t overridden function2(), so the entry for function2 will point to Base::function2().
D2’s virtual table is similar to D1, except the entry for function1 points to Base::function1(), and the entry for function2 points to D2::function2().
Here’s a picture of this graphically:
By using these tables, the compiler and program are able to ensure function calls resolve to the appropriate virtual function, even if you’re only using a pointer or reference to a base class.
When we use the same function name in both the base and derived classes, the function in the base class is declared as virtual using the virtual keyword preceding its normal declaration.
When the function is made virtual C++ determines which function to use at run time based on the type of object pointed to by the base pointer rather than the type of the pointer.
class BC
{
public:
    virtual void show(){}
};
class DC:public BC
{
public:
   void show(){}
};
int main()
{
  BC base;DC derived;
  BC *bptr;
  bptr=&base;
  bptr->show();//base class
  bptr=&derived;
  bptr->show();//derived class
  return 0;
}
if virtual keyword was not used here, base pointer, even when it is made to contain the address of a derived class, always executes function in the base class.
EXAMPLE:-
Virtual functions allow us to create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. For example, consider a employee management software for an organization, let the code has a simple base class Employee , the class contains virtual functions like raiseSalary(), transfer(), promote(),.. etc. Different types of employees like Manager, Engineer, ..etc may have their own implementations of the virtual functions present in base class Employee. In our complete software, we just need to pass a list of employees everywhere and call appropriate functions without even knowing the type of employee. For example, we can easily raise salary of all employees by iterating through list of employees. Every type of employee may have its own logic in its class, we don’t need to worry because if raiseSalary() is present for a specific employee type, only that function would be called.
class Employee
{
public:
    virtual void raiseSalary()
    {  /* common raise salary code */  }
 
    virtual void promote()
    { /* common promote code */ }
};
 
class Manager: public Employee {
    virtual void raiseSalary()
    {  /* Manager specific raise salary code, may contain
          increment of manager specific incentives*/  }
 
    virtual void promote()
    { /* Manager specific promote */ }
};
 
// Similarly, there may be other types of employees
 
// We need a very simple function to increment salary of all employees
// Note that emp[] is an array of pointers and actual pointed objects can
// be any type of employees. This function should ideally be in a class 
// like Organization, we have made it global to keep things simple
void globalRaiseSalary(Employee *emp[], int n)
{
    for (int i = 0; i < n; i++)
        emp[i]->raiseSalary(); // Polymorphic Call: Calls raiseSalary() 
                               // according to the actual object, not 
                               // according to the type of pointer                                 
}
class_name(const class_name&)
Run time polymorphism is implemented through virtual functions in C++. Here we use the pointer to base class to refer to all the derived objects.

When we use the same function name in both the base and derived classes, the function in the base class is declared as virtual using the virtual keyword preceding its normal declaration.
When the function is made virtual C++ determines which function to use at run time based on the type of object pointed to by the base pointer rather than the type of the pointer.
class BC
{
public:
    virtual void show(){}
};
class DC:public BC
{
public:
   void show(){}
};
int main()
{
  BC base;DC derived;
  BC *bptr;
  bptr=&base;
  bptr->show();//base class
  bptr=&derived;
  bptr->show();//derived class
  return 0;
}
if virtual keyword was not used here, base pointer, even when it is made to contain the address of a derived class, always executes function in the base class.
 
Hence, if virtual keyword is used, depending on the type of the object(derived) pointed to by the base pointer , C++ calls that version of the function at run time and hence run time polymorphism is achieved..  
Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class. Example:-
class Base
{
public:
       Base(){ cout<<"Constructing Base";}
       // this is a destructor:
       ~Base(){ cout<<"\nDestroying Base";}
};
class Derive: public Base
{
public:
       Derive(){ cout<<"\nConstructing Derive";}
       ~Derive(){ cout<<"\nDestroying Derive";}
};
int main()
{
        Base *basePtr = new Derive;//or new Derive();
        delete basePtr;
        /*here's the problem! Since Base's destructor is not virtual,
        it's ~Base that is called and not ~Derived. Therefore, all the important
        cleanup is not performed, which can create several resource leaks*/
        return 0;
}
when the base pointer is deleted using the delete operator, it will trigger the base class destructor and the derived class destructor won't be called at all. This may lead to memory leak situation,
OUTPUT:-
Constructing Base
Constructing Derive
Destroying Base
OUTPUT when virtual ~Base() is used:-
Constructing Base
Constructing Derive
Destroying Derive
Destroying Base
Hence we need virtual destructor here so that derived class object is destroyed. Note that constructors can't be virtual. 
Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class. Example:-
class Base
{
public:
       Base(){ cout<<"Constructing Base";}
       // this is a destructor:
       ~Base(){ cout<<"\nDestroying Base";}
};
class Derive: public Base
{
public:
       Derive(){ cout<<"\nConstructing Derive";}
       ~Derive(){ cout<<"\nDestroying Derive";}
};
int main()
{
        Base *basePtr = new Derive;//or new Derive();
        delete basePtr;
        /*here's the problem! Since Base's destructor is not virtual,
        it's ~Base that is called and not ~Derived. Therefore, all the important
        cleanup is not performed, which can create several resource leaks*/
        return 0;
}
when the base pointer is deleted using the delete operator, it will trigger the base class destructor and the derived class destructor won't be called at all. This may lead to memory leak situation,
OUTPUT:-
Constructing Base
Constructing Derive
Destroying Base
OUTPUT when virtual ~Base() is used:-
Constructing Base
Constructing Derive
Destroying Derive
Destroying Base
Hence we need virtual destructor here so that derived class object is destroyed. Note that constructors can't be virtual. 
return type operator op (class_name ob1 , class_name ob2)
here op is the operator symbol.
No of parameters can be
1. 0 if unary operator and member function is used
2. 1 if unary operator and friend function is used.
OR if binary operator and member function is used.
3. 2 if binary operator and friend function is used.
if friend function is used, friend keyword is used in the beginning of the method. 
99% of 2000 kg = 1980 kg water
and 20 kg of raw fruit.
In the evening, 2 % of the fruit was raw fruit (as 98 % was water). Let the fruit weight be x kgs.
(2/100) *x =20
Therefore, x=1000 kgs
(0!+0!+0!+0!+0!)!
=5!
=120
Yes we can do so.The above statement is equivalent to:-
array[i+1]=i;
i++;
This is because post increment operator follows 'use then change' mechanism ie first the value is used and then incremented. In above case, it uses the value i for assignment, increments i, so array index that is referenced is i+1 and assigns i to the index value.
int main(){    int a[6];    int i=0;    a[0]=10;    while (i<5)    {        a[i]=i++;    }        for (i=0;i<=5;i++)        cout<<a[i]<<" ";            return 0;}
output of the above code is 10 0 1 2 3 4
In theoretical computer science, the CAP theorem, also named Brewer's theorem after computer scientist Eric Brewer, states that it is impossible for a distributed computer system to simultaneously provide more than two out of three of the following guarantees:
 
Consistency:  The consistency property describes a consistent view of data on all nodes of the distributed system. That is, the system assures that operations have an atomic characteristic and changes are disseminated simultaneously to all nodes, yielding the same results.
Availability: This property demands the system to eventually answer every request, even in case of failures. This must be true for both read and write operations. 
Partition tolerance: This property describes the fact that the system is resilient to message losses between nodes. A partition is an arbitrary split between nodes of a system, resulting in complete message loss in between. This affects the prior properties. Mechanisms for maintaining consistency must cope with messages losses. And according to the availability property, every node of any potential partition must be able to respond to a request.
In other words, the CAP Theorem states that in the presence of a network partition, one has to choose between consistency and availability.
No distributed system is safe from network failures, thus network partitioning generally has to be tolerated. In the presence of a partition, one is then left with two options: consistency or availability. When choosing consistency over availability, the system will return an error or a time out if particular information cannot be guaranteed to be up to date due to network partitioning. When choosing availability over consistency, the system will always process the query and try to return the most recent available version of the information, even if it cannot guarantee it is up to date due to network partitioning.
CAP is frequently misunderstood as if one had to choose to abandon one of the three guarantees at all times. In fact, the choice is really between consistency and availability for when a partition happens only; at all other times, no trade-off has to be made.
A class encapsulates both data members and member functions, while a structure generally encapsulates only data possibly of different types. 
1. default access specifier of members of a class is private while for structure it is public.
2.while deriving a struct from a struct/class, default access specifier is public but while deriving a class from another class,default access specifier is private.
When we use the same function name in both the base and derived classes, the function in the base class is declared as virtual using the virtual keyword preceding its normal declaration.
When the function is made virtual C++ determines which function to use at run time based on the type of object pointed to by the base pointer rather than the type of the pointer.
class BC

{

public:

    virtual void show(){}

};

class DC:public BC

{

public:

   void show(){}

};

int main()

{

  BC base;DC derived;

  BC *bptr;

  bptr=&base;

  bptr->show();//base class

  bptr=&derived;

  bptr->show();//derived class

  return 0;

}
if virtual keyword was not used here, base pointer, even when it is made to contain the address of a derived class, always executes function in the base class.
In this way we achieve RUN TIME POLYMORPHISM in C++ because depending on the type of object pointed to by the base pointer, we can execute various forms of the same function that is declared virtual in the base class.
Link State Routing is an Intra-domain Routing Protocol ie it is used for routing within an autonomous system.
An autonomous system is a collection of networks or routers working under single administration.
In this protocol, each node of the network maintains entire topology of the network. To update the routing table ie for the formation of shortest path tree for each node, Dijkstra Algorithm is used which is a greedy single source shortest path algorithm.
Principle of LSR:- Tell to everyone what you know about your neighbors.
Moreover, It also uses flooding of LSR Packets for exchange of information.
Open Shortest Path First (OSPF) is an implementation of Link State Routing Protocol.
A set of processes is in a deadlocked state when every process in the set is waiting for resource(s)  that is held by another process in the set.
A deadlock occurs if following four conditions hold simultaneously:
1. mutual exclusion
2. Hold and wait
3. No Preemption
4. Circular Wait.
There are three ways to handle deadlock1) Deadlock prevention or avoidance: The idea is to not let the system into deadlock state.
2) Deadlock detection and recovery: Let deadlock occur, then do preemption to handle it once occurred.
3) Ignore the problem all together: If deadlock is very rare, then let it happen and reboot the system. This is the approach that both Windows and UNIX take.
In deadlock prevention, we ensure that atleast one of the necessary conditions cannot hold.
In deadlock avoidance, we require additional information about how resources are to be requested.We can avoid deadlock by using:-
1. For single instance of each resource type :-Resource-Allocation-Graph Algorithm
2. For multiple instances of resource types:-BANKER'S ALGORITHM

Weekly


Monthly


Overall

Error
Content Related Issue
Software Related Issue