[go: up one dir, main page]

0% found this document useful (0 votes)
30 views42 pages

A hash table.docx

Uploaded by

Sudhanshu Chand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views42 pages

A hash table.docx

Uploaded by

Sudhanshu Chand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

A hash table (or hash map) is a data structure that implements an associative array

abstract data type, a structure that can map keys to values. It uses a hash function to compute
an index (also called a hash code) into an array of buckets or slots, from which the desired value
can be found.

Key Concepts of Hash Table

Hash Function: A function that takes a key and computes an index in the array. The goal of a
hash function is to distribute the keys uniformly across the buckets.

Buckets: Array elements where values are stored. Each bucket can store multiple key-value pairs
in case of collisions.

Collisions: When two keys hash to the same index. There are strategies to handle collisions, such
as chaining and open addressing.

Components of Hash Table

Array: The underlying data structure that stores the data.

Hash Function: Maps keys to indexes in the array.

Buckets: Each index of the array may contain multiple entries.

Operations

Insertion: Add a new key-value pair to the hash table.

Deletion: Remove a key-value pair from the hash table.

Search: Retrieve the value associated with a given key.

Step-by-Step Hash Table Example

Initialize Hash Table: Let's say we have a hash table with 10 buckets (array of size 10).

Hash Function: Assume a simple hash function hash(key) = key % 10.

Insertion:

Insert (15, "apple"):

hash(15) = 15 % 10 = 5.

Store ("apple") at index 5.

Insert (25, "banana"):


hash(25) = 25 % 10 = 5.

Collision! Use chaining to handle the collision and store ("banana") in a linked list at index 5.

Structure After Insertion:

Index: 0 1 2 3 4 5 6 7 8 9

[ ] [ ] [ ] [ ] [ ] [ (15,"apple") -> (25,"banana") ] [ ] [ ] [ ] [ ]

Search:

Search for key 15:

hash(15) = 15 % 10 = 5.

Look at index 5 and find (15, "apple").

Search for key 25:

hash(25) = 25 % 10 = 5.

Look at index 5 and traverse the list to find (25, "banana").

Deletion:

Delete key 15:

hash(15) = 15 % 10 = 5.

Look at index 5, find and remove (15, "apple").

Structure after deletion:

Index: 0 1 2 3 4 5 6 7 8 9

[ ] [ ] [ ] [ ] [ ] [ (25,"banana") ] [ ] [ ] [ ] [ ]

Collision Resolution Strategies

Chaining:

● Each bucket points to a linked list of entries that hash to the same index.
● Simple to implement but requires additional memory for pointers.

Open Addressing: All elements are stored in the array itself.

Methods include:
● Linear Probing: If a slot is occupied, check the next slot.
● Quadratic Probing: Check slots with a quadratic function (e.g., i^2 slots away).
● Double Hashing: Use a second hash function to determine the step size for probing.

Example of Open Addressing (Linear Probing)

Insert (15, "apple"):

hash(15) = 5. Index 5 is empty, so insert there.

Insert (25, "banana"):

hash(25) = 5. Index 5 is occupied. Check index 6.

Index 6 is empty, so insert there.

Structure:

Index: 0 1 2 3 4 5 6 7 8 9

[ ] [ ] [ ] [ ] [ ] ["apple"] ["banana"] [ ] [ ] [ ]

Advantages and Disadvantages

Advantages:

● Fast average-case time complexity for search, insert, and delete operations (O(1)).
● Efficiently handles large datasets.

Disadvantages:

● Performance degrades with high load factors (ratio of number of elements to number of
buckets).
● Requires a good hash function to distribute keys uniformly.
● Collisions can affect performance.

An abstract data type (ADT) is a model for a data structure that defines the type of data it
can store, the operations that can be performed on the data, and the behavior of these operations.
An ADT specifies what operations are to be performed but not how these operations will be
implemented. It provides a clear interface and hides the implementation details from the user.

Key Concepts of Abstract Data Types

Abstraction: ADTs abstract away the implementation details, allowing users to focus on the
operations they can perform without worrying about the underlying data structures or algorithms.
Encapsulation: ADTs encapsulate data and operations together. The data is hidden from the user
and can only be accessed or modified through the defined operations.

Interface: The set of operations defined by an ADT forms its interface. This interface is
independent of any specific implementation, allowing different implementations to provide the
same functionality.

Common Abstract Data Types

1. List: A collection of elements with a specific order.

Operations: Insert, delete, retrieve, iterate.

2. Stack: A collection of elements with last-in, first-out (LIFO) access.

Operations: Push, pop, peek, isEmpty.

3. Queue: A collection of elements with first-in, first-out (FIFO) access.

Operations: Enqueue, dequeue, peek, isEmpty.

4. Priority Queue: A collection of elements where each element has a priority, and
elements are dequeued based on priority.

Operations: Insert, extractMin (or extractMax), peek.

5. Set: A collection of unique elements.

Operations: Add, remove, contains, union, intersection.

6. Map (or Dictionary): A collection of key-value pairs where each key is unique.

Operations: Put, get, remove, containsKey.

Stack Interface

interface Stack {

void push(Object item);

Object pop();

Object peek();

boolean isEmpty();

}
Stack Implementation (Array-Based)

