Top 250 Data Structures Interview Questions and Answers

Updated 23 Feb 2025

Q1. How would you code a linked list? Show the code

Ans.

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.

View 1 answer
right arrow
Frequently asked in

Q2. 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

Ans.

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

Add your answer
right arrow

Q3. Can an array have elements of different data types?

Ans.

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']

View 1 answer
right arrow
Frequently asked in

Q4. Difference between Stack and Queue with real time example

Ans.

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

Add your answer
right arrow
Frequently asked in
Are these interview questions helpful?

Q5. find the nearest greater value of a given value in a BST

Ans.

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.

Add your answer
right arrow

Q6. What is hashmap? Where it is used? What is the time complexity to implement it?

Ans.

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.

Add your answer
right arrow
Frequently asked in
Share interview questions and help millions of jobseekers 🌟

Q7. Can you implement a stack using queue

Ans.

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

Add your answer
right arrow

Q8. difference between graph and tree?

Ans.

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

Add your answer
right arrow
Frequently asked in

Data Structures Jobs

Software Developer 3-8 years
IBM India Pvt. Limited
4.0
Bangalore / Bengaluru
Software Developer 3-8 years
IBM India Pvt. Limited
4.0
Bangalore / Bengaluru
Software Engineer III - IOT 4-8 years
Walmart Labs
3.8
Bangalore / Bengaluru

Q9. Explain ds algorithm for tree traversal

Ans.

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

Add your answer
right arrow

Q10. Diff btw list and array?

Ans.

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

Add your answer
right arrow
Frequently asked in

Q11. 2.What is FIFO and LIFO, where you implemented this?

Ans.

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.

View 1 answer
right arrow

Q12. Differnce between ArrayList and LinkedList

Ans.

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.

Add your answer
right arrow

Q13. Need a DSA Code?How apply?

Ans.

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.

View 48 more answers
right arrow

Q14. What data structure would you use for a dictionary?

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q15. How to detect loop in linked list?

Ans.

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)

Add your answer
right arrow

Q16. 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

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q17. Could you implement those in code ?

Ans.

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.

Add your answer
right arrow

Q18. Squares of a Sorted Array Problem Statement

You are given an array/list ARR consisting of N integers. Your task is to generate a new array/list containing the squares of each element in ARR, with the resulting ...read more

Ans.

Given an array of integers, generate a new array with the squares of each element sorted in increasing order.

  • Iterate through the array and square each element

  • Sort the squared elements in increasing order

  • Return the sorted array

Add your answer
right arrow

Q19. Difference between Hash Map and Linked Hash Map?

Ans.

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}

Add your answer
right arrow

Q20. What would be the ideal data structure to represent people and friend relations in facebook

Ans.

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

View 2 more answers
right arrow
Frequently asked in

Q21. 1.Difference between HashMap and Hashtable ?

Ans.

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

Add your answer
right arrow

Q22. Difference between collection and map.

Ans.

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.

View 1 answer
right arrow
Frequently asked in
Q23. Which data structures are used for implementing an LRU cache?
Ans.

The data structures used for implementing an LRU cache are doubly linked list and hash map.

  • Doubly linked list is used to maintain the order of recently used elements.

  • Hash map is used for fast lookups to check if an element is present in the cache or not.

  • When a new element is accessed, it is moved to the front of the linked list to indicate it as the most recently used.

View 1 answer
right arrow

Q24. What are collections and its type?

Ans.

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.

Add your answer
right arrow

Q25. Sort a "K" Sorted Doubly Linked List

Given a doubly-linked list with N nodes, where each node’s position deviates at most K positions from its position in the sorted list, your task is to sort this given doubly...read more

Ans.

Sort a doubly linked list where each node's position deviates at most K positions from its position in the sorted list.

  • Iterate through the doubly linked list and maintain a min-heap of size K+1 to keep track of the next smallest element.

  • Remove the smallest element from the heap and add it to the sorted list. Update the heap with the next element from the removed node's next position.

  • Continue this process until all nodes are added to the sorted list.

Add your answer
right arrow
Frequently asked in

Q26. Whai is DSA why we use?

Ans.

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.

View 2 more answers
right arrow

Q27. What is Set?

Ans.

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])

Add your answer
right arrow

Q28. how hashset and hashmap work internally?

Ans.

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

View 1 answer
right arrow
Frequently asked in

Q29. Design autocomplete in IDEs

Ans.

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

Add your answer
right arrow
Frequently asked in

Q30. Print the level order traversal of the binary tree in the spiral form

Ans.

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

View 3 more answers
right arrow

Q31. What is the problem with arrays?

Ans.

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

Add your answer
right arrow

Q32. what is hashing and how will you implement?

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q33. Tell me the key factors of store matrix

Ans.

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

Add your answer
right arrow

