Top 250 Data Structures Interview Questions and Answers
Updated 21 Jan 2025
Q1. How would you code a linked list? Show the code
A linked list is a data structure where each element contains a reference to the next element.
Create a Node class with data and next pointer
Create a LinkedList class with head pointer
Implement methods like insert, delete, search, etc.
Q2. Can an array have elements of different data types?
Yes, an array can have elements of different data types.
An array can have elements of different data types, but it's not recommended.
It can make the code harder to read and maintain.
For example, an array can have both strings and numbers: ['apple', 5, 'banana']
Q3. Difference between Stack and Queue with real time example
Stack is LIFO and Queue is FIFO data structure. Stack is like a stack of plates and Queue is like a queue of people.
Stack is Last In First Out (LIFO) and Queue is First In First Out (FIFO)
Stack is like a stack of plates where the last plate added is the first one to be removed
Queue is like a queue of people where the first person to enter is the first one to leave
Stack is used in undo-redo functionality in text editors
Queue is used in printing jobs in a printer
Q4. Validate Binary Tree Nodes Problem
You are provided with 'N' binary tree nodes labeled from 0 to N-1, where node i has two potential children, recorded in the LEFT_CHILD[i]
and RIGHT_CHILD[i]
arrays. Determine ...read more
The task is to determine if the given binary tree nodes form exactly one valid binary tree.
Check if there is only one root node (a node with no parent)
Check if each node has at most one parent
Check if there are no cycles in the tree
Check if all nodes are connected and form a single tree
Q5. What is hashmap? Where it is used? What is the time complexity to implement it?
HashMap is a data structure that stores key-value pairs and provides constant time complexity for basic operations.
HashMap is used to store and retrieve data based on unique keys.
It is commonly used in programming languages to implement associative arrays or dictionaries.
The time complexity to implement a HashMap is O(1) for basic operations like insertion, deletion, and retrieval.
Q6. find the nearest greater value of a given value in a BST
Find the nearest greater value of a given value in a Binary Search Tree (BST).
Start from the root node and compare the given value with the current node's value.
If the given value is less than the current node's value, move to the left subtree.
If the given value is greater than the current node's value, move to the right subtree.
Keep track of the closest greater value encountered while traversing the tree.
Return the closest greater value found.
Q7. Can you implement a stack using queue
Yes, we can implement a stack using two queues.
Push operation: Enqueue the element to the first queue.
Pop operation: Dequeue all elements from the first queue and enqueue them to the second queue until the last element. Dequeue and return the last element. Swap the names of the queues.
Top operation: Same as pop operation but don't dequeue the last element.
Example: Push 1, 2, 3. Queue 1: 1 2 3. Queue 2: empty. Pop operation: Dequeue 1 and 2 from queue 1 and enqueue them to que...read more
Q8. difference between graph and tree?
Graph is a non-linear data structure with cycles while tree is a hierarchical data structure without cycles.
Graph can have multiple starting points and paths between nodes while tree has only one root node and unique paths between nodes.
Graph can have cycles while tree is acyclic.
Graph can be directed or undirected while tree is always directed.
Examples of graphs include social networks, road networks, and computer networks while examples of trees include file systems, organi...read more
Data Structures Jobs
Q9. Diff btw list and array?
List is dynamic and can be modified while array is fixed in size and cannot be modified.
List can grow or shrink dynamically while array has a fixed size.
List can contain elements of different data types while array can only contain elements of the same data type.
List uses more memory than array due to its dynamic nature.
Array is faster than list for accessing elements by index.
Example: List - [1, 'hello', True], Array - [1, 2, 3]
Example: List - ['apple', 'banana', 'orange'], ...read more
Q10. 2.What is FIFO and LIFO, where you implemented this?
FIFO (First-In, First-Out) and LIFO (Last-In, First-Out) are inventory management methods.
FIFO: Oldest items are sold first, used in industries like retail and food.
LIFO: Newest items are sold first, used in industries like manufacturing and construction.
Q11. Differnce between ArrayList and LinkedList
ArrayList is implemented as a resizable array while LinkedList is implemented as a doubly linked list.
ArrayList provides constant time for accessing elements while LinkedList provides constant time for adding or removing elements.
ArrayList is better for storing and accessing data while LinkedList is better for manipulating data.
ArrayList is faster for iterating through elements while LinkedList is faster for adding or removing elements in the middle of the list.
Q12. Need a DSA Code?How apply?
To apply for a DSA Code, you need to follow a specific process.
Contact the relevant authority or organization that issues DSA Codes.
Submit the required documents and information, such as identification proof and business details.
Complete any necessary training or certification programs.
Wait for the approval of your DSA Code application.
Once approved, you will receive your DSA Code.
Q13. What data structure would you use for a dictionary?
An array of key-value pairs is the best data structure for a dictionary.
Use a hash table or a balanced tree to implement the dictionary.
Keys should be unique and immutable.
Values can be any data type.
Access time should be O(1) or O(log n) depending on the implementation.
Examples: Python's dict, Java's HashMap, C++'s unordered_map.
Q14. How to detect loop in linked list?
To detect loop in linked list, use Floyd's cycle-finding algorithm.
Create two pointers, slow and fast, and initialize both to the head of the linked list.
Move slow pointer by one node and fast pointer by two nodes.
If there is a loop, the two pointers will eventually meet.
If there is no loop, the fast pointer will reach the end of the linked list.
Time complexity: O(n), Space complexity: O(1)
Q15. Which data structure inserts and deletes in O(1) time and is it possible to create a data structure with insertion, deletion and search retrieval in O(1) time
Hash table. No, it is not possible to create a data structure with all operations in O(1) time.
Hash table uses a hash function to map keys to indices in an array.
Insertion and deletion can be done in O(1) time on average.
Search retrieval can also be done in O(1) time on average.
However, worst-case scenarios can result in O(n) time complexity.
It is not possible to create a data structure with all operations in O(1) time.
Q16. Could you implement those in code ?
Yes, I can implement those in code.
I have experience in coding and implementing various algorithms and data structures.
I am proficient in programming languages such as Java, Python, and C++.
I can provide examples of my previous coding projects upon request.
Q17. Difference between Hash Map and Linked Hash Map?
HashMap is an unordered collection while LinkedHashMap maintains insertion order.
HashMap uses hash table to store key-value pairs.
LinkedHashMap uses doubly-linked list to maintain the insertion order.
HashMap provides faster access and retrieval time complexity.
LinkedHashMap provides predictable iteration order based on insertion order.
Example: HashMap - {1=A, 2=B, 3=C}, LinkedHashMap - {1=A, 2=B, 3=C}
Q18. What would be the ideal data structure to represent people and friend relations in facebook
Graph
Use a graph data structure to represent people as nodes and friend relations as edges
Each person can be represented as a node with their unique identifier
Friend relations can be represented as directed edges between nodes
This allows for efficient traversal and retrieval of friend connections
Q19. 1.Difference between HashMap and Hashtable ?
HashMap is not synchronized and allows null values, while Hashtable is synchronized and does not allow null values.
HashMap is faster than Hashtable due to lack of synchronization.
Hashtable is thread-safe while HashMap is not.
HashMap allows null values for both key and value, while Hashtable does not.
HashMap is part of the Java Collections Framework while Hashtable is a legacy class.
HashMap uses Iterator while Hashtable uses Enumeration.
Example: HashMap
map = new HashMap<>(); ...read more
Q20. Difference between collection and map.
Collection is a group of objects while Map is a key-value pair data structure.
Collection is used to store and manipulate a group of objects.
Map is used to store and retrieve data based on key-value pairs.
Collection classes include List, Set, and Queue.
Map classes include HashMap, TreeMap, and LinkedHashMap.
Collections allow duplicate elements while Maps do not.
Example: Collection - List of names, Map - Student ID and corresponding name.
Q21. What are collections and its type?
Collections are data structures used to store multiple values of the same data type.
Types of collections in Oracle are Associative arrays, Nested tables, and Varrays.
Associative arrays are indexed by string values, Nested tables are like arrays with no fixed size, and Varrays are like arrays with a fixed size.
Collections can be used to pass multiple values to a stored procedure or function.
Q22. Whai is DSA why we use?
DSA stands for Data Structures and Algorithms. It is used to efficiently store and manipulate data in computer programs.
DSA helps in organizing and managing data effectively.
It provides efficient algorithms for searching, sorting, and manipulating data.
DSA is essential for solving complex problems and optimizing program performance.
Examples of DSA include arrays, linked lists, stacks, queues, trees, and graphs.
Q23. What is Set?
Set is a collection of unique elements with no specific order.
A set can be created using curly braces {} or the set() function.
Sets can only contain immutable objects like strings, numbers, and tuples.
Sets are useful for removing duplicates and performing mathematical operations like union and intersection.
Example: my_set = {1, 2, 3} or my_set = set([1, 2, 3])
Q24. write full and working code to sort a linked list with minimum time complexity
Sort a linked list with minimum time complexity
Use merge sort or quick sort for O(n log n) time complexity
Implement the sorting algorithm recursively
Use a temporary linked list to merge the sorted sub-lists
Consider edge cases like empty list or list with only one element
Q25. how hashset and hashmap work internally?
HashSet and HashMap are both data structures in Java that use hashing to store and retrieve elements.
HashSet uses HashMap internally to store its elements as keys with a dummy value.
HashMap uses an array of linked lists called buckets to store key-value pairs.
Both HashSet and HashMap use the hashCode() method to calculate the hash value of keys.
HashSet uses the hash value to determine the bucket where an element should be stored.
HashMap uses the hash value to determine the bu...read more
Q26. Print the level order traversal of the binary tree in the spiral form
Print the level order traversal of binary tree in spiral form
Perform level order traversal of the binary tree
Alternate the direction of traversal for each level
Use a stack to reverse the order of nodes in each level
Print the nodes in the order of traversal
Q27. What are lists and its functions?
Lists are a collection of ordered and changeable elements. They have various functions to manipulate the data.
Lists are created using square brackets []
They can contain any data type such as strings, integers, or even other lists
Functions include append(), insert(), remove(), pop(), sort(), and reverse()
Example: my_list = ['apple', 'banana', 'cherry']
Example: my_list.append('orange') adds 'orange' to the end of the list
Q28. Explain ds algorithm for tree traversal
DS algorithm for tree traversal is used to visit each node of a tree exactly once.
Depth First Search (DFS) - Preorder, Inorder, Postorder
Breadth First Search (BFS)
DFS is recursive while BFS uses a queue
Preorder - Root, Left, Right
Inorder - Left, Root, Right
Postorder - Left, Right, Root
Q29. 1. What is collection ?
A collection is a framework that provides an architecture to store and manipulate a group of objects.
Collections are used to store, retrieve, manipulate, and communicate data between objects.
They provide various data structures like lists, sets, and maps.
Collections offer methods to add, remove, and search for elements in the collection.
Examples of collections in Java include ArrayList, HashSet, and HashMap.
Q30. What is the problem with arrays?
Arrays have fixed size and can lead to memory wastage and performance issues.
Arrays have a fixed size and cannot be resized dynamically.
Inserting or deleting elements in an array can be time-consuming.
Arrays can lead to memory wastage if they are not fully utilized.
Arrays can cause performance issues if they are too large and need to be traversed frequently.
Arrays can also be prone to buffer overflow attacks.
Example: An array of size 10 is created but only 5 elements are used...read more
Q31. Tell me the key factors of store matrix
The key factors of store matrix include sales performance, inventory management, customer satisfaction, and employee productivity.
Sales performance: The store's ability to meet sales targets and generate revenue.
Inventory management: Efficient management of stock levels to ensure availability of products and minimize losses.
Customer satisfaction: Providing excellent customer service and meeting customer needs.
Employee productivity: Ensuring that employees are motivated, well-...read more
Q32. Write a code for building a heap and explain its time complexity
A code for building a heap and its time complexity
A heap is a complete binary tree where each node is greater than or equal to its children
To build a heap, start from the last non-leaf node and heapify down each node
Time complexity: O(n) for building a heap of n elements
Q33. Implement LRU cache. Write a code for this. LRU cache supports 3 operations, put(key, value) get(key) remove(key)
Implement LRU cache with put, get, and remove operations.
LRU stands for Least Recently Used.
The cache should have a maximum capacity.
When the cache is full, the least recently used item should be removed.
When an item is accessed, it should be moved to the front of the cache.
Use a doubly linked list and a hash map to implement the cache efficiently.
Q34. How does concurrent hashmap works
ConcurrentHashMap is a thread-safe implementation of the Map interface in Java.
It allows multiple threads to read and write to the map concurrently.
It uses a technique called lock striping to divide the map into segments, each with its own lock.
It provides better performance than synchronized HashMap in multi-threaded environments.
It supports atomic operations like putIfAbsent() and replace().
Q35. What is mean by FIFO, LIFO Process?
FIFO and LIFO are inventory management methods. FIFO means First In First Out and LIFO means Last In First Out.
FIFO means the first items received are the first items sold or used
LIFO means the last items received are the first items sold or used
FIFO is commonly used for perishable goods
LIFO is commonly used for non-perishable goods
FIFO results in lower inventory holding costs
LIFO results in higher inventory holding costs
Q36. What is cc.
CC can refer to several things in different contexts, such as cubic centimeters, carbon copy, credit card, etc.
CC stands for cubic centimeters, a unit of measurement for engine displacement in vehicles.
CC can also mean carbon copy, used in email communication to send a copy of a message to multiple recipients.
In finance, CC can stand for credit card.
CC can also refer to closed captioning, a feature that displays text on a screen to provide a transcription of spoken dialogue f...read more
Q37. What is dsr
DSR stands for Daily Sales Report. It is a document that summarizes the sales activities and performance of a business on a daily basis.
DSR provides insights into daily sales trends and helps in tracking sales targets.
It includes information such as total sales, number of transactions, average transaction value, and sales by product or category.
DSR is used by managers to evaluate sales performance, identify areas for improvement, and make informed business decisions.
For examp...read more
Q38. what is hashing and how will you implement?
Hashing is a process of converting data into a fixed-size numerical value called a hash code.
Hashing is used to quickly retrieve data from large datasets.
It is commonly used in data structures like hash tables and hash maps.
Hash functions should be fast, deterministic, and produce unique hash codes for different inputs.
Examples of hash functions include MD5, SHA-1, and SHA-256.
Q39. What is RPN no.
RPN stands for Reverse Polish Notation, a mathematical notation where operators follow their operands.
RPN is used in calculators and programming languages like Forth and PostScript.
In RPN, instead of using parentheses to indicate order of operations, the order is determined by the position of the operator.
For example, in RPN, the expression 3 + 4 * 5 would be written as 3 4 5 * +.
Q40. write a program to print name?
A program to print name using an array of strings.
Declare an array of strings with the name.
Assign the name to the array.
Loop through the array and print each string.
Q41. Explain Array List and List
ArrayList is a resizable array implementation of the List interface in Java.
ArrayList is a dynamic array that can grow or shrink in size.
ArrayList allows duplicate elements and maintains insertion order.
ArrayList provides random access to elements using their index.
List is an interface in Java that represents an ordered collection of elements.
List allows duplicate elements and maintains insertion order.
List provides various methods for manipulating and accessing elements.
Q42. Remove duplicates from a string
Remove duplicates from a string
Convert string to char array
Create a HashSet to store unique characters
Iterate through char array and add to HashSet
Convert HashSet back to string
Q43. Given a binary tree, build a doubly linked list for the leaves of the tree in the given order without using any extra space
The question asks to convert the leaves of a binary tree into a doubly linked list without using extra space.
Traverse the binary tree in a depth-first manner
When a leaf node is encountered, update its left and right pointers to form the doubly linked list
Keep track of the previous leaf node to update its right pointer
Return the head of the doubly linked list
Q44. Design autocomplete in IDEs
Autocomplete in IDEs helps developers write code faster by suggesting code snippets and completing code as they type.
Autocomplete should suggest code snippets based on the context of the code being written
Autocomplete should prioritize suggestions based on frequency of use
Autocomplete should also suggest variable and function names
Autocomplete should be customizable to allow for user-defined snippets and suggestions
Examples of IDEs with autocomplete include Visual Studio Code...read more
Q45. Say we have a number 1.00123456788 how will we store
The number can be stored as a floating-point data type with a precision of at least 12 digits.
Floating-point data type can store decimal numbers with a fractional part.
Precision refers to the number of digits that can be stored after the decimal point.
In this case, a precision of at least 12 digits is required to store the number 1.00123456788.
Q46. What is vertices and edges on a dag?
Vertices are nodes and edges are connections between nodes in a directed acyclic graph (DAG).
Vertices represent the tasks or operations in a DAG.
Edges represent the dependencies between tasks or operations.
Vertices can have multiple incoming edges and outgoing edges.
Edges can be weighted to represent the cost or time required to complete a task.
Examples of DAGs include data processing pipelines and task scheduling systems.
Q47. Implement a min heap using priority queue.
A min heap can be implemented using a priority queue, where the smallest element has the highest priority.
Use a priority queue data structure to implement the min heap.
Ensure that the smallest element has the highest priority.
Implement the necessary operations like insert, delete, and extract min.
Maintain the heap property by percolating up or down as needed.
Q48. Design a data structure for efficient insert(),delete(),search(), return_any_value().
Design a data structure for efficient insert(),delete(),search(), return_any_value().
Consider using a hash table or a balanced binary search tree
For return_any_value(), use a random number generator to select a value
Optimize for the most frequently used operations
Q49. What is filter formula
A filter formula is a formula used to specify criteria for filtering data in a spreadsheet or database.
Filter formulas are used to extract specific data from a larger dataset based on certain conditions.
They can be used in various applications such as Excel, Google Sheets, and SQL databases.
Filter formulas typically involve logical operators (e.g., equals, greater than, less than) and functions (e.g., COUNTIF, SUMIF) to define the filtering criteria.
For example, in Excel, the...read more
Q50. Remove duplicates in an array
Remove duplicates in an array of strings
Create a new empty array
Loop through the original array and check if the current element exists in the new array
If it doesn't exist, add it to the new array
Return the new array
Q51. XOR Query on Tree Problem
Given a tree with a root at node 0 and N vertices connected with N-1 edges, and an array QUERY
of size Q, where each element in the array represents a node in the tree. For each node i...read more
This question is about finding the XOR of all values of nodes in the sub-tree of a given node in a tree.
Read the input values for the number of test cases, number of nodes, and number of queries.
Construct the tree using the given edges.
For each query, traverse the sub-tree of the given node and calculate the XOR of all node values.
Print the XOR values for each query.
Q52. MapSum Pair Implementation
Create a data structure named 'MapSum' with the ability to perform two operations and a constructor.
Explanation:
MapSum()
: Initializes the MapSum.insert(...read more
The question asks to implement a data structure called 'MapSum' with functions to initialize, insert key-value pairs, and find the sum of values with a given prefix.
Implement a class called 'MapSum' with a constructor to initialize the data structure.
Implement the 'insert' function to insert key-value pairs into the 'MapSum'. If a key is already present, replace its value with the new one.
Implement the 'sum' function to find the sum of values whose key has a prefix equal to t...read more
Q53. How many types of graphs? Explain?
There are several types of graphs, including line, bar, pie, scatter, and area graphs.
Line graphs show trends over time.
Bar graphs compare data between different categories.
Pie graphs show proportions of a whole.
Scatter graphs show the relationship between two variables.
Area graphs show the cumulative totals over time.
Q54. What types of data
Data entry operators handle various types of data.
Numeric data (e.g. sales figures, financial data)
Textual data (e.g. customer names, addresses)
Alphanumeric data (e.g. product codes, phone numbers)
Date and time data (e.g. order dates, appointment times)
Categorical data (e.g. product categories, customer types)
Q55. Have you ever used maps
Yes, I have used maps extensively in my work as a GIS Engineer.
I have experience working with various types of maps, including topographic, thematic, and digital maps.
I have used maps to analyze spatial data and create visual representations of data.
I have also used maps to perform geocoding and geolocation tasks.
Examples of software I have used to work with maps include ArcGIS, QGIS, and Google Maps API.
Q56. how to reverse linked list
Reverse a linked list by changing the direction of the pointers.
Iterate through the list and change the direction of the pointers
Keep track of the previous, current and next nodes
Set the next pointer of the current node to the previous node
Move to the next node and repeat until the end of the list is reached
Q57. What is node?
A node is a point of connection within a network that can send, receive, or forward data packets.
Nodes can be devices such as computers, routers, switches, or servers.
Nodes can also be virtual entities such as virtual machines or containers.
Nodes can communicate with each other through various protocols such as TCP/IP or UDP.
Nodes can be organized into different topologies such as star, mesh, or ring.
Nodes can have different roles within a network such as client, server, or g...read more
Q58. Implement AVL Tree.
An AVL tree is a self-balancing binary search tree where the heights of the left and right subtrees differ by at most one.
AVL tree is a binary search tree with additional balance factor for each node.
The balance factor is the difference between the heights of the left and right subtrees.
Insertion and deletion operations in AVL tree maintain the balance factor to ensure the tree remains balanced.
Rotations are performed to balance the tree when necessary.
AVL trees provide effic...read more
Q59. Code a circular linked list
A circular linked list is a data structure where the last node points back to the first node, forming a loop.
Create a Node class with data and next pointer
Initialize the head node and set its next pointer to itself
To add a node, create a new node and set its next pointer to the head node's next pointer, then update the head node's next pointer to the new node
To traverse the circular linked list, start from the head node and continue until reaching the head node again
Q60. diff between hashtable and concurrent hash map
Hashtable is not thread-safe while ConcurrentHashmap is thread-safe.
Hashtable is a legacy class while ConcurrentHashmap is a modern class.
Hashtable uses synchronized methods while ConcurrentHashmap uses lock striping.
ConcurrentHashmap allows multiple threads to read and write concurrently.
Hashtable is slower than ConcurrentHashmap in multi-threaded environments.
Q61. Explain insertion in binary search trees
Insertion in binary search trees involves finding the appropriate position for a new node based on its value.
Start at the root node and compare the value of the new node with the current node.
If the new node's value is less than the current node, move to the left child node.
If the new node's value is greater than the current node, move to the right child node.
Repeat the comparison and movement until reaching a leaf node or a null position.
Insert the new node at the null posit...read more
Q62. detect loop or cycle in a linked list
To detect a loop in a linked list, use Floyd's Cycle Detection Algorithm.
Use two pointers, slow and fast, to traverse the linked list.
If there is a loop, the fast pointer will eventually meet the slow pointer.
Time complexity is O(n) and space complexity is O(1).
Q63. DIFFERENCE BETWEEN STRUCTURE AND LINKS
Structures are rigid bodies that support loads, while links are flexible elements that connect structures.
Structures are typically made of rigid materials like steel or concrete
Links are often made of flexible materials like cables or chains
Structures provide support and stability to a system
Links allow for movement or flexibility within a system
Example: A bridge is a structure that supports loads, while the cables connecting the bridge deck are links
Q64. How many trees are possible with two and three nodes?
Answering the question about possible trees with two and three nodes.
For two nodes, there is only one possible tree.
For three nodes, there are three possible trees.
The formula for calculating the number of possible trees with n nodes is (2n-3)!!.
The double exclamation mark represents the double factorial function.
The double factorial function is defined as n!! = n(n-2)(n-4)...(1 or 2).
Q65. How vector works internally
Vectors are dynamic arrays that allocate memory dynamically. They work by storing elements in contiguous memory locations.
Vectors allocate memory dynamically and store elements in contiguous memory locations
They can be resized dynamically as needed
Accessing elements is done using an index, similar to arrays
Inserting or deleting elements in the middle of a vector can be expensive as it requires shifting all subsequent elements
Vectors have a size and capacity, where size is the...read more
Q66. What is CPV?
CPV stands for Cost Per View. It is a metric used in advertising to measure the cost of each view or interaction with an ad.
CPV is commonly used in online video advertising campaigns.
It is calculated by dividing the total cost of the campaign by the number of views or interactions.
CPV helps advertisers understand the effectiveness and efficiency of their ad campaigns.
For example, if a campaign costs $100 and receives 1,000 views, the CPV would be $0.10 per view.
Q67. Diff b/w arraylist and linkedlist
ArrayList is resizable and uses contiguous memory while LinkedList uses nodes and is best for frequent insertions/deletions.
ArrayList is faster for accessing elements by index
LinkedList is faster for inserting/deleting elements in the middle of the list
ArrayList uses less memory than LinkedList for storing the same number of elements
LinkedList is better suited for implementing a stack or queue
Example: ArrayList
arrList = new ArrayList (); LinkedList linkedList = new LinkedList...read more
Q68. Explain hash function
A hash function is a mathematical function that converts input data of arbitrary size into a fixed-size output.
Hash functions are used to index data in hash tables.
They are also used in cryptography to securely store passwords.
Examples of hash functions include MD5, SHA-1, and SHA-256.
Q69. Let’s say you have 100,000 records and you want to delete 95,000 at a time and keep only 5 thousand. But in local memory you don’t have enough space for 95,000 records. What do you do in this case? How do you d...
read moreTo delete 95,000 records with limited local memory, use batch processing and delete in chunks.
Use batch processing to delete records in chunks
Delete records in descending order of their IDs to avoid index fragmentation
Commit the transaction after deleting each batch to avoid long-running transactions
Consider archiving the deleted records instead of permanently deleting them
Q70. Write a program to store a tree on a file. Also write code to reconstruct the tree from that file. Think of efficient techniques
Program to store and reconstruct a tree from a file with efficient techniques.
Use a recursive approach to traverse the tree and write each node to the file
Include information about the node's parent and children in the file
Use a unique identifier for each node to reconstruct the tree from the file
Use a data structure like a hash table to store the nodes and their identifiers for efficient reconstruction
Q71. How can you change stack into pointers?
Stack can be changed into pointers by creating a dynamic memory allocation using malloc() function.
Use malloc() function to allocate memory dynamically
Create a pointer variable to point to the allocated memory
Use push() and pop() functions to manipulate the stack using pointers
Q72. difference Between hashMap and concurrentHashMap ?
HashMap is not thread-safe while ConcurrentHashMap is thread-safe.
HashMap is not thread-safe and can lead to ConcurrentModificationException if modified while iterating.
ConcurrentHashMap allows concurrent modifications without the need for external synchronization.
ConcurrentHashMap uses separate locks for different segments, allowing multiple threads to read and write concurrently.
ConcurrentHashMap is more suitable for high-concurrency scenarios compared to HashMap.
Q73. What is cache
Cache is a temporary storage area that stores frequently accessed data for quick access.
Cache is used to improve the performance of a system by reducing the time it takes to access data.
It can be implemented in hardware or software.
Examples of cache include browser cache, CPU cache, and disk cache.
Cache can be volatile or non-volatile, depending on whether the data is lost when the system is powered off.
Cache can also be divided into levels, with each level having a different...read more
Q74. What's is data?
Data is information that is collected, stored, and analyzed for various purposes.
Data can be in the form of numbers, text, images, videos, etc.
Data can be structured or unstructured.
Data can be collected from various sources such as surveys, sensors, databases, etc.
Data is used for analysis, decision-making, and reporting.
Examples: customer information in a database, sales figures in a spreadsheet, medical records in a hospital system.
Q75. Rotate an array with the given number of times.
Rotate an array with given number of times.
Use a temporary array to store elements to be rotated
Loop through the original array and copy elements to the temporary array
Copy the rotated elements from the temporary array back to the original array
Q76. What is time series?
Time series is a sequence of data points collected at regular time intervals, used to analyze trends and patterns over time.
Time series data is ordered chronologically
Commonly used in forecasting future values based on past patterns
Examples include stock prices, weather data, and sales figures
Q77. What are tree traversals?
Tree traversals are methods of visiting all nodes in a tree data structure.
There are three types of tree traversals: in-order, pre-order, and post-order.
In-order traversal visits the left subtree, then the root, then the right subtree.
Pre-order traversal visits the root, then the left subtree, then the right subtree.
Post-order traversal visits the left subtree, then the right subtree, then the root.
Tree traversals are commonly used in searching and sorting algorithms.
Q78. Find lca of 2 nodes in a binary tree (write pseudocode)
The Lowest Common Ancestor (LCA) of two nodes in a binary tree is the deepest node that is a common ancestor of both nodes.
Start from the root node and traverse the tree to find the given nodes.
Store the paths from the root to each node.
Compare the paths to find the last common node, which is the LCA.
Q79. Find common ancestor of 2 nodes in a binary tree ?
Find common ancestor of 2 nodes in a binary tree
Traverse the tree from root to both nodes and store the paths
Compare the paths to find the last common node
Use recursion to traverse the tree and find the common ancestor
Q80. Represent numbers using linked list. How would you add two numbers represented in linked list form. Length of numbers can be different
Adding two numbers represented as linked lists with different lengths.
Traverse both linked lists simultaneously, adding corresponding digits and carrying over the carry.
If one list is shorter, consider the remaining digits as 0.
Create a new linked list to store the result.
Handle the case when the sum of digits exceeds 9 by carrying over the digit to the next place value.
If there is a carry after adding all digits, add an additional node to the result linked list.
Q81. What is the use of mapping
Mapping is used to visually represent spatial data and analyze relationships between different geographic features.
Mapping helps in visualizing data and identifying patterns or trends
It allows for spatial analysis and decision-making based on geographic information
Mapping is used in various industries such as urban planning, environmental management, and disaster response
GIS technology uses mapping to create interactive maps for data visualization and analysis
Q82. Find the height og a binary tree without recursion. Write code and testcases
Find height of binary tree without recursion
Use a stack to keep track of nodes
Iteratively traverse the tree and update height
Testcases: empty tree, single node tree, balanced tree, unbalanced tree
Q83. What are different types of streams
Streams are a sequence of data elements made available over time. There are different types of streams.
Byte Streams
Character Streams
Buffered Streams
Data Streams
Object Streams
Print Streams
File Streams
Network Streams
Q84. How many types of alignment?
There are three types of alignment: shaft alignment, belt alignment, and gear alignment.
Shaft alignment involves aligning the rotating shafts of machines to ensure smooth operation and prevent damage.
Belt alignment refers to aligning the belts in machines such as conveyor systems to prevent slipping and maximize efficiency.
Gear alignment involves aligning the gears in machines to ensure proper meshing and smooth transmission of power.
Q85. 0 what is frequency
Frequency is the number of cycles per second of a periodic wave.
Frequency is measured in Hertz (Hz)
It determines the pitch of a sound wave
Higher frequency means higher pitch
Frequency is used in AC circuits to determine the rate of change of voltage or current
Examples of frequency include radio waves, light waves, and electrical signals
Q86. Difference between decision tree and decision table
Decision tree is a graphical representation of decisions and their possible consequences, while decision table is a tabular representation of decisions and their corresponding actions.
Decision tree is a visual representation of a decision-making process, where each branch represents a possible decision and its outcome.
Decision table is a table that lists all possible combinations of conditions and actions, making it easier to determine the appropriate action for a given set o...read more
Q87. What is scale and encoder.
A scale is a device used to measure weight or mass, while an encoder is a device used to convert motion or position into digital signals.
A scale is commonly used in households to measure the weight of objects or people.
An encoder is often used in robotics or automation systems to determine the position or speed of a motor.
Scales can be analog or digital, with digital scales providing more accurate measurements.
Encoders can be rotary or linear, depending on the type of motion ...read more
Q88. What is a dataframe and how it differs from dataset ?
A dataframe is a two-dimensional tabular data structure in which data is organized in rows and columns. It differs from a dataset in terms of structure and functionality.
A dataframe is a data structure in which data is organized in a tabular format with rows and columns.
It is commonly used in data analysis and manipulation tasks.
Dataframes can handle both structured and semi-structured data.
They provide a convenient way to store and manipulate large datasets.
Dataframes offer ...read more
Q89. what is difference between array and dataframe
Arrays are one-dimensional data structures, while dataframes are two-dimensional data structures used in data analysis.
Arrays are one-dimensional and can hold only one type of data, while dataframes are two-dimensional and can hold multiple types of data.
Dataframes are commonly used in data analysis with libraries like Pandas in Python, while arrays are more basic data structures.
Arrays are typically used for simple data storage and manipulation, while dataframes are used for...read more
Q90. What is Array of pointer
An array of pointers is a data structure that stores memory addresses of other variables or objects.
Array of pointers can be used to create dynamic data structures like linked lists or trees.
It allows efficient access and manipulation of data by storing references instead of actual data.
Example: char* names[] = {"John", "Jane", "Mike"};
Q91. 1. Find mistakes in the Json
Identify mistakes in the given JSON.
The keys should be enclosed in double quotes.
The value of 'age' should be a number, not a string.
The value of 'isActive' should be a boolean, not a string.
The last item in the array should not have a comma after it.
Q92. Design a TreeSet functionality
TreeSet is a data structure that stores unique elements in sorted order.
TreeSet is implemented using a Red-Black tree
It provides O(log n) time complexity for basic operations like add, remove, and contains
It also provides methods like first(), last(), headSet(), tailSet(), and subSet()
TreeSet can be used to implement priority queues and sorting algorithms
Q93. How do double linked list work? What is the difference between linked list and double linked list?
A double linked list is a data structure where each node contains a reference to the previous and next node.
In a linked list, each node contains a reference to the next node only, while in a double linked list, each node contains references to both the previous and next nodes.
Double linked lists allow for traversal in both directions, making operations like deletion and insertion easier compared to single linked lists.
Example: In a double linked list, a node might have pointe...read more
Q94. What is Append and Merge?
Append and Merge are two methods used to combine data from multiple sources into a single dataset.
Append adds new rows to an existing dataset.
Merge combines two or more datasets based on a common column or key.
Append is useful when adding new data to an existing dataset, while Merge is useful for combining datasets with related information.
Example: Appending new sales data to an existing sales dataset.
Example: Merging customer data from two different sources based on a common...read more
Q95. Find duplicate elements from array
Find duplicate elements from array
Iterate through the array and use a hash set to keep track of seen elements
If an element is already in the set, it is a duplicate
Return the set of duplicate elements
Q96. What are the properties of a B-Tree?
B-Tree is a self-balancing tree data structure with multiple child nodes and is used for efficient disk access.
B-Tree has a root node, internal nodes, and leaf nodes.
Each node can have multiple child nodes.
The number of child nodes is fixed for a given B-Tree.
B-Tree is self-balancing, which means that the height of the tree is minimized.
B-Tree is used for efficient disk access as it reduces the number of disk accesses required to find a particular data item.
Example: File syst...read more
Q97. Difference between descision table and decision tree
Decision table is a tabular representation of all possible conditions and corresponding actions, while decision tree is a graphical representation of decision-making process.
Decision table lists all possible conditions and corresponding actions in a tabular format.
Decision tree is a graphical representation of decision-making process, showing different paths and outcomes.
Decision table is more suitable for complex conditions with multiple variables, while decision tree is eas...read more
Q98. What is rpn?
RPN stands for Reverse Polish Notation, a mathematical notation where operators are placed after their operands.
RPN is a postfix notation, meaning that operators are written after their operands.
It eliminates the need for parentheses to indicate the order of operations.
RPN is commonly used in calculators and computer programming languages.
Example: In RPN, the expression '3 + 4' would be written as '3 4 +'.
Q99. Tell me where Linear and Non Linear Data Structures are used?
Linear data structures are used when data needs to be accessed sequentially, while non-linear data structures are used when data needs to be accessed in a non-sequential manner.
Linear data structures like arrays and linked lists are used in algorithms that require sequential access, such as searching and sorting.
Non-linear data structures like trees and graphs are used in algorithms that require non-sequential access, such as hierarchical data representation and network routi...read more
Q100. How to check if the tree is balanced?
Check if a tree is balanced by comparing the heights of its left and right subtrees.
Calculate the height of the left subtree and the height of the right subtree.
If the difference between the heights is greater than 1, the tree is not balanced.
Recursively check if both the left and right subtrees are balanced.
If both subtrees are balanced and the height difference is less than or equal to 1, the tree is balanced.
Top Interview Questions for Related Skills
Interview Questions of Data Structures Related Designations
Interview experiences of popular companies
Reviews
Interviews
Salaries
Users/Month