Intermediate_Problems_Solutions
Intermediate_Problems_Solutions
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
Input num
reverse = 0
While num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
Output reverse
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"
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
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
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 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
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
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
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"
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)
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)
Define postorder_traversal(node):
If node is not null:
Call postorder_traversal(node.left)
Call postorder_traversal(node.right)
Output node.value
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
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
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
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
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
14. Find the Shortest Path Between Two Nodes in a Weighted Graph
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)
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
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
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"
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
sum = 0
For i from 1 to 999:
If i % 3 == 0 or i % 5 == 0:
sum = sum + i
Output sum
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"
Input n
Define factorial(x):
fact = 1
For i from 1 to x:
fact = fact * i
Return fact
Input num
While num > 1:
If num % 2 != 0:
Output "Not a Power of 2"
Exit
num = num / 2
Output "Power of 2"
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]
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"
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
Input num
For i from 2 to num:
While num % i == 0:
Output i
num = num / i
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
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"
Input sentence
words = split sentence into words
reversed_sentence = join words in reverse order with spaces
Output reversed_sentence
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
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
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"
Input string
For each character in string:
If character is not a letter or a digit:
Output "False"
Exit
Output "True"
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
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
Input string
count = 1
For each character in string:
If character is an uppercase letter:
count = count + 1
Output count
Input sentence
words = split sentence into words
sort words alphabetically
Output sorted words joined by spaces
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 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
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
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
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
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
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
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"
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 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
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