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

Intermediate_Problems_Solutions

The document contains a comprehensive collection of intermediate problem-solving questions and their logic-based solutions across various topics, including algorithms, data structures, and mathematical concepts. Each problem is presented with a clear input-output format and step-by-step logic for implementation. Key topics include GCD calculation, Fibonacci sequence generation, sorting algorithms, tree traversals, and matrix operations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Intermediate_Problems_Solutions

The document contains a comprehensive collection of intermediate problem-solving questions and their logic-based solutions across various topics, including algorithms, data structures, and mathematical concepts. Each problem is presented with a clear input-output format and step-by-step logic for implementation. Key topics include GCD calculation, Fibonacci sequence generation, sorting algorithms, tree traversals, and matrix operations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Intermediate Problem-Solving Questions with Logic-Based Solutions

1. Find the Greatest Common Divisor (GCD) of Two Numbers

Input num1, num2


While num2 is not zero:
temp = num2
num2 = num1 % num2
num1 = temp
Output num1

2. Generate the First 20 Numbers in the Fibonacci Sequence

Input n = 20
a=0
b=1
Output a, b
For i from 3 to n:
next = a + b
Output next
a=b
b = next

3. Reverse a Given Integer

Input num
reverse = 0
While num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
Output reverse

4. Check if a Given Number is a Palindrome

Input num
original = num
reverse = 0
While num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
If reverse equals original:
Output "Palindrome"
Else:
Output "Not Palindrome"

5. Find All Prime Numbers up to 100

For num from 2 to 100:


is_prime = True
For i from 2 to num - 1:
If num % i == 0:
is_prime = False
Break
If is_prime:
Output num

6. Implement a Binary Search Algorithm for a Sorted List

Input sorted array, target


low = 0
high = length(array) - 1
While low <= high:
mid = (low + high) // 2
If array[mid] equals target:
Output "Found at position", mid
Exit
Else If array[mid] < target:
low = mid + 1
Else:
high = mid - 1
Output "Not Found"

7. Sort a List of Numbers Using Bubble Sort

Input array
For i from 0 to n - 2:
For j from 0 to n - i - 2:
If array[j] > array[j + 1]:
Swap array[j] and array[j + 1]
Output array
8. Find the Second Largest Number in a List

Input array
largest = -infinity
second_largest = -infinity
For i from 0 to n - 1:
If array[i] > largest:
second_largest = largest
largest = array[i]
Else If array[i] > second_largest and array[i] != largest:
second_largest = array[i]
Output second_largest

9. Merge Two Sorted Arrays into One

Input array1, array2


merged = empty
i = 0, j = 0
While i < length(array1) and j < length(array2):
If array1[i] <= array2[j]:
Add array1[i] to merged
i=i+1
Else:
Add array2[j] to merged
j=j+1
While i < length(array1):
Add array1[i] to merged
i=i+1
While j < length(array2):
Add array2[j] to merged
j=j+1
Output merged

10. Count the Number of Vowels in a Given String

Input string
vowels = "aeiouAEIOU"
count = 0
For each character in string:
If character is in vowels:
count = count + 1
Output count
11. Calculate the Power of a Number Using Recursion

Input base, exponent


Define Power(base, exponent):
If exponent == 0:
Return 1
Else:
Return base * Power(base, exponent - 1)
Output Power(base, exponent)

12. Check if Two Strings are Anagrams

Input string1, string2


If length(string1) != length(string2):
Output "Not Anagrams"
Exit
frequency1 = empty, frequency2 = empty
For each character in string1:
Increment frequency1[character]
For each character in string2:
Increment frequency2[character]
If frequency1 equals frequency2:
Output "Anagrams"
Else:
Output "Not Anagrams"

13. Find the Factorial of a Number Using Both Recursion and Iteration

**Recursive:**
Input num
Define Factorial(n):
If n == 0 or n == 1:
Return 1
Else:
Return n * Factorial(n - 1)
Output Factorial(num)

**Iterative:**
Input num
factorial = 1
For i from 1 to num:
factorial = factorial * i
Output factorial
14. Remove Duplicates from a List

