Questions for dsa
Questions for dsa
These questions cover basic data structures, algorithms, and common problem-solving
patterns.
Array-Based Problems
String-Based Problems
Stack Problems
Queue Problems
Mathematical Problems
Next Steps:
::
Here’s a breakdown of solutions to all 100 questions, organized into categories. Each
category will have code examples for every question. Since this is a lot of information, I’ll
provide links or hints for repetitive problems and prioritize unique ones.
Array-Based Problems
2. Reverse an array
def reverse_array(arr):
return arr[::-1]
12. Find the contiguous subarray with the maximum sum (Kadane's
Algorithm)
def max_subarray_sum(arr):
max_sum = curr_sum = arr[0]
for num in arr[1:]:
curr_sum = max(num, curr_sum + num)
max_sum = max(max_sum, curr_sum)
return max_sum
17. Rearrange an array such that the positive and negative numbers alternate
def rearrange_alternate(arr):
pos, neg = [x for x in arr if x >= 0], [x for x in arr if x < 0]
result = []
while pos or neg:
if pos: result.append(pos.pop(0))
if neg: result.append(neg.pop(0))
return result
19. Find the majority element in an array (element appears more than n/2
times)
def majority_element(arr):
count, candidate = 0, None
for num in arr:
if count == 0:
candidate = num
count += 1 if num == candidate else -1
return candidate if arr.count(candidate) > len(arr) // 2 else None
I’ll stop here for now to give you a digestible amount of material. The remaining String-
Based Problems, Linked List Problems, Stack Problems, and more can be provided
incrementally. Let me know how you'd like to proceed or if you’d like the remaining
categories explained in the same way!
Here are solutions for the next 80 problems, divided into categories:
String-Based Problems
# Example
print(reverse_string("hello")) # Output: "olleh"
# Example
print(is_palindrome("madam")) # Output: True
print(is_palindrome("hello")) # Output: False
# Example
print(count_vowels_consonants("hello world")) # Output: (3, 7)
# Example
print(first_non_repeating("swiss")) # Output: "w"
# Example
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False
# Example
print(find_substrings("abc")) # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']
# Example
print(contains_only_digits("12345")) # Output: True
print(contains_only_digits("123a5")) # Output: False
# Example
print(to_uppercase("hello")) # Output: "HELLO"
# Example
print(to_lowercase("HELLO")) # Output: "hello"
# Example
print(remove_duplicates("programming")) # Output: "progamin"
32. Find the length of the longest substring without repeating characters
def longest_unique_substring(s):
seen = {}
max_length = start = 0
for i, char in enumerate(s):
if char in seen and seen[char] >= start:
start = seen[char] + 1
seen[char] = i
max_length = max(max_length, i - start + 1)
return max_length
# Example
print(longest_unique_substring("abcabcbb")) # Output: 3
33. Replace all spaces in a string with '%20'
def replace_spaces(s):
return s.replace(" ", "%20")
# Example
print(replace_spaces("hello world")) # Output: "hello%20world"
# Example
print(find_permutations("abc")) # Output: ['abc', 'acb', 'bac', 'bca',
'cab', 'cba']
# Example
print(is_valid_shuffle("abc", "def", "adbcef")) # Output: True
print(is_valid_shuffle("abc", "def", "abcdefg")) # Output: False
# Example
print(count_substring("hellohello", "hello")) # Output: 2
longest = ""
for i in range(len(s)):
# Odd-length palindromes
odd = expand_around_center(i, i)
# Even-length palindromes
even = expand_around_center(i, i + 1)
longest = max(longest, odd, even, key=len)
return longest
# Example
print(longest_palindrome_substring("babad")) # Output: "bab" or "aba"
# Example
print(reverse_words("hello world")) # Output: "world hello"
# Example
print(are_rotations("abc", "bca")) # Output: True
print(are_rotations("abc", "cab")) # Output: True
# Example
print(most_frequent_char("programming")) # Output: "r"
These cover 40/100. Let me know if you'd like to continue to Linked List, Stack, Queue, or
Tree problems next!
Here are the next 60 solutions, covering Linked List, Stack, Queue, Tree, and additional
algorithms.
class LinkedList:
def __init__(self):
self.head = None
def display(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")
48. Find the nth node from the end of a linked list
def nth_from_end(head, n):
slow, fast = head, head
for _ in range(n):
if fast:
fast = fast.next
else:
return None
while fast:
slow = slow.next
fast = fast.next
return slow.data
Stack Problems
def pop(self):
return self.stack.pop() if not self.is_empty() else None
def peek(self):
return self.stack[-1] if not self.is_empty() else None
def is_empty(self):
return len(self.stack) == 0
class StackUsingQueues:
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
def pop(self):
return self.q1.get() if not self.q1.empty() else None
Queue Problems
def dequeue(self):
return self.queue.pop(0) if not self.is_empty() else None
def is_empty(self):
return len(self.queue) == 0
def dequeue(self):
if self.front == -1:
return "Queue is empty"
data = self.queue[self.front]
if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.size
return data
Tree Problems
def level_order_traversal(root):
if not root:
return
queue = deque([root])
while queue:
node = queue.popleft()
print(node.data, end=" ")
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
Let me know if you’d like to explore the remaining 40 problems in different categories like
graph algorithms, dynamic programming, or sorting and searching algorithms!
Here are the next 40 solutions, covering Graph Algorithms, Dynamic Programming, and
Sorting & Searching.
Graph Algorithms
def display(self):
for node, neighbors in self.adj_list.items():
print(f"{node} -> {', '.join(map(str, neighbors))}")
def has_cycle(graph):
visited = set()
for node in graph:
if node not in visited:
if detect_cycle(graph, node, visited, None):
return True
return False
65. Find the shortest path in an unweighted graph
def shortest_path(graph, start, target):
from collections import deque
queue = deque([(start, [start])])
visited = set()
while queue:
node, path = queue.popleft()
if node == target:
return path
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append((neighbor, path + [neighbor]))
return None
def dfs(node):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor)
stack.append(node)
68. Climbing stairs (reach the nth step with 1 or 2 steps at a time)
def climbing_stairs(n):
if n <= 2:
return n
dp = [0] * (n + 1)
dp[1], dp[2] = 1, 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
Continuing with the next 20 solutions to complete the list of 100 beginner-level DSA
problems in Python:
def heap_sort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
def radix_sort(arr):
max_val = max(arr)
exp = 1
while max_val // exp > 0:
counting_sort_for_radix(arr, exp)
exp *= 10
84. Find the first and last occurrence of a number in a sorted array
def find_first_last(arr, target):
def binary_search(left):
lo, hi = 0, len(arr)
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] < target or (left and arr[mid] == target):
lo = mid + 1
else:
hi = mid
return lo
left_index = binary_search(True)
if left_index == len(arr) or arr[left_index] != target:
return [-1, -1]
return [left_index, binary_search(False) - 1]
_, total_count = merge_sort_and_count(arr)
return total_count
Would you like more advanced-level questions or explanation for any of these solutions?
Here are the next 20 beginner-level DSA problems and their solutions in Python:
def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
This concludes the set of 100 beginner-level DSA problems with Python
solutions. Let me know if you'd like further explanations or have any
additional requests!