Q34. What are lists and its functions?

Ans.

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

Add your answer
right arrow
Frequently asked in

Q35. Write a code for building a heap and explain its time complexity

Ans.

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

Add your answer
right arrow

Q36. 1. What is collection ?

Ans.

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.

View 1 answer
right arrow

Q37. How does concurrent hashmap works

Ans.

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().

Add your answer
right arrow

Q38. What is mean by FIFO, LIFO Process?

Ans.

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

Add your answer
right arrow
Frequently asked in

Q39. What is cc.

Ans.

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

Add your answer
right arrow

Q40. What is dsr

Ans.

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

View 12 more answers
right arrow

Q41. Implement AVL Tree.

Ans.

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

Add your answer
right arrow

Q42. What is RPN no.

Ans.

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 * +.

Add your answer
right arrow

Q43. Sorted Order Printing of a BST Array

Given a Binary Tree consisting of 'N' nodes with integer values, your task is to determine the in-order traversal of the Binary Tree.

Input:

The first line contains an integ...read more
Ans.

The task is to determine the in-order traversal of a Binary Tree given in level order.

  • Implement a function to perform in-order traversal of a Binary Tree

  • Use recursion to traverse left subtree, visit root, and then traverse right subtree

  • Handle null nodes denoted by -1 in the input

Add your answer
right arrow
Frequently asked in

Q44. write a program to print name?

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q45. Explain Array List and List

Ans.

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.

Add your answer
right arrow

Q46. Remove duplicates from a string

Ans.

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

Add your answer
right arrow

Q47. Detect Loop in Singly Linked List

Determine if a given singly linked list of integers contains a cycle.

Explanation:

A cycle in a linked list occurs when a node's next points back to a previous node in the list...read more

Ans.

Detect if a singly linked list has a cycle by using Floyd's Cycle Detection Algorithm.

  • Use Floyd's Cycle Detection Algorithm to detect a cycle in a singly linked list.

  • Maintain two pointers, one moving at twice the speed of the other.

  • If there is a cycle, the two pointers will eventually meet.

  • If one of the pointers reaches the end of the list (null), there is no cycle.

Add your answer
right arrow
Frequently asked in

Q48. Identical Trees Problem Statement

Given two binary trees with 'N' and 'M' nodes respectively, determine if the two trees are identical. Return true if they are identical, otherwise return false.

Input:

The firs...read more
Ans.

Check if two binary trees are identical by comparing their nodes in level order.

  • Traverse both trees in level order and compare corresponding nodes for equality

  • Use a queue to keep track of nodes to be compared

  • Return false if nodes are not equal or if one tree has more nodes than the other

Add your answer
right arrow

Q49. Say we have a number 1.00123456788 how will we store

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q50. What is vertices and edges on a dag?

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q51. Implement a min heap using priority queue.

Ans.

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.

Add your answer
right arrow

Q52. What is node?

Ans.

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

Add your answer
right arrow

Q53. Find lca of 2 nodes in a binary tree (write pseudocode)

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q54. Code a circular linked list

Ans.

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

Add your answer
right arrow
Frequently asked in

Q55. Design a data structure for efficient insert(),delete(),search(), return_any_value().

Ans.

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

Add your answer
right arrow

Q56. Palindrome Linked List Detection

Given a singly linked list of integers, determine if it is a palindrome. A linked list is considered a palindrome if it reads the same forward and backward.

Example:

Input:
The ...read more
Ans.

Check if a singly linked list is a palindrome by comparing elements from both ends.

  • Traverse the linked list to find the middle point

  • Reverse the second half of the linked list

  • Compare the first half with the reversed second half to check for palindrome

  • Example: Input: 1 2 3 2 1 -1, Output: true

Add your answer
right arrow
Frequently asked in

Q57. Given a tree T1 and T2.Find whether T2 is subtree of T1 or not.If not return -1

Ans.

The answer to the question is to check if T2 is a subtree of T1.

  • Check if T1 and T2 are equal, return true if they are

  • If not, recursively check if T2 is a subtree of T1's left subtree

  • If not, recursively check if T2 is a subtree of T1's right subtree

  • If none of the above conditions are met, T2 is not a subtree of T1

Add your answer
right arrow

Q58. What is filter formula

Ans.

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

Add your answer
right arrow

Q59. Remove duplicates in an array

Ans.

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

Add your answer
right arrow

Q60. 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

Ans.

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.

Add your answer
right arrow

Q61. Reverse a Linked List Iteratively

You are given a singly linked list of integers. The task is to return the head of the reversed linked list.

Example:

Input:
The given linked list is 1 -> 2 -> 3 -> 4 -> NULL.
O...read more
Ans.