class ArrayStack implements Stack {

private Object[] elements;

private int top;

public ArrayStack(int capacity) {

elements = new Object[capacity];

top = -1;

@Override

public void push(Object item) {

if (top == elements.length - 1) {

throw new IllegalStateException("Stack is full");

elements[++top] = item;

@Override

public Object pop() {

if (isEmpty()) {

throw new IllegalStateException("Stack is empty");

return elements[top--];

}
@Override

public Object peek() {

if (isEmpty()) {

throw new IllegalStateException("Stack is empty");

return elements[top];

@Override

public boolean isEmpty() {

return top == -1;

Advantages of Abstract Data Types

● Modularity: ADTs promote modular design by separating the interface from the
implementation.
● Reusability: The same ADT can be reused with different implementations.
● Maintainability: Changes to the implementation do not affect the users of the
ADT as long as the interface remains unchanged.
● Abstraction: Users can work with complex data structures without understanding
their implementation details.

CYCLICALLY ROTATE AN ARRAY BY ONE

Given an array, the task is to cyclically rotate the array clockwise by one time.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}

Output: arr[] = {5, 1, 2, 3, 4}


Initialize last element in variable ‘last_el’ that is 5

Then, iterate from n-1 to 1 and assign arr[i] = arr[i-1]

arr[4] = arr[3]

arr[ ] = {1, 2, 3, 4, 4}

arr[3] = arr[2]

arr[ ] = {1, 2, 3, 3, 4}

arr[2] = arr[1]

arr[ ] = {1, 2, 2, 3, 4}

arr[1] = arr[0]

arr[ ] = {1, 1, 2, 3, 4}

Assign arr[0] = last_el

arr[0] = 5

arr[ ] = {5, 1, 2, 3, 4}

Thus the required array will be {5, 1, 2, 3, 4}

Follow the steps to solve the problem:

Store the last element in any temp variable

Shift every element one position ahead

Assign first value = last value (stored in temp variable).

Time Complexity: O(n), as we need to iterate through all the elements. Where n is
the number of elements in the array.

Auxiliary Space: O(1), as we are using constant space.

7. K’th Smallest Element in Unsorted Array

Given an array arr[] of N distinct elements and a number K, where K is smaller


than the size of the array. Find the K’th smallest element in the given array.
Examples:

Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3

Output: 7

Approaches to find K’th smallest element in unsorted array

Naive Approach Using Sorting – O (n log(n)) time and O(1) auxiliary space: The
very basic approach is to sort the given array and return the element at the index

K – 1.

Expected Approach Using Priority Queue (Max-Heap) – O(N * log(K)) time and
O(K) auxiliary space:

The intuition behind this approach is to maintain a max heap (priority queue) of
size K while iterating through the array. Doing this ensures that the max heap
always contains the K smallest elements encountered so far. If the size of the max
heap exceeds K, remove the largest element this step ensures that the heap
maintains the K smallest elements encountered so far. In the end, the max heap’s top
element will be the Kth smallest element.

Using Counting Sort (Not efficient for large range of elements)

8. Union and Intersection of two sorted arrays

Given two sorted arrays, find their union and intersection.

Example: arr1[] = {1, 3, 4, 5, 7}

arr2[] = {2, 3, 5, 6}

Output: Union : {1, 2, 3, 4, 5, 6, 7}

Intersection : {3, 5}

● Union of Two-Sorted Arrays using Sets: The idea of the approach is to build
a Set and insert all the elements from both arrays into it. As a set stores only
unique values, it will only keep all the unique values of both arrays.

Time Complexity: O(m*log(m) + n*log(n)), where ‘m’ and ‘n’ are the size of
the arrays

Auxiliary Space: O(m + n)


● Union of Two-Sorted Arrays using Two-Pointers

To find union of two sorted arrays using two pointers, follow the following
procedure:

a) Use two index variables i and j, initial values i = 0, j = 0


b) If arr1[i] is smaller than arr2[j] then print arr1[i] and increment i.
c) If arr1[i] is greater than arr2[j] then print arr2[j] and increment j.
d) If both are same then print any of them and increment both i and j.
e) Print remaining elements of the larger array.

Time Complexity : O(m + n) Auxiliary Space: O(1)

● Intersection of Two-Sorted Arrays using Sets:

The idea is to add elements of first array in a set. Then, iterate through the
second array and check for each element whether it exists in the set. If an
element is present in set, it means the element is present in both arrays and
the element is added to the output, and its occurrence in the set is removed to
avoid duplicates in the output.

Time Complexity: O(m*log(m) + n*log(n)), where ‘m’ and ‘n’ are the size of
the arrays

Auxiliary Space: O(m + n)

Intersection of Two-Sorted Arrays using Two-Pointers:

To find intersection of two sorted arrays using two-pointers, follow the below
approach:

a) Use two index variables i and j, initial values i = 0, j = 0


b) If arr1[i] is smaller than arr2[j] then increment i.
c) If arr1[i] is greater than arr2[j] then increment j.
d) If both are same then print any of them and increment both i
and j.

Time Complexity : O(m + n) Auxiliary Space: O(1)


● Largest Sum Contiguous Subarray (Kadane’s Algorithm)

Given an array arr[] of size N. The task is to find the sum of the contiguous
subarray within a arr[] with the largest sum.

Example:

Input: arr = {-2,-3,4,-1,-2,1,5,-3}

