SAP Course in Hyderabad | Clinical SAS Training in Hyderabad MyLearn Nest

DSA Interview Questions for Freshers in Hyderabad

150 DSA Interview Questions for Freshers in Hyderabad

150+ DSA Interview Questions for Freshers in Hyderabad: Coding and Technical Interview Preparation

Arrays

1. What is an array?

An array is a linear data structure that stores elements of the same data type in contiguous memory locations. Elements can be accessed using an index.

2. What are the advantages and disadvantages of arrays?

Arrays provide fast random access using indexes and are easy to traverse. Their main disadvantages are fixed size in many implementations and costly insertion or deletion in the middle.

3. What is the difference between a static array and a dynamic array?

A static array generally has a fixed size determined when it is created. A dynamic array can grow or shrink as elements are added or removed.

4. How do you find the largest element in an array?

Initialize the first element as the maximum and traverse the array, updating the maximum whenever a larger element is found. Time complexity is O(n).

5. How do you find the smallest element in an array?

Initialize the first element as the minimum and compare every element with it. Update the minimum whenever a smaller value is found. Complexity is O(n).

6. How do you find the second-largest element?

Maintain two variables, largest and secondLargest, while traversing the array. Update them whenever a larger element is encountered.

7. How do you find the second-smallest element?

Maintain smallest and secondSmallest variables and update them during a single traversal of the array.

8. How do you reverse an array?

Use two pointers, one at the beginning and one at the end, and swap elements while moving both pointers toward the center. Complexity is O(n).

9. How do you find the sum of all elements?

Traverse the array and continuously add each element to a sum variable. Complexity is O(n).

10. How do you calculate the average of array elements?

Calculate the sum of all elements and divide it by the number of elements.

11. How do you remove duplicate elements from an array?

A hash set can be used to store unique elements. Alternatively, if the array is sorted, duplicates can be removed using the two-pointer technique.

12. How do you find duplicate elements in an array?

Use a hash set to track elements already encountered. If an element already exists in the set, it is a duplicate.

13. How do you count the frequency of each element?

Use a hash map where each element is used as a key and its occurrence count is stored as the value.

14. How do you find a missing number from 1 to N?

Use the formula N × (N + 1) / 2 and subtract the sum of the given elements. Another approach is using XOR.

15. How do you find a pair whose sum equals a target?

Use a hash set or hash map to check whether target – currentElement has already been seen. Average complexity is O(n).

16. How do you find all pairs with a given sum?

A hash set can be used to identify complementary values. If the array is sorted, the two-pointer approach can be used.

17. How do you move all zeroes to the end?

Use a pointer to track the position where the next non-zero element should be placed, then move all zeroes to the remaining positions.

18. How do you separate even and odd numbers?

Traverse the array and place even and odd values into separate collections, or use a two-pointer partition approach.

19. How do you find the intersection of two arrays?

Use a hash set to store elements from one array and check which elements of the second array are present in it.

20. How do you find the union of two arrays?

Insert elements from both arrays into a set. The set will contain the unique elements from both arrays.

21. How do you rotate an array left by K positions?

One efficient method is the reversal algorithm: reverse the first K elements, reverse the remaining elements, and then reverse the entire array.

22. How do you rotate an array right by K positions?

Reduce K using K % N, then use the reversal technique to rotate the array efficiently.

23. How do you find the maximum difference between two elements?

Maintain the minimum element seen so far and calculate the difference between the current element and that minimum.

24. How do you find the maximum subarray sum?

Kadane’s algorithm can find the maximum subarray sum in O(n) time.

25. How do you find the majority element?

The Boyer-Moore Voting Algorithm can find an element appearing more than N/2 times in O(n) time and O(1) extra space.

26. How do you merge two sorted arrays?

Use two pointers to compare elements from both arrays and place the smaller element into the result.

27. How do you check whether an array is sorted?

Compare every element with the next element. If any element is greater than the following element for ascending order, the array is not sorted.

28. How do you find the first repeating element?

Use a hash set while traversing the array. The first element already present in the set is the first repeating element.

29. How do you find the first non-repeating element?

First count frequencies using a hash map, then traverse the array again and return the first element with frequency one.

30. How do you find the longest consecutive sequence?

Store elements in a hash set. Start a sequence only when number – 1 is not present, then count consecutive values.

Strings

1. What is a string?

A string is a sequence of characters. In many programming languages, strings are represented using character arrays or specialized string objects.

2. How do you reverse a string?

Convert the string into characters and use two pointers to swap characters from both ends.

3. How do you check whether a string is a palindrome?

Compare characters from the beginning and end while moving toward the center. If all corresponding characters match, it is a palindrome.