Reverse a singly linked list iteratively and return the head of the reversed linked list.

  • Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.

  • Keep track of the previous, current, and next nodes while traversing the linked list.

  • Update the head of the reversed linked list to be the last node encountered.

  • Time complexity: O(N), Space complexity: O(1).

Add your answer
right arrow

Q62. Partial BST Problem Statement

Check if a given binary tree is a Partial Binary Search Tree (BST). A Partial BST adheres to the following properties:

  • The left subtree of a node contains only nodes with data les...read more
Ans.

Check if a binary tree is a Partial Binary Search Tree (BST) based on specific properties.

  • Traverse the tree in level order and check if each node satisfies the properties of a Partial BST.

  • Use recursion to check if the left and right subtrees are also Partial BSTs.

  • Compare the data of each node with its children to ensure the BST properties are maintained.

  • Example: For input 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1, the output should be true.

Add your answer
right arrow

Q63. MapSum Pair Implementation

Create a data structure named 'MapSum' with the ability to perform two operations and a constructor.

Explanation:

Implement the following:
  • MapSum(): Initializes the MapSum.
  • insert(...read more
Ans.

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

Add your answer
right arrow
Frequently asked in

Q64. How many types of graphs? Explain?

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q65. Find the height og a binary tree without recursion. Write code and testcases

Ans.

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

Add your answer
right arrow

Q66. What types of data

Ans.

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)

View 1 answer
right arrow

Q67. Have you ever used maps

Ans.

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.

Add your answer
right arrow

Q68. how to reverse linked list

Ans.

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

Add your answer
right arrow

Q69. Preorder Traversal Problem Statement

You are provided with the root node of a binary tree comprising N nodes. Your objective is to output its preorder traversal. Preorder traversal of a binary tree is performed...read more

Ans.

Implement a function to perform preorder traversal on a binary tree given the root node.

  • Create a recursive function to traverse the tree in preorder fashion.

  • Visit the root node, then recursively traverse left subtree, followed by right subtree.

  • Store the visited nodes in an array and return the array as the result.

  • Example: For the input tree [1, 2, 3, 4, -1, 5, 6, -1, 7, -1, -1, -1, -1, -1, -1], the preorder traversal output should be [1, 2, 4, 7, 3, 5, 6].

Add your answer
right arrow
Frequently asked in

Q70. diff between hashtable and concurrent hash map

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q71. Explain insertion in binary search trees

Ans.

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

Add your answer
right arrow
Frequently asked in

Q72. What do you mean by a Structure?

Ans.

A structure is a way of organizing and arranging elements or components in a systematic manner.

  • A structure provides a framework or framework for organizing and managing information or objects.

  • It helps in creating a logical and hierarchical arrangement of elements.

  • Structures can be found in various fields such as architecture, engineering, computer science, and biology.

  • Examples of structures include buildings, bridges, data structures in programming, organizational hierarchies...read more

Add your answer
right arrow
Frequently asked in

Q73. How many trees are possible with two and three nodes?

Ans.

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).

Add your answer
right arrow

Q74. How vector works internally

Ans.

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

Add your answer
right arrow
Frequently asked in

Q75. What is CPV?

Ans.

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.

View 3 more answers
right arrow
Frequently asked in

Q76. What are the properties of a B-Tree?

Ans.

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

Add your answer
right arrow

Q77. Diff b/w arraylist and linkedlist

Ans.

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

Add your answer
right arrow
Frequently asked in

Q78. Explain hash function

Ans.

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.

Add your answer
right arrow

Q79. 1. Write a routine to output the elements of the inorder traversal of a binary tree one by one in its each call. eg: Assuming the inorder traversal is 1, 2, 3, 4, 5, the routine should return 1 in its first cal...

read more
Ans.

The routine should output the elements of the inorder traversal of a binary tree one by one in each call.

  • Implement an inorder traversal algorithm recursively

  • Use a global variable or pass a reference to keep track of the current element

  • Call the routine repeatedly to get the next element in each call

Add your answer
right arrow

Q80. 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 more
Ans.

To 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

Add your answer
right arrow
Frequently asked in

Q81. Write a program to store a tree on a file. Also write code to reconstruct the tree from that file. Think of efficient techniques

Ans.

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

Add your answer
right arrow

Q82. How can you change stack into pointers?

Ans.

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

Add your answer
right arrow
Frequently asked in

Q83. Difference between HashMap and ConcurentHashMap

Ans.

HashMap is not thread-safe while ConcurrentHashMap is thread-safe.

  • HashMap is not thread-safe and can cause ConcurrentModificationException if modified while iterating.

  • ConcurrentHashMap allows concurrent modifications without causing any exception.

  • ConcurrentHashMap achieves thread-safety by dividing the map into segments and locking only a portion of the map during updates.

  • ConcurrentHashMap is suitable for high-concurrency scenarios where multiple threads are accessing and mod...read more