Output: 7

Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7.

The idea of Kadane’s algorithm is to maintain a variable max_ending_here


that stores the maximum sum contiguous subarray ending at current index
and a variable max_so_far stores the maximum sum of contiguous subarray
found so far, Everytime there is a positive-sum value in max_ending_here
compare it with max_so_far and update max_so_far if it is greater than
max_so_far.

Time Complexity: O(N) Auxiliary Space: O(1)

● Maximum Product Subarray

Follow the below steps to solve the problem:

o Run a nested for loop to generate every subarray


▪ Calculate the product of elements in the current subarray
o Return the maximum of these products calculated from the subarrays

Time Complexity: O(N2) Auxiliary Space: O(1)

Maximum Product Subarray using Kadane’s Algorithm :


Follow the below steps to solve the problem:

a) Use 3 variables, max_so_far, max_ending_here &


min_ending_here
b) For every index, the maximum number ending at that index
will be the maximum(arr[i], max_ending_here * arr[i],
min_ending_here[i]*arr[i])
c) Similarly, the minimum number ending here will be the
minimum of these 3
d) Thus we get the final value for the maximum product subarray

Time Complexity: O(N) Auxiliary Space: O(1)

Pseudocode of Kadane’s algorithm:

Initialize:

max_so_far = INT_MIN

max_ending_here = 0

Loop for each element of the array

(a) max_ending_here = max_ending_here + a[i]

(b) if(max_so_far < max_ending_here)

max_so_far = max_ending_here

(c) if(max_ending_here < 0)


max_ending_here = 0

return max_so_far

MCQs on JavaScript Language


1) The ” var” and “function” are known as _____________.

a. Data types

b. Keywords

c. Prototypes

d. Declaration statements

2) Which of these is the correct way in which we can call the JavaScript code?

a. Triggering Event

b. Preprocessor

c. Function/Method

d. RMI

3) Which of these functions of the Number Object would format a number with
different numbers of digits to the decimal’s right?

a. toFixed()

b. toExponential()

c. toLocaleString()

d. toPrecision()

4) Out of the following functions of the string object, which one would return the
character in any string via the specified number of characters starting at a
specified position?

a. search()

b. substr()

c. split()
d. slice()

5) Look at the snippets given below and check the one in which the variable “a”
isn’t equal to the “NULL”.

a. if (a!)

b. if(a!=null)

c. if(a!==null)

d. if(a!null)

6) In JavaScript, what do we use for calling the expression for function definition?

a. Function literal

b. Function prototype

c. Function declaration

d. Function calling

7) Which of these is used in JavaScript for calling a method or a function?

a. Functional Expression

b. Property Access Expression

c. Primary Expression

d. Invocation Expression

8) Which of these operators are used for checking if a specific property exists?

a. in

b. within

c. exist

d. exists

9) “The expression that can appear legally on an assignment expression’s left


side” is a common explanation for variables, elements of arrays, and properties
of objects. These are known as __________:

a. Prototypes
b. Properties

c. Lvalue

d. Definition

10) Which of these is a correct output for the JavaScript code given below?

string X= “Hey”;

string Y=”There”;

alert(X+Y);

a. Hey There

b. Hey_There

c. HeyThere

d. undefined

11) In case a value of an operator is NULL, then the unary operator would return
the ____________ typeof.

a. object

b. boolean

c. string

d. undefined

12)In the line of code given below, what will the “datatype” written in brackets be
called? article[datatype]=assignment_value;

a. An object

b. A String

c. Floating point

d. An integer

13)In the line of code given below, the prototype represents the _____________.

functionx(){};

a. Prototype of a function
b. Function x

c. Not valid

d. A custom constructor

14)A function’s execution would stop whenever a program control would encounter
the _________ statement in the function’s body.

a. goto statement

b. break statement

c. continue statement

d. return statement

15) Which of these codes is equivalent to the code given below?

a.x(g,h);

a. a [ “x” ] ( g , h );

b. x (g) &&a.x (h);

c. x( g&&h );

d. a (x )[ “g” , “h” ];

16) What will be the output of the following JavaScript code?

<p id="demo"></p>
<script>
var js = 10;
js *= 5;
document.getElementById("demo").innerHTML = js;
</script>

a) 10
b) 50
c) 5
d) Error

17) Will the following JavaScript code work?

var js = (function(x) {return x*x;}(10));


a) Exception will be thrown
b) Memory leak
c) Error
d) Yes, perfectly

18) Where is Client-side JavaScript code is embedded within HTML documents?


a) A URL that uses the special javascript:code
b) A URL that uses the special javascript:protocol
c) A URL that uses the special javascript:encoding
d) A URL that uses the special javascript:stack

19) Which of the following object is the main entry point to all client-side JavaScript
features and APIs?
a) Position
b) Window
c) Standard
d) Location

20) What will be the output of the following JavaScript program?

function sanfoundry(javascript)
{
return (javascript ? “yes” : “no”);
}
bool ans=true;
console.log(sanfoundry(ans));
a) Compilation error
b) Runtime error
c) Yes
d) No

21) What will be the output of the following JavaScript function?

<p id="demo"></p>
<script>
function javascript()
{
// javacript abs() method
document.getElementById("demo").innerHTML = Math.abs(-7.25);
}
</script>
a) -7.25
b) 7.25
c) -7
d) 7