4. How do you count vowels and consonants?

Traverse the string and check whether each alphabetic character belongs to the set of vowels. The remaining alphabetic characters are consonants.

5. How do you count character frequency?

Use a hash map to store each character and increment its count whenever it appears.

6. How do you find the first non-repeating character?

Count each character’s frequency and then traverse the string again to find the first character with frequency one.

7. How do you find duplicate characters?

Use a hash map or hash set to track characters that have already appeared.

8. How do you remove duplicate characters?

Use a set to track previously seen characters and build a new string containing only the first occurrence.

9. How do you check whether two strings are anagrams?

Two strings are anagrams if they contain the same characters with the same frequencies. This can be checked using character frequency counting.

10. How do you find all anagrams of a string?

Use a sliding-window technique with character frequency counts to compare each substring with the target frequency.

11. How do you reverse words in a sentence?

Split the sentence into words and reverse their order.

12. How do you count words in a string?

Split the string based on whitespace and count the resulting words, taking care of multiple spaces.

13. How do you find the longest word?

Split the sentence into words and maintain the word with the greatest length.

14. How do you check whether one string is a rotation of another?

Two strings are rotations if they have the same length and the first string occurs inside the concatenation of the second string with itself.

15. How do you find the longest substring without repeating characters?

Use a sliding window and a set or hash map to maintain the characters currently inside the window.

16. How do you find the longest palindromic substring?

One approach is expanding around each possible center. Another approach is dynamic programming.

17. How do you replace spaces with a specific character?

Traverse the string and replace every space with the required character.

18. How do you remove whitespace from a string?

Traverse the string and add only non-whitespace characters to the result.

19. How do you convert lowercase characters to uppercase?

Use the language’s character conversion functions or ASCII character differences where appropriate.

20. How do you check whether a string contains only digits?

Traverse every character and verify that it belongs to the range 0–9.

Linked Lists

1. What is a linked list?

A linked list is a linear data structure consisting of nodes where each node contains data and a reference to another node.

2. What is the difference between an array and a linked list?

Arrays generally provide fast index-based access, while linked lists provide easier insertion and deletion when the required node position is known.

3. What are the types of linked lists?

The major types are singly linked lists, doubly linked lists, and circular linked lists.

4. What are the advantages of linked lists?

They can grow dynamically and allow efficient insertion and deletion without shifting many elements.

5. How do you create a singly linked list?

Create nodes containing data and a next reference, then connect each node to the next node.6. How do you insert a node at the beginning?

Create a new node, point its next to the current head, and update the head to the new node.

7. How do you insert a node at the end?

Traverse to the last node and set its next reference to the new node.

8. How do you insert a node at a specific position?

Traverse to the node before the required position, update its links, and insert the new node.

9. How do you delete a node?

Find the previous node and change its next pointer to skip the node being deleted.

10. How do you search for an element?

Start from the head and traverse node by node until the target value is found or the list ends.

11. How do you find the length?

Traverse the linked list and increment a counter for every node.

12. How do you reverse a linked list?

Maintain three pointers: previous, current, and next. Reverse each node’s link while traversing.

13. How do you find the middle node?

Use slow and fast pointers. The slow pointer moves one step while the fast pointer moves two steps.

14. How do you detect a cycle?

Floyd’s Cycle Detection Algorithm uses slow and fast pointers. If they meet, a cycle exists.

15. How do you find the starting point of a cycle?

After slow and fast pointers meet, move one pointer to the head. Move both one step at a time; their meeting point is the cycle’s starting node.

16. How do you remove a cycle?

Find the cycle’s starting node and disconnect the link from the previous node in the cycle.

17. How do you find the Nth node from the end?

Use two pointers separated by N positions. Move both until the first pointer reaches the end.

18. How do you merge two sorted linked lists?

Compare the current nodes of both lists and repeatedly attach the smaller node to the result.

19. How do you check whether a linked list is a palindrome?

Find the middle, reverse the second half, and compare the two halves.

20. How do you remove duplicates from a linked list?

For an unsorted list, a hash set can track values already seen. For a sorted list, compare adjacent nodes.

Stack and Queue

1. What is a stack?

A stack is a linear data structure that follows LIFO — Last In, First Out.

2. What is a queue?

A queue is a linear data structure that follows FIFO — First In, First Out.

3. Difference between stack and queue?

A stack removes the most recently inserted element, while a queue removes the earliest inserted element.

4. What are LIFO and FIFO?

LIFO means Last In, First Out. FIFO means First In, First Out.

5. How do you implement a stack using an array?

Maintain a top index. Push increments the index and inserts an element; pop removes the element at top.6. How do you implement a stack using a linked list?