Add your answer
right arrow
Frequently asked in

Q84. What is cache

Ans.

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

Add your answer
right arrow

Q85. What do u mean by data

Ans.

Data refers to facts, statistics, or information collected for analysis or reference.

  • Data is raw, unprocessed information.

  • It can be in the form of numbers, text, images, or any other format.

  • Examples include customer names, product prices, and sales figures.

  • Data can be structured (organized in a specific way) or unstructured (not organized).

Add your answer
right arrow

Q86. how does look up happens in a list when you do my_list[5]?

Ans.

my_list[5] retrieves the 6th element of the list.

  • Indexing starts from 0 in Python.

  • The integer inside the square brackets is the index of the element to retrieve.

  • If the index is out of range, an IndexError is raised.

Add your answer
right arrow
Frequently asked in

Q87. Rotate an array with the given number of times.

Ans.

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

Add your answer
right arrow
Frequently asked in

Q88. What is time series?

Ans.

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

Add your answer
right arrow
Frequently asked in

Q89. What are tree traversals?

Ans.

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.

Add your answer
right arrow
Frequently asked in

Q90. Find common ancestor of 2 nodes in a binary tree ?

Ans.

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

Add your answer
right arrow
Q91. What is the best way to retrieve the minimum number at any point in time from a bag where numbers are continuously inserted and removed?
Ans.

Use a min heap to efficiently retrieve the minimum number from a bag where numbers are continuously inserted and removed.

  • Implement a min heap data structure to keep track of the minimum number at any point in time.

  • When a number is inserted, add it to the min heap.

  • When a number is removed, remove it from the min heap.

  • The root of the min heap will always contain the minimum number.

Add your answer
right arrow

Q92. Clone a Linked List with Random Pointers Problem Statement

Given a linked list where each node contains two pointers: the first points to the next node in sequence, and the second is a random pointer that can p...read more

Ans.

Clone a linked list with random pointers by creating deep copy of the original list without duplicating references.

  • Create a deep copy of the linked list by instantiating new nodes for each node in the original list.

  • Ensure that the random pointers in the cloned list point to the corresponding nodes in the new list.

  • Do not duplicate references to original nodes while creating the clone.

  • Implement the function to clone the linked list without using additional space.

  • Verify that the...read more

Add your answer
right arrow

Q93. Represent numbers using linked list. How would you add two numbers represented in linked list form. Length of numbers can be different

Ans.

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.

Add your answer
right arrow

Q94. How do we map the paths

Ans.

Mapping paths involves identifying and visualizing the routes or connections between different points or elements.

  • Identify the starting point and ending point of the path

  • Determine the possible routes or connections between the points

  • Use mapping tools or software to visualize the paths

  • Consider factors such as distance, time, and obstacles when mapping paths

Add your answer
right arrow
Frequently asked in

Q95. What are different types of streams

Ans.

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

Add your answer
right arrow

Q96. Binary Search Tree Iterator Problem Statement

Design and implement a class BSTIterator to perform an in-order traversal over a Binary Search Tree (BST). Your implementation should include the following methods:...read more

Ans.

Design and implement a class BSTIterator to perform in-order traversal over a Binary Search Tree (BST).

  • Implement a parameterized constructor to initialize the iterator with the root of the BST.

  • Implement a method 'next()' to return the next smallest element in in-order traversal.

  • Implement a method 'hasNext()' to check if there exists a next smallest element in traversal.

  • Ensure the output is the in-order traversal of the BST using the iterator.

Add your answer
right arrow

Q97. How many types of alignment?

Ans.

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.

View 3 more answers
right arrow

Q98. 0 what is frequency

Ans.

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

Add your answer
right arrow

Q99. Difference between decision tree and decision table

Ans.

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

View 1 answer
right arrow
Frequently asked in

Q100. What is scale and encoder.

Ans.

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

Add your answer
right arrow
Frequently asked in
1
2
3
Next
Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Interview experiences of popular companies

3.7
 • 10.4k Interviews
3.8
 • 8.1k Interviews
3.6
 • 7.5k Interviews
3.7
 • 5.6k Interviews
3.8
 • 5.6k Interviews
4.1
 • 5k Interviews
3.7
 • 4.7k Interviews
3.5
 • 3.8k Interviews
3.7
 • 846 Interviews
View all
Recently Viewed
JOBS
Browse jobs
Discover jobs you love
SALARIES
Accenture
SALARIES
Infosys
REVIEWS
Tech Mahindra
No Reviews
SALARIES
Cognizant
SALARIES
Intuit
SALARIES
Google
REVIEWS
LTIMindtree
No Reviews
SALARIES
Expedia Group
DESIGNATION
Data Structures Interview Questions
Share an Interview
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
70 Lakh+

Reviews

5 Lakh+

Interviews

4 Crore+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter