basics of DSA
basics of DSA
What is an array?
Iterate through the array, keeping track of the maximum value encountered.
A string is a sequence of characters, while an array can store elements of any data
type.
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).
python
class Node:
def __init__(self, data):
self.data = data
self.next = None
A stack is a linear data structure following Last In First Out (LIFO) principle.
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.
python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = self.rear = None
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.
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?
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.
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.
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.
Common techniques include chaining (storing collided keys in a linked list) and
open addressing (finding another spot in the table).
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.
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?
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.
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.