22) Which of the following explains correctly what happens when a JavaScript program is
developed on a Unix Machine?
a) will work perfectly well on a Windows Machine
b) will be displayed as JavaScript text on the browser
c) will throw errors and exceptions
d) must be restricted to a Unix Machine only

23) Which is a more efficient JavaScript code snippet?


Code 1 : // for loop in javascript

for(var num=10;num>=1;num--)
{
document.writeln(num);
}
Code 2 :

var num=10;
while(num>=1)
{
document.writeln(num);
num++;
}
a) Code 1
b) Code 2
c) Both Code 1 and Code 2
d) Cannot Compare

24) What will be the output of the following JavaScript code?

function printArray(a)
{
var len = a.length, i = 0;
if (len == 0)
console.log("Empty Array");
else
{
// do-while loop in javascript
do
{
console.log(a[i]);
} while (++i < len);
}
}
a) Prints “Empty Array”
b) Prints 0 to the length of the array
c) Prints the numbers in the array in order
d) Prints the numbers in the array in the reverse order

25) Which of the following scoping type does JavaScript use?


a) Sequential
b) Segmental
c) Lexical
d) Literal

26) What will be the function of the following JavaScript program?

var scope = "js scope";


function checkscope()
{
var scope = "javascript scope";
function f()
{
return scope;
}
return f;
}
a) Returns the value in scope
b) Returns value null
c) Shows an error message
d) Returns exception

27) What will be the result or type of error if p is not defined in the following JavaScript
code snippet?

console.log(p)
a) Value not found Error
b) Reference Error
c) Null
d) Zero

27) Why event handlers is needed in JS?


a) Allows JavaScript code to alter the behaviour of windows
b) Adds innerHTML page to the code
c) Change the server location
d) Performs handling of exceptions and occurrences

28) What will be the firstname and surname of the following JavaScript program?

var book = {
"main title": "JavaScript",
'sub-title': "The Definitive Guide",
"for": "all audiences",
author: {
firstname: "David",
surname: "Flanagan"
}
};
a) objects
b) property names
c) properties
d) property values

28) Consider the following JavaScript statement containing regular expressions and
check if the pattern matches.

var text = "testing: 1, 2, 3";


var pattern = /d+/g;
a) text.check(pattern)
b) pattern.test(text)
c) text==pattern
d) text.equals(pattern)

29) Where Client-side JavaScript code is embedded within HTML documents?


a) A URL that uses the special javascript:code
b) A URL that uses the special javascript:protocol
c) A URL that uses the special javascript:encoding
d) A URL that uses the special javascript:stack

30) Which of the following object is the main entry point to all client-side JavaScript features
and APIs?
a) Position
b) Window
c) Standard
d) Location

31) Which of the following can be used to call a JavaScript Code Snippet?
a) Function/Method
b) Preprocessor
c) Triggering Event
d) RMI

32) Which of the following is a way of embedding Client-side JavaScript code within
HTML documents?
a) From javascript:encoding
b) External file specified by the src attribute of a “script” tag
c) By using a header tag
d) By using body tag

33) Which character in JavaScript code will be interpreted as XML markup?


a) !
b) >
c) &
d) .

34) What is the code for getting the current time?


a) now = new Date();
b) var now = new Date();
c) var now = Date();
d) var now = new Date(current);

35) One of the main advantage of using src attribute is ____________


a) It becomes self-cached
b) It makes the HTML file modular
c) It restricts manipulation in the HTML file
d) It simplifies the HTML files

36) What will be done if more than one page requires a file of JavaScript code?
a) Downloads that many times
b) Retrives from the browser cache
c) Must be re executed
d) Must be included in all the pages

37) What will be the output of the following JavaScript code?

<p id="demo"></p>
<script>
var numbers1 = [4, 9];
var numbers2 = numbers1.map(myFunction);
document.getElementById("demo").innerHTML = numbers2;
function myFunction(value, index, array)
{
return value * 2;
}
</script>

a) 8 9
b) 8 18
c) 4 9
d) Error

38) What will be the output of the following JavaScript code?

<p id="demo"></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var arr= numbers.every(myFunction);
document.getElementById("demo").innerHTML =arr;
function myFunction(value, index, array)
{
return value > 18;
}
</script>

a) true
b) false
c) 0
d) error

39) What are the properties supporting CSS styles for a document element?
a) style and font
b) style and className
c) size and style
d) className and font

40) What is the purpose of the event handlers in the JavaScript?


a) Adds innerHTML page to the code
b) Performs handling of exceptions and occurrences
c) Allows JavaScript code to alter the behaviour of windows
d) Change the server location

41) Which handler is triggered when the content of the document in the window is stable
and ready for manipulation?
a) onload
b) manipulate
c) create
d) onkeypress

42) What is the JavaScript code snippet to find all container elements with class
“reveal”?
a) var elements = document.getElementsByClassName(“reveal”);
b) var elements = document.getElementByClassName(“reveal”);
c) var elements = document.getElementByName(“reveal”);
d) var elements = document.getElementsClassName(“reveal”);