Input array
unique = empty
For i from 0 to length(array) - 1:
If array[i] is not in unique:
Add array[i] to unique
Output unique

15. Implement the Euclidean Algorithm to Find the GCD of Two Numbers

Input num1, num2


While num2 != 0:
temp = num2
num2 = num1 % num2
num1 = temp
Output num1

16. Rotate a List by K Positions

Input array, k
n = length(array)
rotated = empty
For i from 0 to n - 1:
new_position = (i + k) % n
rotated[new_position] = array[i]
Output rotated

17. Generate All Subsets of a Given Set

Input set
For i from 0 to (2^n) - 1:
subset = empty
For j from 0 to n - 1:
If (i >> j) & 1 == 1:
Add set[j] to subset
Output subset

18. Find the Largest Sum of Any Contiguous Subarray in an Array

Input array
max_sum = -infinity
current_sum = 0
For i from 0 to length(array) - 1:
current_sum = current_sum + array[i]
If current_sum > max_sum:
max_sum = current_sum
If current_sum < 0:
current_sum = 0
Output max_sum

19. Determine if a Number is an Armstrong Number

Input num
original = num
sum = 0
digits = count the number of digits in num
While num > 0:
digit = num % 10
sum = sum + (digit ^ digits)
num = num // 10
If sum == original:
Output "Armstrong Number"
Else:
Output "Not Armstrong Number"

20. Check if a String Contains Balanced Parentheses

Input string
stack = empty
For each character in string:
If character is an opening parenthesis:
Push character onto stack
Else If character is a closing parenthesis:
If stack is empty:
Output "Not Balanced"
Exit
top = Pop from stack
If top and character are not matching pairs:
Output "Not Balanced"
Exit
If stack is empty:
Output "Balanced"
Else:
Output "Not Balanced"
Data Structures Problem-Solving Questions with Logic-Based Solutions
1. Implement a Stack and Its Operations (Push, Pop, Peek)

stack = empty list


Define push(item):
Add item to the end of the stack
Define pop():
If stack is empty:
Output "Underflow"
Else:
Remove and return the last item in the stack
Define peek():
If stack is empty:
Output "Underflow"
Else:
Return the last item in the stack

2. Implement a Queue and Its Operations (Enqueue, Dequeue, Front)

queue = empty list


Define enqueue(item):
Add item to the end of the queue
Define dequeue():
If queue is empty:
Output "Underflow"
Else:
Remove and return the first item in the queue
Define front():
If queue is empty:
Output "Underflow"
Else:
Return the first item in the queue

3. Write a Program to Traverse a Binary Tree in Preorder

Define preorder_traversal(node):
If node is not null:
Output node.value
Call preorder_traversal(node.left)
Call preorder_traversal(node.right)
4. Write a Program to Traverse a Binary Tree in Inorder

Define inorder_traversal(node):
If node is not null:
Call inorder_traversal(node.left)
Output node.value
Call inorder_traversal(node.right)

5. Write a Program to Traverse a Binary Tree in Postorder

Define postorder_traversal(node):
If node is not null:
Call postorder_traversal(node.left)
Call postorder_traversal(node.right)
Output node.value

6. Implement a Function to Find the Height of a Binary Tree

Define height(node):
If node is null:
Return 0
Else:
left_height = height(node.left)
right_height = height(node.right)
Return max(left_height, right_height) + 1

7. Create a Linked List and Implement Basic Operations (Add, Delete, Display)

Define Node(value):
Initialize value and next = null

Define LinkedList:
Initialize head = null

Function add(value):
Create a new node with value
If head is null:
head = new node
Else:
Traverse to the end of the list
Set the next of the last node to the new node
Function delete(value):
If head is null:
Output "List is empty"
Else:
If head.value == value:
Remove head
Else:
Traverse the list to find the node with value
Remove the node

Function display():
Traverse the list and output each node's value

8. Write an Algorithm to Detect a Cycle in a Linked List

