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

basics of DSA

DSA QUESTION

Uploaded by

soodhardik12
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

basics of DSA

DSA QUESTION

Uploaded by

soodhardik12
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Array and Strings

What is an array?

An array is a collection of items stored at contiguous memory locations, allowing


the same type of data to be stored together.

How do you find the largest element in an array?

Iterate through the array, keeping track of the maximum value encountered.

What is the difference between a string and an array?

A string is a sequence of characters, while an array can store elements of any data
type.

How do you reverse a string in Python?

python
def reverse_string(s):
return s[::-1]
What is a multidimensional array?

An array containing one or more arrays within it, often used to represent matrices
or tables.

Linked Lists
What is a linked list?

A linked list is a linear data structure where elements are stored in nodes, each
pointing to the next node in the sequence.

What is the difference between a singly linked list and a doubly linked list?

A singly linked list allows traversal in one direction, while a doubly linked list
allows traversal in both directions (forward and backward).

How do you insert an element at the beginning of a linked list?

python
class Node:
def __init__(self, data):
self.data = data
self.next = None

def insert_at_beginning(head, data):


new_node = Node(data)
new_node.next = head
return new_node
How do you detect a cycle in a linked list?

Use Floyd's Cycle-Finding Algorithm (Tortoise and Hare method).

Stacks and Queues


What is a stack?

A stack is a linear data structure following Last In First Out (LIFO) principle.

How do you implement a stack using an array?


python
class Stack:
def __init__(self):
self.stack = []

def push(self, item):


self.stack.append(item)

def pop(self):
if not self.is_empty():
return self.stack.pop()

def is_empty(self):
return len(self.stack) == 0
What is a queue?

A queue is a linear data structure following First In First Out (FIFO) principle.

How do you implement a queue using a linked list?

python
class Node:
def __init__(self, data):
self.data = data
self.next = None

class Queue:
def __init__(self):
self.front = self.rear = None

def enqueue(self, item):


new_node = Node(item)
if self.rear is None:
self.front = self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node

def dequeue(self):
if self.front is None:
return None
temp = self.front
self.front = temp.next
if self.front is None:
self.rear = None
return temp.data
Trees
What is a binary tree?

A binary tree is a tree data structure where each node has at most two children
referred to as the left child and the right child.

What is the difference between a binary tree and a binary search tree (BST)?

In a binary tree, nodes can have any order. In a BST, the left subtree of a node
contains only nodes with values less than the node’s key, and the right subtree
only nodes with values greater.

How do you traverse a binary tree in pre-order?


python
def pre_order_traversal(root):
if root:
print(root.data)
pre_order_traversal(root.left)
pre_order_traversal(root.right)
How do you find the height of a binary tree?

python
def height(root):
if root is None:
return 0
else:
left_height = height(root.left)
right_height = height(root.right)
return max(left_height, right_height) + 1
Graphs
What is a graph?

A graph is a data structure consisting of a set of nodes (vertices) and a set of


edges connecting pairs of nodes.

What is the difference between a directed and an undirected graph?

In a directed graph, edges have a direction. In an undirected graph, edges do not


have a direction.

How do you represent a graph using an adjacency list?

python
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
How do you perform a depth-first search (DFS) on a graph?

python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
Sorting and Searching
What is the bubble sort algorithm?

Bubble sort is a simple sorting algorithm that repeatedly steps through the list,
compares adjacent elements, and swaps them if they are in the wrong order.

How do you implement the quicksort algorithm?

python
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
What is a binary search algorithm?

Binary search is an efficient algorithm for finding an item from a sorted list by
repeatedly dividing the search interval in half.

How do you implement binary search?

python
def binary_search(arr, x):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
left = mid + 1
else:
right = mid - 1
return -1
Hashing
What is a hash table?

A hash table is a data structure that maps keys to values for highly efficient
lookup.

How do you handle collisions in a hash table?

Common techniques include chaining (storing collided keys in a linked list) and
open addressing (finding another spot in the table).

How do you implement a simple hash function?

python
def hash_function(key):
return hash(key) % 10
Dynamic Programming
What is dynamic programming?

Dynamic programming is a method for solving complex problems by breaking them down
into simpler subproblems and storing the results of subproblems to avoid redundant
calculations.

How do you solve the Fibonacci sequence using dynamic programming?

python
def fibonacci(n, memo={}):
if n in memo:
return memo[n]
if n <= 2:
return 1
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]
Recursion
What is recursion?

Recursion is a method where the solution to a problem depends on solutions to


smaller instances of the same problem.

1. What is an Array?
An array is a data structure that stores elements of the same type in contiguous
memory locations. Each element can be accessed using an index. Arrays have fixed
size and are efficient for sequential access.

