0% found this document useful (0 votes)
15 views

DSA Past Interview Questions

The document contains a collection of DSA past interview questions for the year 2023-24, covering fundamental concepts such as data structures, arrays, linked lists, and algorithms. It includes coding examples in C++ and Python for tasks like counting character occurrences, checking for palindromes, generating prime numbers, and finding the second maximum element in an array. Additionally, it discusses various DSA problems and sorting algorithms, providing insights into their implementations and complexities.

Uploaded by

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

DSA Past Interview Questions

The document contains a collection of DSA past interview questions for the year 2023-24, covering fundamental concepts such as data structures, arrays, linked lists, and algorithms. It includes coding examples in C++ and Python for tasks like counting character occurrences, checking for palindromes, generating prime numbers, and finding the second maximum element in an array. Additionally, it discusses various DSA problems and sorting algorithms, providing insights into their implementations and complexities.

Uploaded by

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

CSPIT, CE DSA past interview questions year 2023-24

DSA past interview questions


1. What are data structures?
Data structures are a way of organizing and storing data in a computer so that it can be
accessed and modified efficiently. They define the relationships between the data
elements, as well as the operations that can be performed on them.

2. What is an array?
An array is a linear data structure consisting of a collection of elements, each identified
by at least one array index or key. It is a contiguous block of memory where each
element is of the same data type, and the elements are accessed using their indices.

3. Is an array a primitive datatype?


Arrays are not primitive data types in most programming languages. They are typically
considered composite or structured data types because they are composed of elements
of another data type.

4. What are 2D and 3D arrays?


2D Array: A 2D array, also known as a two-dimensional array, is an array of arrays. It
represents a tabular format consisting of rows and columns, where each element is
identified by two indices - row index and column index.
3D Array: A 3D array, or three-dimensional array, is an array of arrays of arrays. It
extends the concept of a 2D array into three dimensions, forming a cube-like structure
where each element is identified by three indices.

5. Draw a 2D array and access one of the elements of the array.


+---+---+---+---+
|1|2|3|4|
+---+---+---+---+
|5|6|7|8|
+---+---+---+---+
| 9 |10 |11 |12 |
+---+---+---+---+
|13 |14 |15 |16 |
+---+---+---+---+

To access element at row index 2 and column index 3 (assuming 0-based indexing), you
would access array[2][3], which in this case is 12.

6. Write a program to iterate through a string and calculate number of times a


specific character is appeared on the string?

1
CSPIT, CE DSA past interview questions year 2023-24

#include <iostream>
#include <string>

int countOccurrences(const std::string& str, char target) {


int count = 0;
for (char ch : str) {
if (ch == target) {
count++;
}
}
return count;
}

int main() {
std::string str;
char target;

// Input string
std::cout << "Enter a string: ";
std::getline(std::cin, str);

// Input target character


std::cout << "Enter the character to count: ";
std::cin >> target;

// Count occurrences
int occurrences = countOccurrences(str, target);

// Output the result


std::cout << "The character '" << target << "' appeared " << occurrences << " times in
the string." << std::endl;

return 0;
}

7. What is a Linked List and a Doubly Linked List?

Linked List:
A linked list is a linear data structure where each element is a separate object (node)
containing both the data and a reference (link) to the next node in the sequence. The last
node points to null, indicating the end of the list. Linked lists offer dynamic memory
allocation, efficient insertion and deletion operations, and they don't have a fixed size.

Doubly Linked List:


A doubly linked list is a variation of the linked list where each node contains a reference to
the next node (next pointer) and a reference to the previous node (previous pointer). This
allows traversal in both forward and backward directions. It provides more flexibility than
a singly linked list but requires more memory due to the additional pointers.

2
CSPIT, CE DSA past interview questions year 2023-24

8. Check whether a given string is a palindrome or not without using inbuilt


functions.

Here's a C++ code to check if a given string is a palindrome or not:

cpp
Copy code
#include <iostream>
#include <string>

bool isPalindrome(const std::string& str) {


int start = 0;
int end = str.length() - 1;

while (start < end) {


if (str[start] != str[end]) {
return false;
}
start++;
end--;
}
return true;
}

int main() {
std::string input;
std::cout << "Enter a string: ";
std::cin >> input;

if (isPalindrome(input)) {
std::cout << "The string is a palindrome." << std::endl;
} else {
std::cout << "The string is not a palindrome." << std::endl;
}

return 0;
}

9. Generate prime numbers up to a given input n.

Here's a Python code to generate prime numbers up to a given input n:

python
def generate_primes(n):
primes = []
for num in range(2, n + 1):
if all(num % i != 0 for i in range(2, int(num**0.5) + 1)):
primes.append(num)

3
CSPIT, CE DSA past interview questions year 2023-24

return primes

n = int(input("Enter a number: "))


print("Prime numbers up to", n, "are:", generate_primes(n))

10. Output-based coding questions.

Output-based coding questions usually involve analyzing code and predicting the output
without actually running the code. These questions test your understanding of
programming concepts and language syntax.

11. Logical problem 1: A frog was at the bottom of a well that is 30 steps. It jumps 3
steps each day and falls back 2 each day. How many days will it take to reach the
top?

The frog advances 3 steps each day but retreats 2 steps, so it makes a net gain of 1 step
each day. Since the well has 30 steps and the frog makes 1 step of progress per day, it will
take 30 days for the frog to reach the top.

12. Logical problem 2: There are 100 balls in a bowl, 99 balls are of the same
weight. You are given one weighing machine and you need to find that one ball
having a different weight. How will you do that in minimum comparisons?

This problem can be solved using a binary search approach. Here's how:

Divide the balls into two equal groups of 50 each.


Weigh one group against the other using the weighing machine.
If the weights are equal, then the odd ball is in the other 50 balls.
If the weights are not equal, the odd ball is in the lighter group.
Repeat the process recursively with the lighter group until you find the odd ball.
This approach requires only 7 weighings to find the odd ball.

13. DSA: Given a string, you need to find the occurrence of each word.

Here's a Python code to find the occurrence of each word in a given string:

python
Copy code
def count_word_occurrences(sentence):
words = sentence.split()
word_count = {}

for word in words:


if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1

4
CSPIT, CE DSA past interview questions year 2023-24

return word_count

input_string = input("Enter a string: ")


word_occurrences = count_word_occurrences(input_string)
print("Word occurrences:")
for word, count in word_occurrences.items():
print(f"{word}: {count}")

14. Given an integer n and an array of size n, find the second maximum element
from the array.

Here's a Python code to find the second maximum element from an array:

python
Copy code
def find_second_max(arr):
if len(arr) < 2:
return "Array should have at least two elements."

max1 = max2 = float('-inf')

for num in arr:


if num > max1:
max2 = max1
max1 = num
elif max1 > num > max2:
max2 = num

return max2

n = int(input("Enter the size of the array: "))


arr = list(map(int, input("Enter the elements of the array separated by space: ").split()))

second_max = find_second_max(arr)
print("Second maximum element in the array:", second_max)
These solutions address the logical problem, count occurrences of words in a string, and
find the second maximum element from an array.
(First related constraints. Give Brute Force Approach and then optimal approach)

5
CSPIT, CE DSA past interview questions year 2023-24

DSA Problems
1. Min and max valued character from a string:
To find the minimum and maximum valued character from a string, you would iterate
through the string and keep track of the minimum and maximum characters
encountered.

2. Rearrange Array Alternately:


In this problem, you need to rearrange the elements of the array alternatively, such that
the first element becomes the maximum value, the second element becomes the
minimum value, the third element becomes the second maximum value, and so on.

3. Coin Change Problem:


This problem involves finding the number of ways to make a certain amount of change
using a given set of coins. It's a classic dynamic programming problem where you need
to find the combinations of coins that sum up to the desired amount.

4. Merge Intervals:
Given an array of intervals, the task is to merge overlapping intervals and return a new
array of non-overlapping intervals.

5. Calculate the frequency of each word in the given string:


This problem requires counting the frequency of each word in a given string. It involves
tokenizing the string into words and then counting the occurrences of each word.

6. Number of ways to sort Array:


This problem involves determining the number of ways in which an array can be sorted.
It could involve permutations and combinations of sorting algorithms.

7. Explain any one sort and sort the given array with that:
One common sorting algorithm is Merge Sort. It follows the divide and conquer
approach. Here's a brief explanation:

Divide the array into two halves.

6
CSPIT, CE DSA past interview questions year 2023-24

Recursively sort each half.


Merge the sorted halves.
The time complexity of Merge Sort is O(n log n).
Below is an example of sorting an array using Merge Sort in Python:
python
Copy code
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]

merge_sort(L)
merge_sort(R)

i=j=k=0

while i < len(L) and j < len(R):


if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

while i < len(L):


arr[k] = L[i]
i += 1
k += 1

7
CSPIT, CE DSA past interview questions year 2023-24

while j < len(R):


arr[k] = R[j]
j += 1
k += 1

arr = [12, 11, 13, 5, 6, 7]


merge_sort(arr)
print("Sorted array:", arr)

8. Best way to sort array:


The best sorting algorithm depends on various factors such as the size of the array, the
distribution of elements, and the available memory. Some commonly used sorting
algorithms include:

Quicksort: Generally considered one of the fastest sorting algorithms. It has an average
time complexity of O(n log n) but can degrade to O(n^2) in worst-case scenarios.
Merge Sort: Provides stable sorting with a time complexity of O(n log n) in all cases but
requires extra space for merging.
Heapsort: An in-place sorting algorithm with a time complexity of O(n log n) but slower
compared to quicksort for most datasets.
Insertion Sort: Efficient for small datasets or nearly sorted arrays with a time
complexity of O(n^2) but not suitable for large datasets.
Selection Sort: Simple and easy to implement but has a time complexity of O(n^2) and
performs poorly on large datasets.
Depending on the specific requirements and constraints of the problem, the best sorting
algorithm may vary.

You might also like