Define detect_cycle(head):
slow_pointer = head
fast_pointer = head
While fast_pointer is not null and fast_pointer.next is not null:
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next.next
If slow_pointer == fast_pointer:
Output "Cycle Detected"
Return True
Output "No Cycle"
Return False

9. Implement a Priority Queue Using a Heap

Define PriorityQueue:
Initialize heap = empty list

Function push(item):
Add item to heap
Reorganize heap to maintain the min-heap or max-heap property

Function pop():
If heap is empty:
Output "Underflow"
Else:
Remove and return the root of the heap
Reorganize heap

Function peek():
If heap is empty:
Output "Underflow"
Else:
Return the root of the heap

10. Write a Program to Find the Depth of a Nested List

Define find_depth(nested_list):
max_depth = 1
For each element in nested_list:
If element is a list:
max_depth = max(max_depth, find_depth(element) + 1)
Return max_depth

11. Convert a Decimal Number to Binary Using a Stack

Input decimal_number
stack = empty
While decimal_number > 0:
remainder = decimal_number % 2
Push remainder onto stack
decimal_number = decimal_number // 2
binary_representation = empty string
While stack is not empty:
binary_representation = binary_representation + Pop from stack
Output binary_representation

12. Implement Breadth-First Search (BFS) for a Graph

Define BFS(graph, start_node):


queue = empty
visited = empty set
Enqueue start_node into queue
Add start_node to visited
While queue is not empty:
current_node = Dequeue from queue
Output current_node
For each neighbor of current_node:
If neighbor is not in visited:
Enqueue neighbor into queue
Add neighbor to visited
13. Implement Depth-First Search (DFS) for a Graph

Define DFS(graph, start_node, visited):


If start_node is not in visited:
Output start_node
Add start_node to visited
For each neighbor of start_node:
Call DFS(graph, neighbor, visited)

14. Find the Shortest Path Between Two Nodes in a Weighted Graph

Define dijkstra(graph, source, target):


distances = Initialize all nodes to infinity, except source (0)
priority_queue = Add source with distance 0
While priority_queue is not empty:
current_node = Extract node with smallest distance
If current_node is target:
Output distances[target]
Exit
For each neighbor of current_node:
new_distance = distances[current_node] + weight(current_node, neighbor)
If new_distance < distances[neighbor]:
Update distances[neighbor] = new_distance
Add neighbor to priority_queue

15. Count the Number of Leaf Nodes in a Binary Tree

Define count_leaf_nodes(node):
If node is null:
Return 0
If node.left is null and node.right is null:
Return 1
Return count_leaf_nodes(node.left) + count_leaf_nodes(node.right)

16. Implement a Trie and Insert Words into It

Define TrieNode:
Initialize children = empty dictionary
Initialize is_end_of_word = False

Define Trie:
Initialize root = new TrieNode
Function insert(word):
current_node = root
For each character in word:
If character not in current_node.children:
current_node.children[character] = new TrieNode
current_node = current_node.children[character]
current_node.is_end_of_word = True

17. Write an Algorithm to Check if a Graph is Connected

Define is_connected(graph):
visited = empty set
Call DFS(graph, any_start_node, visited)
If size of visited == number of nodes in graph:
Output "Graph is connected"
Else:
Output "Graph is not connected"

18. Implement the Dijkstra Algorithm for Finding the Shortest Path

Refer to Solution 14 (Dijkstra Implementation)

19. Perform Matrix Multiplication of Two 2D Arrays

Input matrix1 of size m x n, matrix2 of size n x p


result = Initialize matrix of size m x p with zeros
For i from 0 to m - 1:
For j from 0 to p - 1:
For k from 0 to n - 1:
result[i][j] = result[i][j] + matrix1[i][k] * matrix2[k][j]
Output result

20. Find the Transpose of a Matrix

Input matrix of size m x n


transpose = Initialize matrix of size n x m with zeros
For i from 0 to m - 1:
For j from 0 to n - 1:
transpose[j][i] = matrix[i][j]
Output transpose
Mathematical Problem-Solving Questions with Logic-Based Solutions
1. Check if a Number is a Perfect Number