Use the head node as the top of the stack. Insert and delete nodes at the head.7. How do you implement a queue using an array?

Maintain front and rear indexes. Insert at the rear and remove from the front.

8. How do you implement a queue using a linked list?

Maintain pointers to both the front and rear nodes.

9. How do you implement a stack using two queues?

Elements can be rearranged between two queues so that the most recently inserted element is available for the pop operation.

10. How do you implement a queue using two stacks?

Use one stack for insertion and another for removal. Transfer elements when the removal stack is empty.

11. How do you check balanced parentheses?

Push opening brackets onto a stack and pop when matching closing brackets appear. The brackets are balanced if the stack is empty at the end.

12. How do you reverse a string using a stack?

Push every character onto the stack and then pop them one by one.

13. What is the next greater element problem?

For each element, find the first element to its right that is greater. A monotonic stack can solve it efficiently.

14. How do you design a minimum stack?

Maintain a normal stack and another stack containing the minimum value at each level.

15. What is a circular queue?

A circular queue connects the last position back to the first position, allowing unused spaces at the beginning to be reused.

16. How is a circular queue implemented?

Use front and rear indexes with modulo arithmetic to wrap around the array.

17. What is a deque?

A deque, or double-ended queue, allows insertion and deletion from both the front and rear.

18. Difference between queue and deque?

A normal queue generally inserts at the rear and removes from the front. A deque supports operations at both ends.

Searching and Sorting

1. What is linear search?

Linear search checks elements one by one until the target is found. Its worst-case complexity is O(n).

2. What is binary search?

Binary search repeatedly divides a sorted search space into two halves. Its time complexity is O(log n).

3. Difference between linear search and binary search?

Linear search works on unsorted data but can take O(n). Binary search is faster but normally requires sorted data.

4. How do you implement binary search iteratively?

Maintain low and high indexes, calculate the middle index, and eliminate half of the search space after every comparison.

5. How do you implement binary search recursively?

Call the function recursively on either the left or right half depending on whether the target is smaller or larger than the middle element.

6. How do you find the first occurrence using binary search?

When the target is found, record the position and continue searching toward the left side.

7. How do you find the last occurrence?

When the target is found, record the position and continue searching toward the right side.

8. How do you find the square root using binary search?

Search between 0 and the number and compare the square of the middle value with the target.

9. What is bubble sort?

Bubble sort repeatedly compares adjacent elements and swaps them when they are in the wrong order.

10. What is selection sort?

Selection sort repeatedly finds the smallest remaining element and places it in the correct position.

11. What is insertion sort?

Insertion sort builds the sorted portion of an array by inserting each new element into its correct position.

12. What is merge sort?

Merge sort divides the array into smaller parts, recursively sorts them, and merges the sorted parts. Complexity is O(n log n).

13. What is quick sort?

Quick sort selects a pivot, partitions the array around the pivot, and recursively sorts the resulting partitions.

14. What is the time complexity of bubble sort?

Average and worst-case complexity is O(n²). Its best case can be O(n) with an optimized implementation.

15. What is the time complexity of merge sort?

Merge sort has O(n log n) time complexity in best, average, and worst cases.

16. What is the time complexity of quick sort?

Average complexity is O(n log n), while the worst case is O(n²).

17. Difference between merge sort and quick sort?

Merge sort guarantees O(n log n) time but generally requires additional memory. Quick sort can be performed in-place and is often fast in practice, but its worst case is O(n²).

18. Which sorting algorithm is useful for nearly sorted data?

Insertion sort is particularly effective for nearly sorted data because it requires relatively few shifts when elements are already close to their correct positions.

Hashing

1. What is hashing?

Hashing converts a key into an index or hash value that can be used for fast data lookup.

2. What is a hash table?

A hash table stores key-value pairs and uses a hash function to determine where the data should be stored.

3. What is a hash function?

A hash function converts a key into a numerical value used to determine its storage location.

4. What is a collision?

A collision occurs when two different keys produce the same hash value or storage index.

4. How are hash collisions handled?

Common techniques include separate chaining and open addressing, such as linear probing.

5. Difference between HashMap and HashSet?

A HashMap stores key-value pairs, while a HashSet stores unique values.

6. How do you find duplicates using hashing?

Traverse the data and store each element in a hash set. If an element already exists, it is a duplicate.

7. How do you count frequencies using a hash map?

Use each element as a key and increment its associated value whenever the element appears.

8. How do you find two numbers with a target sum using hashing?

For each number, calculate target – number and check whether that value already exists in the hash map or set.

9. How do you find the first non-repeating element using hashing?

First calculate the frequency of every element and then return the first element whose frequency is one.

Trees and Binary Trees

1. What is a tree?

