Programming Exercises

Exercise 1: Balanced Parentheses Checker

Write a function that takes a string containing only parentheses (,), curly braces {,}, and square brackets [,] and returns True if the parentheses are balanced and False otherwise. For example:

balanced("(())")  # Output: True

balanced("({[]})")  # Output: True

balanced("(()")  # Output: False

 

Exercise 2: Evaluate Postfix Expression

Write a function to evaluate a postfix expression using a stack. The postfix expression is provided as a string with operands and operators separated by spaces. For example:

evaluate_postfix("3 4 + 2 *")  # Output: 14

evaluate_postfix("5 1 2 + 4 * + 3 -")  # Output: 14

 

Exercise 3: Interleave the First Half of Queue with Second Half

Write a function to interleave the first half of a queue with the second half. For example, if the queue is [1, 2, 3, 4, 5, 6], after interleaving it becomes [1, 4, 2, 5, 3, 6].

 

Exercise 4: Generate Binary Numbers from 1 to n using a Queue

Write a function to generate binary numbers from 1 to n using a queue. For example, if n is 5, the output should be ["1", "10", "11", "100", "101"].

 

Exercise 5: Top K Frequent Elements

Given an integer array, return the k most frequent elements. Implement it using a priority queue to efficiently find the top k frequent elements.

 

Exercise 6: Kth Largest Element in an Array

Find the kth largest element in an unsorted integer array using a priority queue.

 

Exercise 7: Sliding Window Maximum:

Given an array of integers and a window size k, return the maximum value in each window of size k as it slides from left to right. Use a deque to efficiently find the maximum value in each window.