Input num
sum_of_divisors = 0
For i from 1 to num - 1:
If num % i == 0:
sum_of_divisors = sum_of_divisors + i
If sum_of_divisors == num:
Output "Perfect Number"
Else:
Output "Not a Perfect Number"

2. Calculate the nth Triangular Number

Input n
triangular_number = n * (n + 1) / 2
Output triangular_number

3. Write a Program to Find the Least Common Multiple (LCM) of Two Numbers

Input num1, num2


Define gcd(a, b):
While b != 0:
temp = b
b=a%b
a = temp
Return a

lcm = (num1 * num2) / gcd(num1, num2)


Output lcm

4. Generate All Permutations of a String

Define permute(string, left, right):


If left == right:
Output string
Else:
For i from left to right:
Swap string[left] with string[i]
Call permute(string, left + 1, right)
Swap string[left] with string[i] # Backtrack

5. Solve the Tower of Hanoi Problem

Define hanoi(n, source, target, auxiliary):


If n == 1:
Output "Move disk from", source, "to", target
Else:
Call hanoi(n - 1, source, auxiliary, target)
Output "Move disk from", source, "to", target
Call hanoi(n - 1, auxiliary, target, source)

6. Write a Program to Calculate Compound Interest

Input principal, rate, time, n


amount = principal * (1 + rate / n)^(n * time)
compound_interest = amount - principal
Output compound_interest

7. Find the Sum of All Numbers Divisible by 3 or 5 Below 1000

sum = 0
For i from 1 to 999:
If i % 3 == 0 or i % 5 == 0:
sum = sum + i
Output sum

8. Implement a Program to Calculate the Determinant of a 3x3 Matrix

Input matrix of size 3x3


determinant = matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) -
matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]) + matrix[0][2] *
(matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0])
Output determinant

9. Write an Algorithm to Compute the Value of Pi Using a Series

Input terms
pi = 0
For i from 0 to terms - 1:
pi = pi + ((-1)^i) / (2 * i + 1)
pi = pi * 4
Output pi

10. Find the Square Root of a Number Without Using Built-In Functions

Input num
guess = num / 2
tolerance = 0.00001
While absolute(guess * guess - num) > tolerance:
guess = (guess + num / guess) / 2
Output guess

11. Check if a Number Can Be Expressed as the Sum of Two Prime Numbers

Input num
For i from 2 to num / 2:
If i is prime and (num - i) is prime:
Output i, "and", (num - i), "are prime numbers that sum to", num
Exit
Output "Cannot be expressed as the sum of two prime numbers"

12. Implement an Algorithm to Calculate the nth Catalan Number

Input n
Define factorial(x):
fact = 1
For i from 1 to x:
fact = fact * i
Return fact

catalan = factorial(2 * n) / (factorial(n + 1) * factorial(n))


Output catalan

13. Write a Program to Determine if a Number is a Power of 2

Input num
While num > 1:
If num % 2 != 0:
Output "Not a Power of 2"
Exit
num = num / 2
Output "Power of 2"

14. Count the Number of Trailing Zeroes in the Factorial of a Number

Input num
count = 0
factor = 5
While num / factor >= 1:
count = count + num // factor
factor = factor * 5
Output count

15. Implement a Function to Compute the nth Fibonacci Number Using Dynamic
Programming

Input n
fib = array of size n + 1
fib[0] = 0
fib[1] = 1
For i from 2 to n:
fib[i] = fib[i - 1] + fib[i - 2]
Output fib[n]

16. Check if a Number is a Happy Number

Input num
Define get_sum_of_squares(x):
sum = 0
While x > 0:
digit = x % 10
sum = sum + digit^2
x = x // 10
Return sum

slow = num
fast = get_sum_of_squares(num)
While fast != 1 and slow != fast:
slow = get_sum_of_squares(slow)
fast = get_sum_of_squares(get_sum_of_squares(fast))
If fast == 1:
Output "Happy Number"
Else:
Output "Not a Happy Number"

17. Write a Program to Solve Linear Equations of the Form ax + b = 0