43) What is the JavaScript code snippet to update the content of the timestamp element
when the user clicks on it?
a) timestamp.onLoad = function() { this.innerHTML = new Date().toString(); }
b) timestamp.onclick = function() { this.innerHTML = new Date().toString(); }
c) timestamp.onload = function() { this.innerHTML = new Date().toString(); }
d) timestamp.onclick = function() { innerHTML = new Date().toString(); }
44) Which syntax is used to describe elements in CSS?
a) Protectors
b) Selectors
c) Both Protectors and Selectors
d) Protectors or Selectors

45) Which of the following is the ultimate element selection method?


a) querySelectorAll()
b) querySelector()
c) queryAll()
d) query()

46) Which of the following is the default positioning elements with CSS?
a) relative
b) static
c) absolute
d) fixed

47) . Which property lays the element according to the normal flow?
a) relative
b) absolute
c) fixed
d) static

48) What will be the output of the following JavaScript code?

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>
<script>
function myFunction()
{
var str = "a,b,c,d,e,f";
var arr = str.split(",");
document.getElementById("demo").innerHTML = arr[3];
}
</script>

a) d
b) a
c) b
d) c

49) A JavaScript program can traverse and manipulate document content through
__________
a) Element Object
b) Document Object
c) Both Element and Document Object
d) Data object

50) The service(s) that enables networking through scripted HTTP requests is
__________
a) XMLHttpResponse
b) XMLRequest
c) XMLHttpRequest
d) XMLHttps

51) Which of the following communicates with server-side CGI scripts through HTML
form submissions and can be written without the use of JavaScript?
a) Static Web Pages
b) Interactive Web Pages
c) Conditional Web Pages
d) All web pages

52) Which is not a form of client-side storage?


a) Web Databases
b) FileSystem API
c) Offline Web Applications
d) Online Web Applications

53) The localStorage and sessionStorage belongs to ___________


a) Window object
b) Element object
c) Hash object
d) DOM object

54) What is the lifetime of the data stored through localStorage?


a) Permanent
b) Temporary
c) Both Permanent and Temporary at times
d) Cannot store

55) Which is the function used to store a value?


a) setItem()
b) set()
c) storeItem()
d) store()

56) What is the purpose of the canvas element?


a) Creates drawing surface
b) Exposes powerful drawing API to client-side JavaScript
c) Creates drawing surface & Exposes powerful drawing API to client-side JavaScript
d) Creates a rectangular box
57) Which method is used to obtain the “drawing context” object?
a) getContext()
b) getObject()
c) get()
d) getDrawing()

58) How does SVG describe complex shapes?


a) Path of lines
b) Path of curves
c) Path of lines and curves
d) Planes

59) How do you restore a saved coordinate system?


a) restore()
b) getback()
c) set()
d) back()

60) Why is the total size of the page important?


a) Time taken to download
b) Size of IP packet should be less than 65500
c) Size of IP packet should be less than 65535
d) Size of IP packet should be greater than 65500

61) Which layer is used to control the communication between the hardware in the
network?
a) Network Access Layer
b) Internet Layer
c) Transport Layer
d) Presentation Layer

62) What is React.js?


a) Open-source JavaScript back-end library
b) JavaScript front-end library to create a database
c) Free and open-source JavaScript front-end library
d) None of the mentioned

63) React.js is written in which of the following language?


a) C
b) C++
c) JavaScript
d) Java

64) In which of the following directory React Components are saved?


a) Inside js/components/
b) Inside components/js/
c) Inside vendor/js/components/
d) Inside vendor/components/
65) In which condition is the React.js Lifecycle method static
getDerivedSateFromProps(props, state) is called?
a) When the state of the component is updated
b) When a component is created for the first time
c) Both of the mentioned
d) None of the mentioned

66) Which of the following is method is not a part of ReactDOM?


a) ReactDOM.hydrate()
b) ReactDOM.destroy()
c) ReactDOM.createPortal()
d) All of the mentioned

67) Which of the following is used to pass data to a component from outside in React?
a) props
b) render with arguments
c) setState
d) PropTypes

68) Which of the following class in Bootstrap is used to provide a responsive fixed width
container?
a) .container-fixed
b) .container-fluid
c) .container
d) All of the above

69) Which of the following class in Bootstrap is used to create a dropdown menu?
a) .dropdown
b) .select
c) .select-list
d) None of the above

70) Which of the following bootstrap styles can be used to create a default progress bar?
a) .nav-progress
b) .link-progress-bar
c) .progress, .progress-bar
d) All of the mentioned

71) Which plugin is used to cycle through elements, like a slideshow?


a) Carousel Plugin
b) Modal Plugin
c) Tooltip Plugin
d) None of the mentioned

72) Which of the following is correct about the data-animation Data attribute of the
Popover Plugin?
a) Gives the popover a CSS fade transition
b) Inserts the popover with HTML
c) Indicates how the popover should be positioned
d) Assigns delegated tasks to the designated targets

73) The content must be placed within ________ in Bootstrap.


a) Rows
b) Containers
c) Columns
d) None of the mentioned

74) Which of the following is the default size of H3 bootstrap heading?


a) 12px
b) 24px
c) 36px
d) 48px

75) Which of the following statement is true for AngularJS?


a) AngularJS is a closed-source front-end web framework
b) AngularJS is an open-source front-end web framework
c) AngularJS is an open-source backend web framework
d) AngularJS is a closed-source back-end web framework

76) Which of the following is the correct syntax for writing AngularJS expressions?
a) {{expression}}
b) {{expression | filter1 | filter2 | …}}
c) Both of the mentioned
d) None of the mentioned

77) Which of the following directives is used to start an angularJS application?


a) ng-repeat
b) ng-init
c) ng-app
d) ng-model

78) . AngularJS expressions bind AngularJS data to HTML like which of the following
directive?
a) ng-repeat
b) ng-bind
c) ng-app
d) ng-model

79) Which of the following statement is correct about data binding in AngularJS?
a) Automatic synchronization of data between model and view components
b) Automatic synchronization of data between model and controller components
c) Technique to save html data in the database
d) Technique to bind database data to html control

80) Which of the following is an advantage of AngularJS?


a) Uses dependency injection and makes use of separation of concerns
b) Code is unit-testable
c) Provides reusable components
d) All of the mentioned

81) Which of the following is a stateless protocol?


a) HTML
b) XHTML
c) HTTP
d) XML

82) What does the value 2 of the WebSocket attribute Socket.readyState indicate?
a) Closed connection
b) Handshake connection
c) Unestablished connection
d) Established connection and communication is possible

83) Which method is used to close the WebSocket?


a) Socket.flush()
b) Socket.close()
c) Socket.Close()
d) Socket.dispose()

84) What does the following JavaScript code snippet do?

var httpserver = new http.Server();

a) Create an HTTP Server


b) Create HTTP Connection between Client and Server
c) HTTP Server & Connection
d) Create a connection between two servers

Data Structure MCQ

1) What is a data structure?


a) A programming language
b) A collection of algorithms
c) A way to store and organize data
d) A type of computer hardware

2) What are the disadvantages of arrays?


a) Index value of an array can be negative
b) Elements are sequentially accessed
c) Data structure like queue or stack cannot be implemented
d) There are chances of wastage of memory space if elements inserted in an array
are lesser than the allocated size

3) Which data structure is used for implementing recursion?


a) Stack
b) Queue
c) List
d) Array

4) The data structure required to check whether an expression contains a balanced


parenthesis is?
a) Queue
b) Stack
c) Tree
d) Array

5) What is the value of the postfix expression 6 3 2 4 + – *?


a) 74
b) -18
c) 22
d) 40

6) The data structure required for Breadth First Traversal on a graph is?
a) Array
b) Stack
c) Tree
d) Queue

7) Which of the following points is/are not true about Linked List data structure when it is
compared with an array?
a) Random access is not allowed in a typical implementation of Linked Lists
b) Access of elements in linked list takes less time than compared to arrays
c) Arrays have better cache locality that can make them better in terms of
performance
d) It is easy to insert and delete elements in Linked List

8) What is a bit array?


a) Data structure that compactly stores bits
b) Data structure for representing arrays of records
c) Array in which elements are not present in continuous locations
d) An array in which most of the elements have the same value

9) Which of the following tree data structures is not a balanced binary tree?
a) Splay tree
b) B-tree
c) AVL tree
d) Red-black tree

10) Which algorithm is used in the top tree data structure?


a) Backtracking
b) Divide and Conquer
c) Branch
d) Greedy
11) Which of the following is the most widely used external memory data structure?
a) B-tree
b) Red-black tree
c) AVL tree
d) Both AVL tree and Red-black tree

12) What will be the output of the following program?

main()
{
char str[]="san foundry";
int len = strlen(str);
int i;

for(i=0;i<len;i++)
push(str[i]); // pushes an element into stack

for(i=0;i<len;i++)
pop(); //pops an element from the stack
}

a) yrdnuof nas
b) foundry nas
c) sanfoundry
d) san foundry

13) What is an AVL tree?


a) a tree which is unbalanced and is a height balanced tree
b) a tree which is balanced and is a height balanced tree
c) a tree with atmost 3 children
d) a tree with three children

14) What is the use of the bin data structure?


a) to have efficient traversal
b) to have efficient region query
c) to have efficient deletion
d) to have efficient insertion

15) Which of the following is the simplest data structure that supports range searching?
a) AA-trees
b) K-d trees
c) Heaps
d) binary search trees
16) Which type of data structure is a ternary heap?
a) Hash
b) Array
c) Priority Stack
d) Priority Queue

17) What is a dequeue?


a) A queue implemented with both singly and doubly linked lists
b) A queue with insert/delete defined for front side of the queue
c) A queue with insert/delete defined for both front and rear ends of the queue
d) A queue implemented with a doubly linked list

18) What does the following function check for? (all necessary headers to be included
and function is called from main)

#define MAX 10
typedef struct stack
{
int top;
int item[MAX];
}stack;
int function(stack *s)
{
if(s->top == -1)
return 1;
else return 0;
}

a) full stack
b) invalid index
c) empty stack
d) infinite stack

19) What is the time complexity of pop() operation when the stack is implemented using
an array?
a) O(1)
b) O(n)
c) O(logn)
d) O(nlogn)

20) What happens when you pop from an empty stack while implementing using the
Stack ADT in Java?
a) Undefined error
b) Compiler displays a warning
c) EmptyStackException is thrown
d) NoStackException is thrown

21) Array implementation of Stack is not dynamic, which of the following statements
supports this argument?
a) space allocation for array is fixed and cannot be changed during run-time
b) user unable to give the input for stack operations
c) a runtime exception halts execution
d) improper program compilation

22) What is the best case time complexity of deleting a node in a Singly Linked list?
a) O (n)
b) O (n2)
c) O (nlogn)
d) O (1)

23) Which of the following statements are not correct with respect to Singly Linked
List(SLL) and Doubly Linked List(DLL)?
a) Complexity of Insertion and Deletion at known position is O(n) in SLL and O(1) in
DLL
b) SLL uses lesser memory per node than DLL
c) DLL has more searching power than SLL
d) Number of node fields in SLL is more than DLL

24) What is the functionality of the following piece of code?

public void display()


{ if(size == 0)
System.out.println("underflow");
else
{
Node current = first;
while(current != null)
{ System.out.println(current.getEle());
current = current.getNext();
}
}
}

a) reverse the list


b) display the list
c) display the list excluding top-of-the-stack-element
d) reverse the list excluding top-of-the-stack-element
25) Consider these functions:
push() : push an element into the stack
pop() : pop the top-of-the-stack element
top() : returns the item stored in top-of-the-stack-node
What will be the output after performing these sequence of operations

push(20);
push(4);
top();
pop();
pop();
push(5);
top();

a) 20
b) 4
c) stack underflow
d) 5

26) Minimum number of queues to implement stack is ___________


a) 3
b) 4
c) 1
d) 2

27) The data structure required for Breadth First Traversal on a graph is?
a) Stack
b) Array
c) Queue
d) Tree

28) Circular Queue is also known as ________


a) Ring Buffer
b) Square Buffer
c) Rectangle Buffer
d) Curve Buffer

29) If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a
time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC

30) A data structure in which elements can be inserted or deleted at/from both ends but
not in the middle is?
a) Queue
b) Circular queue
c) Dequeue
d) Priority queue

31) A normal queue, if implemented using an array of size MAX_SIZE, gets full when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front

32) Linked lists are not suitable for the implementation of ___________
a) Insertion sort
b) Radix sort
c) Polynomial manipulation
d) Binary search

33) Linked list is considered as an example of ___________ type of memory allocation.


a) Dynamic
b) Static
c) Compile time
d) Heap

34) Linked list data structure offers considerable saving in _____________


a) Computational Time
b) Space Utilization
c) Space Utilization and Computational Time
d) Speed Utilization

35) What does the following function do for a given Linked List with first node as head?

void fun1(struct node* head)


{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}

a) Prints all nodes of linked lists


b) Prints all nodes of linked list in reverse order
c) Prints alternate nodes of Linked List
d) Prints alternate nodes in reverse order

36) With what data structure can a priority queue be implemented?


a) Array
b) List
c) Heap
d) Tree

37) What is the time complexity to insert a node based on key in a priority queue?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

38) What is not a disadvantage of priority scheduling in operating systems?


a) A low priority process might have to wait indefinitely for the CPU
b) If the system crashes, the low priority systems may be lost permanently
c) Interrupt handling
d) Indefinite blocking

39) What is the time complexity to insert a node based on position in a priority queue?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

40) What is the functionality of the following piece of code?


public void function(Object item)
{ Node temp=new Node(item,trail);
if(isEmpty())
{ head.setNext(temp);
temp.setNext(trail);
}
else
{ Node cur=head.getNext();
while(cur.getNext()!=trail)
{ cur=cur.getNext();
}
cur.setNext(temp);
}
size++;
}

a) Insert at the front end of the dequeue


b) Insert at the rear end of the dequeue
c) Fetch the element at the rear end of the dequeue
d) Fetch the element at the front end of the dequeue
41) What are the applications of dequeue?
a) A-Steal job scheduling algorithm
b) Can be used as both stack and queue
c) To find the maximum of all sub arrays of size k
d) All of the mentioned

42) What is the time complexity of deleting from the rear end of the dequeue
implemented with a singly linked list?
a) O(nlogn)
b) O(logn)
c) O(n)
d) O(n2)

43) After performing these set of operations, what does the final list look contain?

InsertFront(10);
InsertFront(20);
InsertRear(30);
DeleteFront();
InsertRear(40);
InsertRear(10);
DeleteRear();
InsertRear(15);
display();

a) 10 30 10 15
b) 20 30 40 15
c) 20 30 40 10
d) 10 30 40 15

44) What is xor linked list?


a) uses of bitwise XOR operation to decrease storage requirements for doubly linked
lists
b) uses of bitwise XOR operation to decrease storage requirements for linked lists
c) uses of bitwise operations to decrease storage requirements for doubly linked lists
d) just another form of linked list

45) What does a xor linked list have?


a) every node stores the XOR of addresses of previous and next nodes
b) actuall memory address of next node
c) every node stores the XOR of addresses of previous and next two nodes
d) every node stores xor 0 and the current node address

46) What does first and last nodes of a xor linked lists contain ? (let address of first and
last be A and B)
a) NULL xor A and B xor NULL
b) NULL and NULL
c) A and B
d) NULL xor A and B

47) Which of the following is an advantage of XOR list?


a) Almost of debugging tools cannot follow the XOR chain, making debugging difficult
b) You need to remember the address of the previously accessed node in order to
calculate the next node’s address
c) In some contexts XOR of pointers is not defined
d) XOR list decreases the space requirement in doubly linked list

