A hash table.docx
A hash table.docx
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.
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.
Operations
Initialize Hash Table: Let's say we have a hash table with 10 buckets (array of size 10).
Insertion:
hash(15) = 15 % 10 = 5.
Collision! Use chaining to handle the collision and store ("banana") in a linked list at index 5.
Index: 0 1 2 3 4 5 6 7 8 9
Search:
hash(15) = 15 % 10 = 5.
hash(25) = 25 % 10 = 5.
Deletion:
hash(15) = 15 % 10 = 5.
Index: 0 1 2 3 4 5 6 7 8 9
[ ] [ ] [ ] [ ] [ ] [ (25,"banana") ] [ ] [ ] [ ] [ ]
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.
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.
Structure:
Index: 0 1 2 3 4 5 6 7 8 9
[ ] [ ] [ ] [ ] [ ] ["apple"] ["banana"] [ ] [ ] [ ]
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.
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.
4. Priority Queue: A collection of elements where each element has a priority, and
elements are dequeued based on priority.
6. Map (or Dictionary): A collection of key-value pairs where each key is unique.
Stack Interface
interface Stack {
Object pop();
Object peek();
boolean isEmpty();
}
Stack Implementation (Array-Based)
top = -1;
@Override
if (top == elements.length - 1) {
elements[++top] = item;
@Override
if (isEmpty()) {
return elements[top--];
}
@Override
if (isEmpty()) {
return elements[top];
@Override
● 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.
Given an array, the task is to cyclically rotate the array clockwise by one time.
Examples:
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}
arr[0] = 5
arr[ ] = {5, 1, 2, 3, 4}
Time Complexity: O(n), as we need to iterate through all the elements. Where n is
the number of elements in the array.
Output: 7
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.
arr2[] = {2, 3, 5, 6}
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
To find union of two sorted arrays using two pointers, follow the following
procedure:
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
To find intersection of two sorted arrays using two-pointers, follow the below
approach:
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:
Output: 7
Initialize:
max_so_far = INT_MIN
max_ending_here = 0
max_so_far = max_ending_here
return max_so_far
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
a. Functional 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
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
a.x(g,h);
a. a [ “x” ] ( g , h );
c. x( g&&h );
d. a (x )[ “g” , “h” ];
<p id="demo"></p>
<script>
var js = 10;
js *= 5;
document.getElementById("demo").innerHTML = js;
</script>
a) 10
b) 50
c) 5
d) Error
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
function sanfoundry(javascript)
{
return (javascript ? “yes” : “no”);
}
bool ans=true;
console.log(sanfoundry(ans));
a) Compilation error
b) Runtime error
c) Yes
d) No
<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
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
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
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
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.
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
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
<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
<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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
push(20);
push(4);
top();
pop();
pop();
push(5);
top();
a) 20
b) 4
c) stack underflow
d) 5
27) The data structure required for Breadth First Traversal on a graph is?
a) Stack
b) Array
c) Queue
d) Tree
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
35) What does the following function do for a given Linked List with first node as head?
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)
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)
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
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
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
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
}
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
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
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
}
}
}
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)
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