Input a, b
If a == 0:
If b == 0:
Output "Infinite Solutions"
Else:
Output "No Solution"
Else:
x = -b / a
Output x

18. Compute the Sum of Digits of a Given Number Until a Single Digit is Obtained

Input num
While num >= 10:
sum = 0
While num > 0:
sum = sum + (num % 10)
num = num // 10
num = sum
Output num

19. Find All the Prime Factors of a Number

Input num
For i from 2 to num:
While num % i == 0:
Output i
num = num / i

20. Calculate the Greatest Product of Four Adjacent Numbers in a Grid

Input grid of size n x m


max_product = 0
For i from 0 to n - 1:
For j from 0 to m - 1:
Compute products in all possible directions (horizontal, vertical, diagonal)
Update max_product if a larger product is found
Output max_product

String Manipulation Problem-Solving Questions with Logic-Based Solutions


1. Count the Frequency of Each Character in a String

Input string
frequency = empty dictionary
For each character in string:
If character is not in frequency:
frequency[character] = 1
Else:
frequency[character] = frequency[character] + 1
Output frequency

2. Check if a String is a Valid Palindrome Ignoring Spaces and Punctuation

Input string
filtered_string = remove non-alphanumeric characters from string and convert to lowercase
reversed_string = reverse filtered_string
If filtered_string == reversed_string:
Output "Valid Palindrome"
Else:
Output "Not a Palindrome"

3. Reverse the Words in a Given Sentence

Input sentence
words = split sentence into words
reversed_sentence = join words in reverse order with spaces
Output reversed_sentence

4. Implement a Function to Find the Longest Common Prefix in a List of Strings

Input list_of_strings
If list_of_strings is empty:
Output ""
prefix = list_of_strings[0]
For each string in list_of_strings:
While string does not start with prefix:
Remove the last character from prefix
If prefix is empty:
Output ""
Output prefix

5. Write a Program to Find All Substrings of a String

Input string
substrings = empty list
For i from 0 to length(string) - 1:
For j from i to length(string) - 1:
Add substring string[i:j+1] to substrings
Output substrings

6. Count the Number of Occurrences of a Substring in a String

Input string, substring


count = 0
For i from 0 to length(string) - length(substring):
If string[i:i+length(substring)] == substring:
count = count + 1
Output count

7. Replace Every Occurrence of a Given Character in a String with Another Character

Input string, target_char, replacement_char


result = ""
For each character in string:
If character == target_char:
result = result + replacement_char
Else:
result = result + character
Output result

8. Write an Algorithm to Find the First Non-Repeating Character in a String

Input string
frequency = empty dictionary
For each character in string:
If character is not in frequency:
frequency[character] = 1
Else:
frequency[character] = frequency[character] + 1
For each character in string:
If frequency[character] == 1:
Output character
Exit
Output "No Non-Repeating Character Found"

9. Check if a String Contains Only Alphanumeric Characters

Input string
For each character in string:
If character is not a letter or a digit:
Output "False"
Exit
Output "True"

10. Implement a Caesar Cipher for Encrypting Text

Input string, shift


encrypted = ""
For each character in string:
If character is a letter:
shifted_char = shift character by shift positions within the alphabet
Add shifted_char to encrypted
Else:
Add character to encrypted
Output encrypted

11. Decode a String Encoded with the Caesar Cipher

Input string, shift


decoded = ""
For each character in string:
If character is a letter:
shifted_char = shift character backward by shift positions within the alphabet
Add shifted_char to decoded
Else:
Add character to decoded
Output decoded
12. Write a Program to Find the Longest Palindromic Substring

Input string
longest_palindrome = ""
For i from 0 to length(string) - 1:
For j from i to length(string) - 1:
substring = string[i:j+1]
If substring is a palindrome and length(substring) > length(longest_palindrome):
longest_palindrome = substring
Output longest_palindrome

13. Check if One String is a Rotation of Another String

Input string1, string2


If length(string1) != length(string2):
Output "Not a Rotation"
Else:
doubled_string = string1 + string1
If string2 is a substring of doubled_string:
Output "Rotation"
Else:
Output "Not a Rotation"