48) Free lists are used in


a) static memory allocation
b) dynamic memory allocation
c) contagious allocations
d) are used for speeding up linked list operations

49) What are implicit and explicit implementations of freelists?


a) garbage collection and new or malloc operators respectively
b) new or malloc and garbage collection respectively
c) implicit implementation is not favored
d) explicit implementation is not favored

50) What datastructures can be used in implementing a free list?


a) only linked list
b) linked list or sort trees
c) arrays
d) trees

51) What are different ways of implementing free lists and which is simple among them?
a) best fit, first fit, worst fit, simple-first fit
b) best fit, first fit, worst fit, simple-best fit
c) best fit, first fit, worst fit, simple-worst fit
d) best fit simple-best fit

52) How does implicit free lists(garbage collection) works in adding memory to free list ?
a) whichever comes last will be added to free list
b) whichever comes first will be added to free list
c) certain blocks cannot be used if there are no pointers to them and hence they can
be freed
d) makes a probabilistic guess

53) What is buddy memory management of free lists ?


a) modified version of first fit
b) buddy allocation keeps several free lists, each one holds blocks which are of one
particular size
c) modified version of best fit
d) a tree representation of free lists
54) What are the disadvantages in implementing buddy system algorithm for free lists?
a) internal fragmentation
b) it takes so much space
c) we no more have the hole lists in order of memory address, so it is difficult to
detect if 2 holes remain adjacent in memory and shall be merged into one hole
d) both a and c are correct

55) Assume there is a free list which contains nodes and is filled with a value if it is
already assigned and the value will be the size of requested block else will be 0.

z = startpoint;
while ((z < end) && \\ didn't reach end
(*z <= len)) \\ too small to satisfy request
{
assign this block
}

The above code represents what?


a) code for first fit
b) code for best fit
c) code for worst fit
d) none of the mentioned

56) How are free blocks linked together mostly and in what addressing order?
a) circular linked list and increasing addressing order
b) linked list and decreasing addressing order
c) linked list and in no addressing order
d) none of the mentioned

57) Accessing free list very frequently for wide range of addresses can lead to
a) paging
b) segmentation fault
c) memory errors
d) cache problems

58) Where does a triply linked list contains an extra pointer in comparison to a doubly
linked list?
a) Top of the node
b) Bottom of the node
c) Before the node
d) After the node

59) For which of the following purpose a top pointer can be used?
a) Storing the address of the head pointer
b) Storing the address of the previous node
c) Storing the address of the next node
d) Storing equal values on the same level

60) Which of the following is a typical declaration of a triply linked list in C?


a)

struct node
{
int data;
struct node *previous;
struct node *top;
};

b) struct node {

int data;
struct node *next;
struct node *top;
};

c)

struct node
{
int data;
struct node *next;
struct node *previous;
struct node *top;
};

d)

struct node
{
int data;
struct node *next;
struct node *previous

61) A node will be rejected while inserting if the given node is already present in a triply
linked list.
a) True
b) False

62) Which of the following is true about a triply linked list?


a) Dynamic in nature
b) Allows random access
c) Less memory wastage
d) Reverse traversing is difficult

63) Memory usage in triply linked list is higher than doubly linked list.
a) True
b) False

64) Consider the following algorithm to insert an element in a triply linked list.

insertelement(data)
{
create a node with given data.
if the linked list is empty
{
_____________
_____________
}
if the given node is less than the head
{
link the nodes through address and adjust the tail
}
if the given node is not less than the head
{
if the given node is equal to the head
{
new node is inserted on top of the head
}
else
{
traverse the linked list to find an element greater than the
node and insert in front of the node
}
}
}

Which of the following option is best suited to fill the blank?


a) initializing previous, next and top pointers to null

pointing the head and tail to the node created

b) pointing previous, next and top pointers to the node created

initializing the head and tail to null

c) initializing previous, next and top pointers to null

initializing the head and tail to null

d) pointing previous, next and top pointers to the node

65) Which among the following is the time complexity for inserting at the beginning of a
triply linked list?
a) O(n)
b) O(1)
c) O(log n)
d) O(n2)

66) What is a skip list?


a) a linkedlist with size value in nodes
b) a linkedlist that allows faster search within an ordered sequence
c) a linkedlist that allows slower search within an ordered sequence
d) a tree which is in the form of linked list

67) Consider the 2-level skip list

How to access 38?


a) travel 20-30-35-38
b) travel 20-30-40-38
c) travel 20-38
d) travel 20-40-38
68) What is the time complexity improvement of skip lists from linked lists in insertion and
deletion?
a) O(n) to O(logn) where n is number of elements
b) O(n) to O(1) where n is number of elements
c) no change
d) O(n) to O(n2) where n is number of elements

69) To which data structure are skip lists similar to in terms of time complexities in worst
and best cases?
a) balanced binary search trees
b) binary search trees
c) binary trees
d) linked lists

70) The nodes in a skip list may have many forward references. their number is
determined
a) probabilistically
b) randomly
c) sequentially
d) orthogonally

71) Are the below statements true about skiplists?


In a sorted set of elements skip lists can implement the below operations
i.given a element find closest element to the given value in the sorted set in O(logn)
ii.find the number of elements in the set whose values fall a given range in O(logn)
a) true
b) false

You might also like