A tree is a hierarchical, non-linear data structure consisting of nodes connected by edges.

2. What is a binary tree?

A binary tree is a tree in which each node has at most two children.

3. What is a binary search tree?

A BST is a binary tree where values in the left subtree are smaller than the node and values in the right subtree are larger, subject to the chosen duplicate-handling rule.

4. Difference between binary tree and BST?

A binary tree only restricts the number of children. A BST also maintains an ordering property that enables efficient searching.

5. What are preorder, inorder, and postorder traversals?

Preorder visits Root → Left → Right. Inorder visits Left → Root → Right. Postorder visits Left → Right → Root.

5. What is level-order traversal?

Level-order traversal visits nodes level by level from top to bottom, usually using a queue.

6. How do you find the height of a binary tree?

Recursively calculate the height of the left and right subtrees and take the larger value plus one.

7. How do you count nodes in a binary tree?

Recursively count the nodes in the left and right subtrees and add one for the current node.

8. How do you count leaf nodes?

A leaf is a node with no children. Traverse the tree and increment the count whenever such a node is found.

9. How do you search in a BST?

Compare the target with the current node. Move left if the target is smaller and right if it is larger.

10. How do you insert into a BST?

Compare the new value with each node and recursively or iteratively move left or right until an empty position is found.

11. How do you delete a node from a BST?

There are three cases: deleting a leaf, deleting a node with one child, and deleting a node with two children.

12. How do you find minimum and maximum in a BST?

The minimum is found by continuously moving left. The maximum is found by continuously moving right.

13. How do you check whether a binary tree is balanced?

For every node, compare the heights of its left and right subtrees. Their difference should not exceed one for a height-balanced tree.

14. What is the lowest common ancestor?

The lowest common ancestor is the deepest node that is an ancestor of two given nodes.

Graphs

1. What is a graph?

A graph is a non-linear data structure consisting of vertices, also called nodes, and edges connecting them.

2. What are vertices and edges?

Vertices represent entities or points, while edges represent relationships or connections between them.

3. Difference between directed and undirected graphs?

In a directed graph, edges have a direction. In an undirected graph, edges represent connections in both directions.

4. What is a weighted graph?

A weighted graph assigns a value or cost to each edge.

5. How can a graph be represented?

Common representations are an adjacency matrix and an adjacency list.

6. What is an adjacency matrix?

It is a two-dimensional matrix where the entry at row i and column j indicates whether an edge exists between vertices i and j, possibly storing its weight.

7. What is an adjacency list?

Each vertex stores a list of vertices connected to it. It is generally memory-efficient for sparse graphs.

8. What is BFS?

Breadth-First Search explores a graph level by level and generally uses a queue.

9. What is DFS?

Depth-First Search explores as far as possible along one path before backtracking. It can use recursion or an explicit stack.

10. Difference between BFS and DFS?

BFS explores level by level and uses a queue. DFS explores depth-first and uses recursion or a stack.

11. How do you detect a cycle in an undirected graph?

DFS with parent tracking or a disjoint-set data structure can be used to detect cycles.

12. How do you find the shortest path in an unweighted graph?

BFS can find the shortest path because it explores vertices in increasing order of distance from the starting vertex.

Recursion, Greedy and Dynamic Programming

1. What is recursion?

Recursion is a technique where a function calls itself to solve smaller instances of the same problem.

2. What is a base condition?

A base condition is the stopping condition that prevents recursive calls from continuing indefinitely.

3. How do you calculate factorial using recursion?

The factorial can be defined as factorial(n) = n × factorial(n-1), with factorial(0) = 1 as the base case.

4. How do you generate Fibonacci numbers using recursion?

The recursive definition is F(n) = F(n-1) + F(n-2), with base cases such as F(0)=0 and F(1)=1.

5. What is dynamic programming?

Dynamic programming solves problems with overlapping subproblems by storing previously calculated results to avoid repeated work.

6. Difference between recursion, memoization, and tabulation?

Recursion solves a problem through function calls. Memoization stores results of recursive calls. Tabulation solves the problem iteratively, usually by filling a table from smaller problems to larger ones.

7. Difference between greedy algorithms and dynamic programming?

A greedy algorithm makes the best local choice at each step, hoping it leads to a global optimum. Dynamic programming considers overlapping subproblems and stores results to systematically find an optimal solution when the problem has the required properties. 

Build Strong Coding Skills with DSA

Build Strong Coding Skills with DSA

Starting your career in the IT industry requires strong coding and problem-solving skills, especially when preparing for technical interviews. My Learnnest helps freshers in Hyderabad build a strong foundation in Data Structures and Algorithms through practical learning and interview-focused preparation. 

Popup