14. Implement a Function to Split a String by Spaces Without Using Built-In Functions

Input string
words = empty list
word = ""
For each character in string:
If character is not a space:
word = word + character
Else:
If word is not empty:
Add word to words
word = ""
If word is not empty:
Add word to words
Output words

15. Find the Number of Words in a camelCase String

Input string
count = 1
For each character in string:
If character is an uppercase letter:
count = count + 1
Output count

16. Write a Program to Sort Words in a Sentence Alphabetically

Input sentence
words = split sentence into words
sort words alphabetically
Output sorted words joined by spaces

17. Implement a Function to Remove All Adjacent Duplicate Characters in a String

Input string
stack = empty
For each character in string:
If stack is not empty and stack[top] == character:
Pop from stack
Else:
Push character onto stack
Output stack joined as a string

18. Write an Algorithm to Find the Edit Distance Between Two Strings

Input string1, string2


Define dp as a 2D array of size (length(string1)+1) x (length(string2)+1)
For i from 0 to length(string1):
dp[i][0] = i
For j from 0 to length(string2):
dp[0][j] = j
For i from 1 to length(string1):
For j from 1 to length(string2):
If string1[i-1] == string2[j-1]:
dp[i][j] = dp[i-1][j-1]
Else:
dp[i][j] = 1 + minimum(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
Output dp[length(string1)][length(string2)]
19. Implement a Function to Check if Two Strings are Isomorphic

Input string1, string2


If length(string1) != length(string2):
Output "Not Isomorphic"
mapping1 = empty dictionary
mapping2 = empty dictionary
For i from 0 to length(string1) - 1:
If string1[i] is not in mapping1 and string2[i] is not in mapping2:
Add string1[i] -> string2[i] to mapping1
Add string2[i] -> string1[i] to mapping2
Else:
If mapping1[string1[i]] != string2[i] or mapping2[string2[i]] != string1[i]:
Output "Not Isomorphic"
Exit
Output "Isomorphic"

20. Write a Program to Determine the Lexicographical Rank of a String

Input string
rank = 1
factorial = 1
For i from 1 to length(string):
factorial = factorial * i
For i from 0 to length(string) - 1:
count = 0
For j from i+1 to length(string) - 1:
If string[j] < string[i]:
count = count + 1
rank = rank + count * factorial / (length(string) - i)
Output rank

Logical and Miscellaneous Problem-Solving Questions with Logic-Based


Solutions
1. Write a Function to Simulate a Basic Calculator (Add, Subtract, Multiply, Divide)

Define calculator(a, b, operator):


If operator == '+':
Return a + b
Else If operator == '-':
Return a - b
Else If operator == '*':
Return a * b
Else If operator == '/' and b != 0:
Return a / b
Else:
Output "Invalid operator or division by zero"

2. Simulate Rolling Two Dice and Compute the Sum

Define roll_dice():
dice1 = generate random number between 1 and 6
dice2 = generate random number between 1 and 6
sum = dice1 + dice2
Output dice1, dice2, sum

3. Create a Program to Generate a Random Password of Length N

Define generate_password(n):
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!
@#$%^&*()"
password = ""
For i from 1 to n:
random_char = select random character from characters
password = password + random_char
Output password

4. Implement a Basic Stopwatch Program

Define stopwatch():
Input "Press Enter to start"
start_time = current time
Input "Press Enter to stop"
end_time = current time
elapsed_time = end_time - start_time
Output elapsed_time

5. Simulate a Coin Toss and Count the Occurrences of Heads and Tails

Define coin_toss(n):
heads = 0
tails = 0
For i from 1 to n:
result = generate random number (0 or 1)
If result == 0:
heads = heads + 1
Else:
tails = tails + 1
Output heads, tails

6. Create a Program to Solve Sudoku Puzzles

Define solve_sudoku(board):
If board is completely filled:
Return True
For each empty cell in board:
For number from 1 to 9:
If number is valid in the cell:
Place number in the cell
If solve_sudoku(board) returns True:
Return True
Remove number from the cell (backtrack)
Return False

7. Write a Program to Simulate Conway's Game of Life

Define game_of_life(grid, generations):


For each generation:
Create new_grid with same dimensions as grid
For each cell in grid:
Count live neighbors
Apply rules of Game of Life to determine the state of the cell in new_grid
Replace grid with new_grid
Output final grid

8. Implement a Function to Determine if a Point Lies Inside a Rectangle

Define point_in_rectangle(point, rectangle):


If rectangle.left <= point.x <= rectangle.right and rectangle.bottom <= point.y <= rectangle.top:
Return True
Else:
Return False
9. Write a Program to Generate a Random Maze

Define generate_maze(rows, cols):


Initialize grid with walls
Start at a random cell and apply depth-first search to create paths
Ensure there is at least one path from start to end
Output maze

10. Simulate a Basic Banking System with Account Creation and Balance Inquiry

Define BankingSystem:
accounts = empty dictionary
Define create_account(account_id, initial_balance):
If account_id is not in accounts:
accounts[account_id] = initial_balance
Output "Account created"
Else:
Output "Account already exists"
Define balance_inquiry(account_id):
If account_id is in accounts:
Output accounts[account_id]
Else:
Output "Account not found"

11. Implement a Function to Find the Day of the Week for a Given Date

Define day_of_week(year, month, day):


Apply Zeller's Congruence formula to compute day of the week
Output day of the week (e.g., Monday, Tuesday, etc.)

12. Write a Program to Count the Number of Set Bits in a Binary Number

Define count_set_bits(num):
count = 0
While num > 0:
If num % 2 == 1:
count = count + 1
num = num // 2
Output count
13. Simulate a Queue System for a Theme Park Ride

Define ThemeParkQueue:
queue = empty list
Define join_queue(person):
Add person to the end of the queue
Define serve_next():
If queue is not empty:
Remove and return the first person in the queue
Else:
Output "No one in queue"

14. Implement a Function to Generate Random Lottery Numbers

Define generate_lottery_numbers(n, max_value):


lottery_numbers = empty set
While size of lottery_numbers < n:
number = generate random number between 1 and max_value
Add number to lottery_numbers
Output lottery_numbers

15. Write a Program to Find the Intersection of Two Arrays

Define array_intersection(array1, array2):


intersection = empty list
For each element in array1:
If element is in array2 and not in intersection:
Add element to intersection
Output intersection

16. Create a Program to Compress a String Using Run-Length Encoding

Define run_length_encoding(string):
encoded = ""
count = 1
For i from 1 to length(string):
If string[i] == string[i-1]:
count = count + 1
Else:
encoded = encoded + string[i-1] + str(count)
count = 1
Add the last character and its count to encoded
Output encoded

17. Write a Function to Calculate the Hamming Distance Between Two Binary Strings

Define hamming_distance(string1, string2):


If length(string1) != length(string2):
Output "Strings must be of equal length"
Exit
distance = 0
For i from 0 to length(string1) - 1:
If string1[i] != string2[i]:
distance = distance + 1
Output distance

18. Implement a Basic Spell Checker Using a Dictionary of Words

Define spell_checker(word, dictionary):


If word in dictionary:
Output "Correct"
Else:
Output "Incorrect"

19. Simulate a Traffic Light System

Define traffic_light_system():
lights = ["Red", "Green", "Yellow"]
For each light in sequence:
Display light
Wait for a fixed duration before switching to the next light

20. Create a Program to Calculate the Median of a Stream of Numbers

Define median_of_stream(numbers):
Sort numbers
If size of numbers is odd:
median = middle element
Else:
median = average of two middle elements
Output median
21. Write a Function to Generate a Histogram of Frequencies from a List of Numbers

Define histogram(numbers):
frequency = empty dictionary
For each number in numbers:
If number is not in frequency:
frequency[number] = 1
Else:
frequency[number] = frequency[number] + 1
For each key in frequency:
Output key and frequency[key] as a bar graph

You might also like