2. Reverse an Array
Solution: Swap the first and last elements using two pointers.
Code (Python):

python
Copy code
def reverse_array(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
3. Check if a String is a Palindrome
A string is a palindrome if it reads the same forward and backward.
Code:

python
Copy code
def is_palindrome(s):
return s == s[::-1]
4. Find the Missing Number in an Array
For an array with size n-1 containing numbers from 1 to n:
Solution: Use the formula for sum of the first n numbers: Sum = n*(n+1)/2.
Code:

python
Copy code
def find_missing_number(arr, n):
total = n * (n + 1) // 2
return total - sum(arr)
5. Find the Maximum Subarray Sum (Kadane's Algorithm)
Solution: Keep track of the current sum and maximum sum so far.
Code:

python
Copy code
def max_subarray_sum(arr):
max_sum = cur_sum = arr[0]
for num in arr[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)
return max_sum
6. Check if an Array is Sorted
Solution: Traverse the array and compare adjacent elements.
Code:

python
Copy code
def is_sorted(arr):
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
return False
return True
7. Move Zeros to the End
Shift non-zero elements to the front.
Code:

python
Copy code
def move_zeros(arr):
pos = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[pos], arr[i] = arr[i], arr[pos]
pos += 1
return arr
8. Find the Second Largest Element
Track the largest and second-largest elements during iteration.
Code:

python
Copy code
def second_largest(arr):
largest = second = float('-inf')
for num in arr:
if num > largest:
second = largest
largest = num
elif num > second and num != largest:
second = num
return second
9. Remove Duplicates from a Sorted Array
Use two pointers to overwrite duplicates.
Code:

python
Copy code
def remove_duplicates(arr):
if not arr:
return 0
j = 0
for i in range(1, len(arr)):
if arr[i] != arr[j]:
j += 1
arr[j] = arr[i]
return arr[:j+1]
10. Reverse a String
Solution: Use slicing or two pointers.
Code:

python
Copy code
def reverse_string(s):
return s[::-1]
11. Check for Anagram Strings
Two strings are anagrams if they contain the same characters with the same
frequencies.
Code:

python
Copy code
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
12. Find the First Non-Repeating Character
Use a frequency counter.
Code:

python
Copy code
from collections import Counter

def first_non_repeating(s):
freq = Counter(s)
for ch in s:
if freq[ch] == 1:
return ch
return -1
13. Find the Intersection of Two Arrays
Solution: Use sets for efficient lookups.
Code:

python
Copy code
def intersection(arr1, arr2):
return list(set(arr1) & set(arr2))
14. Binary Search
Works on sorted arrays by repeatedly dividing the search space.
Code:

python
Copy code
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
15. Find the Middle of a Linked List
Use slow and fast pointers. The slow pointer moves one step while the fast moves
two steps.

16. Reverse a Linked List


Use three pointers: prev, current, and next.

17. Detect a Loop in a Linked List


Use Floyd’s Cycle Detection Algorithm: slow and fast pointers.

18. Valid Parentheses


Use a stack to check balanced brackets.
Code:
python
Copy code
def is_valid_parentheses(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for ch in s:
if ch in mapping:
top = stack.pop() if stack else '#'
if mapping[ch] != top:
return False
else:
stack.append(ch)
return not stack
19. Find the Lowest Common Ancestor (LCA) in a BST
Traverse the BST and check the divergence point between two nodes.

20. Breadth-First Search (BFS) for a Graph


Use a queue for level-order traversal.

21. Depth-First Search (DFS) for a Graph


Use a stack or recursion for traversal.

22. Implement a Queue using Two Stacks


Use two stacks to simulate enqueue and dequeue operations.

23. Sort an Array using Merge Sort


Divide the array into halves and merge them in sorted order.

24. Sort an Array using Quick Sort


Choose a pivot, partition the array, and sort the subarrays recursively.

25. Find the Peak Element in an Array


Use binary search to find a local maximum.

26. Check if Two Strings are Rotations


Concatenate the first string with itself and search for the second string.
Code:

python
Copy code
def is_rotation(s1, s2):
return len(s1) == len(s2) and s2 in (s1 + s1)
27. Find the Longest Palindromic Substring
Expand around centers or use dynamic programming.

28. Implement Stack Operations


Push, pop, and peek operations using arrays or linked lists.

29. Find the Diameter of a Binary Tree


Calculate the longest path between any two nodes using recursion.

30. Find the Shortest Path in a Graph (Dijkstra’s Algorithm)


Use a priority queue to efficiently find the shortest distance from the source.

You might also like