C++ Practice Exercises

Strengthen your C++ skills with hands-on coding exercises. From basic syntax to advanced algorithms.

0
Completed
0
Points Earned
58
Total Exercises
Hello World Program
beginner
Write your first C++ program that prints "Hello, World!" to the console
5 min10 pts
Write a C++ program that outputs "Hello, World!" to the console.

Requirements:
- Use the iostream library
- Include proper headers
- Use the main function
- Print the exact text "Hello, World!"

Test Cases:

Input: None
Expected Output: Hello, World!
Simple Calculator
beginner
Create a calculator that performs basic arithmetic operations
15 min25 pts
Create a simple calculator program that:
- Takes two numbers as input
- Takes an operator (+, -, *, /) as input
- Performs the calculation
- Displays the result

Handle division by zero appropriately.

Test Cases:

Input: 10 + 5
Expected Output: Result: 15
Input: 10 / 0
Expected Output: Error: Division by zero!
Variables and Data Types
beginner
Practice declaring and using different data types in C++
8 min15 pts
Write a program that declares variables of different data types and displays their values.

Requirements:
- Declare an integer variable
- Declare a floating-point variable
- Declare a character variable
- Declare a string variable
- Display all variables with appropriate labels

Test Cases:

Input: None
Expected Output: Name: John
Required Constructs: int, double, char, string
Even or Odd Checker
beginner
Check if a number is even or odd
8 min15 pts
Write a program that takes a number as input and determines whether it is even or odd.

Requirements:
- Take an integer as input
- Check if it's even or odd using the modulo operator
- Display the result

Test Cases:

Input: 8
Expected Output: 8 is even.
Input: 7
Expected Output: 7 is odd.
Largest of Three Numbers
beginner
Find the largest among three numbers
12 min20 pts
Write a program that takes three numbers as input and finds the largest among them.

Requirements:
- Take three numbers as input
- Compare them to find the largest
- Display the largest number

Test Cases:

Input: 10 25 15
Expected Output: Largest number is: 25
Input: 5 5 5
Expected Output: Largest number is: 5
Grade Calculator
beginner
Calculate and display grade based on marks
12 min20 pts
Write a program that takes marks as input and displays the corresponding grade.

Grading System:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F

Requirements:
- Take marks as input
- Determine the grade
- Display the grade

Test Cases:

Input: 95
Expected Output: Grade: A
Input: 75
Expected Output: Grade: C
Input: 45
Expected Output: Grade: F
Sum of Numbers
beginner
Calculate the sum of numbers from 1 to n
12 min20 pts
Write a program that calculates the sum of all numbers from 1 to n, where n is provided by the user.

Requirements:
- Take n as input
- Use a loop to sum numbers from 1 to n
- Display the sum

Test Cases:

Input: 5
Expected Output: Sum of numbers from 1 to 5 is: 15
Input: 10
Expected Output: Sum of numbers from 1 to 10 is: 55
Factorial Calculator
beginner
Calculate the factorial of a number
15 min25 pts
Write a program that calculates the factorial of a given number.

Factorial of n (n!) = n × (n-1) × (n-2) × ... × 2 × 1
Example: 5! = 5 × 4 × 3 × 2 × 1 = 120

Requirements:
- Take a number as input
- Calculate its factorial
- Display the result

Test Cases:

Input: 5
Expected Output: Factorial of 5 is: 120
Input: 0
Expected Output: Factorial of 0 is: 1
Multiplication Table
beginner
Generate multiplication table for a given number
12 min20 pts
Write a program that generates the multiplication table for a given number.

Requirements:
- Take a number as input
- Display its multiplication table from 1 to 10
- Format the output clearly

Test Cases:

Input: 5
Expected Output: 5 x 1 = 5
Required Constructs: for, cout
Reverse a Number
beginner
Reverse the digits of a given number
15 min25 pts
Write a program that reverses the digits of a given number.

Example: If input is 1234, output should be 4321

Requirements:
- Take a number as input
- Reverse its digits
- Display the reversed number

Test Cases:

Input: 1234
Expected Output: Reversed number: 4321
Input: 567
Expected Output: Reversed number: 765
Palindrome Number Checker
beginner
Check if a number is a palindrome
15 min25 pts
Write a program that checks if a given number is a palindrome.

A palindrome number reads the same forwards and backwards.
Example: 121, 1331, 7 are palindromes

Requirements:
- Take a number as input
- Check if it's a palindrome
- Display appropriate message

Test Cases:

Input: 121
Expected Output: 121 is a palindrome.
Input: 123
Expected Output: 123 is not a palindrome.
Sum of Digits
beginner
Calculate the sum of digits in a number
12 min20 pts
Write a program that calculates the sum of all digits in a given number.

Example: If input is 1234, sum = 1 + 2 + 3 + 4 = 10

Requirements:
- Take a number as input
- Extract each digit and sum them
- Display the sum

Test Cases:

Input: 1234
Expected Output: Sum of digits of 1234 is: 10
Input: 567
Expected Output: Sum of digits of 567 is: 18
Temperature Converter
beginner
Convert temperature between Celsius and Fahrenheit
15 min25 pts
Write a program that converts temperature between Celsius and Fahrenheit.

Formulas:
- Celsius to Fahrenheit: F = (C × 9/5) + 32
- Fahrenheit to Celsius: C = (F - 32) × 5/9

Requirements:
- Ask user for conversion type
- Take temperature value as input
- Perform conversion and display result

Test Cases:

Input: 1 25
Expected Output: 25.00 Celsius = 77.00 Fahrenheit
Required Constructs: if, cin, cout
Area and Perimeter Calculator
beginner
Calculate area and perimeter of rectangle and circle
15 min25 pts
Write a program that calculates area and perimeter for different shapes.

For Rectangle:
- Area = length × width
- Perimeter = 2 × (length + width)

For Circle:
- Area = π × radius²
- Perimeter (Circumference) = 2 × π × radius

Requirements:
- Ask user to choose shape
- Take required measurements as input
- Calculate and display area and perimeter

Test Cases:

Input: 1 5 3
Expected Output: Area: 15.00
Required Constructs: if, cin, cout
Count Vowels in String
beginner
Count the number of vowels in a string
15 min25 pts
Write a program that counts the number of vowels (a, e, i, o, u) in a given string.

Requirements:
- Take a string as input
- Count vowels (both uppercase and lowercase)
- Display the count

Test Cases:

Input: Hello World
Expected Output: Number of vowels: 3
Required Constructs: for, string
Fibonacci Sequence
intermediate
Generate the Fibonacci sequence up to n terms
20 min40 pts
Write a program that generates the Fibonacci sequence up to n terms.

The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers: 0, 1, 1, 2, 3, 5, 8, 13, ...

Requirements:
- Ask the user for the number of terms
- Display the sequence
- Handle edge cases (n <= 0)

Test Cases:

Input: 5
Expected Output: Fibonacci sequence: 0 1 1 2 3
Input: 1
Expected Output: Fibonacci sequence: 0
Prime Number Checker
intermediate
Check if a given number is prime
18 min35 pts
Write a program that checks whether a given number is prime or not.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Requirements:
- Take a number as input
- Check if it's prime
- Display appropriate message
- Optimize for efficiency

Test Cases:

Input: 17
Expected Output: 17 is a prime number.
Input: 15
Expected Output: 15 is not a prime number.
Bubble Sort Algorithm
intermediate
Implement bubble sort to sort an array in ascending order
20 min40 pts
Implement the Bubble Sort algorithm to sort an array in ascending order.

Bubble Sort repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed.

Requirements:
- Take array size and elements as input
- Sort the array using bubble sort algorithm
- Display the sorted array
- Show the number of swaps performed

Test Cases:

Input: 5 64 34 25 12 22
Expected Output: Sorted array: 12 22 25 34 64
Merge Sort Algorithm
advanced
Implement merge sort using divide and conquer approach
40 min60 pts
Implement the Merge Sort algorithm using a divide and conquer approach.

Merge Sort divides the array into two halves, sorts them recursively, and then merges the sorted halves.

Algorithm:
1. Divide: Split array into two halves
2. Conquer: Recursively sort both halves
3. Combine: Merge the two sorted halves

Requirements:
- Take array size and elements as input
- Sort using merge sort algorithm
- Display the sorted array
- Time complexity should be O(n log n)

Test Cases:

Input: 6 38 27 43 3 9 82
Expected Output: Sorted array: 3 9 27 38 43 82
Breadth-First Search (BFS)
advanced
Implement BFS algorithm to traverse a graph level by level
45 min65 pts
Implement Breadth-First Search (BFS) algorithm to traverse a graph.

BFS explores all nodes at the present depth level before moving to nodes at the next depth level.

Algorithm:
1. Start from a source node
2. Visit all neighbors of current node
3. Mark visited nodes
4. Use a queue to maintain order of exploration

Requirements:
- Represent graph using adjacency list
- Implement BFS starting from a given node
- Display the order of node visits
- Handle disconnected components

Test Cases:

Input: 5 4 0 1 0 2 1 3 2 4 0
Expected Output: BFS traversal starting from node 0:
Required Constructs: vector, queue, function
Matrix Multiplication
advanced
Implement matrix multiplication for 2x2 matrices
30 min60 pts
Implement matrix multiplication for two 2x2 matrices.

Requirements:
- Create a function to multiply two 2x2 matrices
- Take input for both matrices
- Display the result matrix
- Handle the mathematical rules of matrix multiplication

Test Cases:

Input: A: [[1,2],[3,4]] B: [[5,6],[7,8]]
Expected Output: Result: [[19,22],[43,50]]
Array Sum
beginner
Calculate the sum of all elements in an array
10 min20 pts
Write a program that calculates the sum of all elements in an array.

Requirements:
- Take array size and elements as input
- Calculate the sum of all elements
- Display the result

Test Cases:

Input: 5 1 2 3 4 5
Expected Output: Sum of array elements: 15
Find Maximum and Minimum in Array
beginner
Find the largest and smallest elements in an array
12 min25 pts
Write a program that finds the maximum and minimum elements in an array.

Requirements:
- Take array size and elements as input
- Find the maximum element
- Find the minimum element
- Display both results

Test Cases:

Input: 5 10 5 20 15 8
Expected Output: Maximum element: 20
Required Constructs: array, for
Reverse an Array
beginner
Reverse the elements of an array
12 min25 pts
Write a program that reverses the elements of an array.

Requirements:
- Take array size and elements as input
- Reverse the array in-place or create a new reversed array
- Display the reversed array

Test Cases:

Input: 5 1 2 3 4 5
Expected Output: Reversed array: 5 4 3 2 1
Linear Search in Array
beginner
Search for an element in an array using linear search
10 min20 pts
Write a program that searches for an element in an array using linear search.

Requirements:
- Take array size and elements as input
- Take the element to search for
- Find the index of the element (or -1 if not found)
- Display the result

Test Cases:

Input: 5 10 20 30 40 50 30
Expected Output: Element found at index: 2
Binary Search in Array
intermediate
Search for an element in a sorted array using binary search
18 min35 pts
Write a program that searches for an element in a sorted array using binary search.

Binary search works by repeatedly dividing the search interval in half.

Requirements:
- Take sorted array size and elements as input
- Take the element to search for
- Use binary search algorithm
- Display the index if found, or -1 if not found

Test Cases:

Input: 5 10 20 30 40 50 30
Expected Output: Element found at index: 2
Merge Two Sorted Arrays
intermediate
Merge two sorted arrays into one sorted array
20 min40 pts
Write a program that merges two sorted arrays into one sorted array.

Requirements:
- Take two sorted arrays as input
- Merge them into a single sorted array
- Display the merged array

Test Cases:

Input: 3 1 3 5 3 2 4 6
Expected Output: Merged array: 1 2 3 4 5 6
Stack Implementation
intermediate
Implement a stack data structure with push, pop, and peek operations
25 min45 pts
Implement a stack data structure using an array.

A stack follows LIFO (Last In First Out) principle.

Operations to implement:
- push(x): Add element x to the top
- pop(): Remove and return top element
- peek(): Return top element without removing
- isEmpty(): Check if stack is empty
- display(): Show all elements

Requirements:
- Use an array to store stack elements
- Handle stack overflow and underflow

Test Cases:

Input: None
Expected Output: 30 pushed to stack
Required Constructs: class, array
Queue Implementation
intermediate
Implement a queue data structure with enqueue and dequeue operations
25 min45 pts
Implement a queue data structure using an array.

A queue follows FIFO (First In First Out) principle.

Operations to implement:
- enqueue(x): Add element x to the rear
- dequeue(): Remove and return front element
- front(): Return front element without removing
- isEmpty(): Check if queue is empty
- display(): Show all elements

Requirements:
- Use an array to store queue elements
- Handle queue overflow and underflow

Test Cases:

Input: None
Expected Output: 30 enqueued to queue
Required Constructs: class, array
Linked List - Basic Operations
intermediate
Implement a singly linked list with insert, delete, and display operations
30 min50 pts
Implement a singly linked list with the following operations:

- insertAtEnd(value): Insert a node at the end
- insertAtBeginning(value): Insert a node at the beginning
- deleteNode(value): Delete a node with given value
- display(): Display all nodes
- search(value): Search for a value in the list

Requirements:
- Use a Node structure with data and next pointer
- Handle empty list cases

Test Cases:

Input: None
Expected Output: List: 5 -> 10 -> 20 -> NULL
Required Constructs: class, struct, pointer
Binary Tree Traversal
intermediate
Implement inorder, preorder, and postorder traversal of a binary tree
30 min50 pts
Implement a binary tree and perform three types of traversals:

- Inorder: Left -> Root -> Right
- Preorder: Root -> Left -> Right
- Postorder: Left -> Right -> Root

Requirements:
- Create a binary tree structure
- Implement all three traversal methods
- Display the traversal results

Test Cases:

Input: None
Expected Output: Inorder: 20 30 40 50 70
Required Constructs: class, struct, recursion
Array Rotation
intermediate
Rotate an array to the left or right by k positions
18 min35 pts
Write a program to rotate an array to the left by k positions.

Example: [1, 2, 3, 4, 5] rotated left by 2 becomes [3, 4, 5, 1, 2]

Requirements:
- Take array size, elements, and rotation count as input
- Rotate the array to the left
- Display the rotated array

Test Cases:

Input: 5 1 2 3 4 5 2
Expected Output: Rotated array: 3 4 5 1 2
Count Element Frequency
intermediate
Count the frequency of each element in an array
15 min30 pts
Write a program that counts the frequency of each element in an array.

Requirements:
- Take array size and elements as input
- Count how many times each element appears
- Display each element with its frequency

Test Cases:

Input: 5 1 2 2 3 1
Expected Output: 1 appears 2 time(s)
Two Sum Problem
intermediate
Find two numbers in an array that add up to a target sum
20 min40 pts
Given an array of integers and a target sum, find two numbers that add up to the target.

Return the indices of the two numbers.

Example: Array [2, 7, 11, 15], target = 9
Output: indices 0 and 1 (2 + 7 = 9)

Requirements:
- Take array size, elements, and target sum as input
- Find two indices whose values sum to target
- Display the indices or a message if not found

Test Cases:

Input: 4 2 7 11 15 9
Expected Output: Indices: 0 and 1
Remove Duplicates from Array
intermediate
Remove duplicate elements from an array
18 min35 pts
Write a program to remove duplicate elements from an array.

Requirements:
- Take array size and elements as input
- Remove duplicate elements
- Display the array without duplicates

Test Cases:

Input: 5 1 2 2 3 1
Expected Output: Array without duplicates: 1 2 3
Matrix Transpose
intermediate
Find the transpose of a matrix
15 min30 pts
Write a program to find the transpose of a matrix.

The transpose of a matrix is obtained by interchanging rows and columns.

Example:
Original:    Transpose:
1 2 3        1 4
4 5 6        2 5
             3 6

Requirements:
- Take matrix dimensions and elements as input
- Calculate and display the transpose

Test Cases:

Input: 2 3 1 2 3 4 5 6
Expected Output: Transpose matrix:
Required Constructs: array, for
Sparse Matrix Representation
advanced
Represent a sparse matrix efficiently
30 min50 pts
A sparse matrix has most elements as zero. Represent it efficiently by storing only non-zero elements.

Requirements:
- Take matrix dimensions and elements as input
- Identify non-zero elements
- Store them in a compact format (row, column, value)
- Display the sparse representation

Test Cases:

Input: 3 3 0 0 1 2 0 0 0 3 0
Expected Output: Row
Required Constructs: struct, array
Circular Queue Implementation
advanced
Implement a circular queue to efficiently use array space
30 min50 pts
Implement a circular queue using an array.

A circular queue reuses the space after dequeuing elements.

Operations:
- enqueue(x): Add element to rear
- dequeue(): Remove element from front
- isEmpty(): Check if queue is empty
- isFull(): Check if queue is full
- display(): Show all elements

Requirements:
- Use modulo arithmetic for circular behavior
- Handle wrap-around of indices

Test Cases:

Input: None
Expected Output: 30 enqueued
Required Constructs: class, array
Doubly Linked List
advanced
Implement a doubly linked list with forward and backward traversal
35 min55 pts
Implement a doubly linked list with the following operations:

- insertAtEnd(value): Insert at the end
- insertAtBeginning(value): Insert at the beginning
- deleteNode(value): Delete a node
- displayForward(): Display from head to tail
- displayBackward(): Display from tail to head

Requirements:
- Each node has data, next, and prev pointers
- Maintain both head and tail pointers

Test Cases:

Input: None
Expected Output: Forward: 5 <-> 10 <-> 20 <-> NULL
Required Constructs: class, struct, pointer
Binary Search Tree Operations
advanced
Implement a BST with insert, search, and delete operations
40 min60 pts
Implement a Binary Search Tree (BST) with the following operations:

- insert(value): Insert a value maintaining BST property
- search(value): Search for a value
- deleteNode(value): Delete a node
- inorder(): Display inorder traversal

BST Property: Left child < Root < Right child

Requirements:
- Handle all three cases of deletion: leaf, one child, two children

Test Cases:

Input: None
Expected Output: Inorder: 20 30 40 50 70
Required Constructs: class, struct, recursion
LRU Cache Implementation
advanced
Implement a Least Recently Used (LRU) Cache combining hash map and doubly linked list for O(1) operations
90 min100 pts
Implement an LRU (Least Recently Used) Cache that supports get() and put() operations in O(1) time complexity.

An LRU cache evicts the least recently used item when the cache reaches its capacity.

Requirements:
- Implement get(key): Return value if key exists, -1 otherwise. Move accessed item to front.
- Implement put(key, value): Insert or update value. If cache is full, remove least recently used item.
- All operations must be O(1) time complexity
- Use a combination of hash map and doubly linked list
- Cache has a maximum capacity

Operations:
- get(key): Get value and mark as recently used
- put(key, value): Add/update value and mark as recently used
- display(): Show current cache state

This problem requires:
- Hash map for O(1) key lookup
- Doubly linked list for O(1) insertion/deletion
- Combining both data structures efficiently
- Managing cache capacity and eviction policy

Test Cases:

Input: None
Expected Output: Cache state (most recent first):
Required Constructs: class, struct, unordered_map, pointer
Quick Sort Algorithm
advanced
Implement quick sort using partition and recursion
45 min65 pts
Implement the Quick Sort algorithm using divide and conquer.

Quick Sort picks a pivot element and partitions the array around the pivot.

Algorithm:
1. Choose a pivot element
2. Partition: Rearrange array so elements < pivot are left, > pivot are right
3. Recursively sort left and right partitions

Requirements:
- Take array size and elements as input
- Sort using quick sort algorithm
- Display the sorted array
- Average time complexity: O(n log n)

Test Cases:

Input: 6 64 34 25 12 22 11
Expected Output: Sorted array: 11 12 22 25 34 64
Depth-First Search (DFS)
advanced
Implement DFS algorithm to traverse a graph
40 min60 pts
Implement Depth-First Search (DFS) algorithm to traverse a graph.

DFS explores as far as possible along each branch before backtracking.

Algorithm:
1. Start from a source node
2. Mark node as visited
3. Recursively visit all unvisited neighbors
4. Backtrack when no more unvisited neighbors

Requirements:
- Represent graph using adjacency list
- Implement DFS starting from a given node
- Display the order of node visits
- Use recursion or stack

Test Cases:

Input: 5 4 0 1 0 2 1 3 2 4 0
Expected Output: DFS traversal starting from node 0:
Required Constructs: vector, recursion
Min Heap Implementation
advanced
Implement a min heap data structure with insert and extract operations
50 min70 pts
Implement a Min Heap data structure.

A Min Heap is a complete binary tree where parent nodes are always smaller than or equal to their children.

Operations to implement:
- insert(value): Insert a value maintaining heap property
- extractMin(): Remove and return minimum element
- getMin(): Return minimum without removing
- display(): Show heap structure

Heap Property: Parent <= Children

Requirements:
- Use array-based representation
- Maintain heap property after each operation
- Implement heapify operations

Test Cases:

Input: None
Expected Output: 10 inserted into heap
Required Constructs: class, vector
String Palindrome Checker
beginner
Check if a string is a palindrome using different methods
15 min25 pts
Write a program that checks if a given string is a palindrome.

A palindrome reads the same forwards and backwards (ignoring case and spaces).
Examples: "racecar", "A man a plan a canal Panama", "level"

Requirements:
- Take a string as input
- Check if it's a palindrome
- Ignore case differences
- Optionally ignore spaces and punctuation
- Display appropriate message

Test Cases:

Input: racecar
Expected Output: racecar" is a palindrome.
Input: hello
Expected Output: hello" is not a palindrome.
Dijkstra's Shortest Path Algorithm
advanced
Implement Dijkstra's algorithm to find shortest paths in a weighted graph
60 min80 pts
Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a weighted graph.

Dijkstra's algorithm finds shortest paths from a source to all vertices in a weighted graph with non-negative edge weights.

Algorithm:
1. Initialize distances: source = 0, all others = infinity
2. Use priority queue (min heap) to select unvisited node with minimum distance
3. For each neighbor, update distance if shorter path found
4. Mark node as visited
5. Repeat until all nodes visited

Requirements:
- Represent weighted graph using adjacency list
- Find shortest distances from source to all nodes
- Display shortest distances
- Handle non-negative weights only

Test Cases:

Input: 5 7 0 1 4 0 2 1 1 2 2 1 3 5 2 3 8 2 4 9 3 4 2 0
Expected Output: Shortest distances from node 0:
Required Constructs: vector, priority_queue, algorithm
Search in Rotated Sorted Array
advanced
Implement binary search to find a target in a rotated sorted array
50 min70 pts
Given a rotated sorted array (e.g., [4,5,6,7,0,1,2] is rotated at index 4), 
find the index of a target value using binary search in O(log n) time.

A rotated sorted array is a sorted array that has been rotated at some pivot point.
For example, [0,1,2,4,5,6,7] rotated at index 3 becomes [4,5,6,7,0,1,2].

Requirements:
- Use binary search approach
- Handle rotation by checking which half is sorted
- Return -1 if target is not found
- Time complexity: O(log n)

Test Cases:

Input: 7 4 5 6 7 0 1 2 0
Expected Output: Target found at index: 4
Input: 4 1 3 5 7 3
Expected Output: Target found at index: 1
Longest Common Subsequence (LCS)
advanced
Find the length of the longest common subsequence between two strings using dynamic programming
55 min75 pts
Given two strings, find the length of their longest common subsequence (LCS).

A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, "ace" is a subsequence of "abcde".

Example:
String 1: "ABCDGH"
String 2: "AEDFHR"
LCS: "ADH" (length 3)

Requirements:
- Use dynamic programming approach
- Create a 2D DP table
- Time complexity: O(m * n) where m and n are string lengths
- Space complexity: O(m * n)

Test Cases:

Input: ABCDGH AEDFHR
Expected Output: Length of Longest Common Subsequence: 3
Input: AGGTAB GXTXAYB
Expected Output: Length of Longest Common Subsequence: 4
0/1 Knapsack Problem
advanced
Solve the classic 0/1 knapsack problem using dynamic programming
60 min80 pts
Given weights and values of n items, put these items in a knapsack of capacity W 
to get the maximum total value. You cannot break items (0/1 property).

Each item can be used at most once.

Example:
Weights: [10, 20, 30]
Values: [60, 100, 120]
Capacity: 50
Maximum value: 160 (items with weight 20 and 30)

Requirements:
- Use dynamic programming
- Create a 2D DP table
- Time complexity: O(n * W) where n is number of items
- Return the maximum value that can be obtained

Test Cases:

Input: 3 10 20 30 60 100 120 50
Expected Output: Maximum value: 160
Input: 4 1 3 4 5 1 4 5 7 7
Expected Output: Maximum value: 9
Longest Increasing Subsequence (LIS)
advanced
Find the length of the longest increasing subsequence using dynamic programming
50 min70 pts
Given an array of integers, find the length of the longest increasing subsequence (LIS).

A subsequence is a sequence that can be derived from an array by deleting some elements 
without changing the order of the remaining elements.

Example:
Array: [10, 9, 2, 5, 3, 7, 101, 18]
LIS: [2, 3, 7, 18] or [2, 5, 7, 18] (length 4)

Requirements:
- Use dynamic programming
- Time complexity: O(n^2) where n is array size
- Return the length of LIS

Test Cases:

Input: 8 10 9 2 5 3 7 101 18
Expected Output: Length of Longest Increasing Subsequence: 4
Input: 6 0 1 0 3 2 3
Expected Output: Length of Longest Increasing Subsequence: 4
Topological Sort
advanced
Implement topological sorting for a directed acyclic graph (DAG)
55 min75 pts
Given a directed acyclic graph (DAG), find a topological ordering of its vertices.

A topological sort is a linear ordering of vertices such that for every directed edge (u, v), 
vertex u comes before v in the ordering.

Example:
Graph: 0 -> 1, 0 -> 2, 1 -> 3, 2 -> 3
Topological order: [0, 1, 2, 3] or [0, 2, 1, 3]

Requirements:
- Use DFS-based approach
- Handle cycles (return empty if cycle exists)
- Time complexity: O(V + E) where V is vertices, E is edges
- Print the topological order

Test Cases:

Input: 4 4 0 1 0 2 1 3 2 3
Expected Output: Topological order:
Required Constructs: vector, stack, algorithm
Union-Find (Disjoint Set Union)
advanced
Implement Union-Find data structure with path compression and union by rank
50 min70 pts
Implement the Union-Find (Disjoint Set Union) data structure with path compression 
and union by rank optimizations.

Operations:
- find(x): Find the root of the set containing x
- union(x, y): Union the sets containing x and y
- connected(x, y): Check if x and y are in the same set

Requirements:
- Use path compression in find() for O(α(n)) amortized time
- Use union by rank to keep tree height small
- α(n) is the inverse Ackermann function (practically constant)
- Support operations on n elements

Test Cases:

Input: 5 6 1 0 1 1 2 3 3 0 2 1 1 4 3 0 4 2 0
Expected Output: Connected
Required Constructs: vector, class
Segment Tree - Range Sum Query
advanced
Implement a segment tree for range sum queries and point updates
65 min85 pts
Implement a Segment Tree that supports:
1. Range Sum Query: Get sum of elements in range [l, r]
2. Point Update: Update value at index i

A segment tree is a binary tree where each node stores information about a segment of the array.

Example:
Array: [1, 3, 5, 7, 9, 11]
Query(1, 3): Sum of indices 1 to 3 = 3 + 5 + 7 = 15
Update(2, 10): Change element at index 2 to 10

Requirements:
- Build tree in O(n) time
- Query in O(log n) time
- Update in O(log n) time
- Use array-based representation

Test Cases:

Input: 6 1 3 5 7 9 11 3 1 1 3 2 2 10 1 1 3
Expected Output: Sum[1, 3] = 15
Required Constructs: vector, class
Trie (Prefix Tree)
advanced
Implement a Trie data structure for efficient string prefix matching
55 min75 pts
Implement a Trie (Prefix Tree) that supports:
1. insert(word): Insert a word into the trie
2. search(word): Return true if word exists in trie
3. startsWith(prefix): Return true if any word starts with prefix

A Trie is a tree-like data structure that stores strings character by character.

Example:
Insert: "apple", "app", "apply"
search("app"): true
search("apps"): false
startsWith("app"): true

Requirements:
- Each node has 26 children (for lowercase letters a-z)
- Mark end of word with a flag
- Time complexity: O(m) per operation where m is word length

Test Cases:

Input: 5 1 apple 1 app 2 app 2 apps 3 app
Expected Output: Search(app) = true
Required Constructs: vector, class, string
KMP String Matching Algorithm
advanced
Implement the Knuth-Morris-Pratt algorithm for efficient string pattern matching
60 min80 pts
Implement the KMP (Knuth-Morris-Pratt) algorithm to find all occurrences of a pattern 
in a text string.

KMP algorithm uses a failure function (LPS - Longest Proper Prefix which is also Suffix) 
to avoid unnecessary comparisons.

Example:
Text: "ABABDABACDABABCABCAB"
Pattern: "ABABCABAB"
Find all starting positions where pattern occurs.

Requirements:
- Build LPS array for the pattern
- Use LPS to skip unnecessary comparisons
- Time complexity: O(n + m) where n is text length, m is pattern length
- Return all starting indices where pattern is found

Test Cases:

Input: ABABDABACDABABCABCAB ABABCABAB
Expected Output: Pattern found at indices:
Required Constructs: vector, string
Floyd-Warshall Algorithm
advanced
Implement Floyd-Warshall algorithm to find shortest paths between all pairs of vertices
65 min85 pts
Implement the Floyd-Warshall algorithm to find the shortest distances between 
all pairs of vertices in a weighted graph.

The algorithm works for both directed and undirected graphs, and can handle negative edge weights 
(but not negative cycles).

Example:
Graph with 4 vertices:
0 -> 1: 5
0 -> 3: 10
1 -> 2: 3
2 -> 3: 1

Find shortest distance between every pair of vertices.

Requirements:
- Use dynamic programming approach
- Create distance matrix: dist[i][j] = shortest distance from i to j
- Time complexity: O(V^3) where V is number of vertices
- Handle unreachable vertices (use INT_MAX or -1)

Test Cases:

Input: 4 4 0 1 5 0 3 10 1 2 3 2 3 1
Expected Output: Shortest distances between all pairs:
Required Constructs: vector, algorithm, climits
A* Search Algorithm
advanced
Implement the A* pathfinding algorithm with heuristic function for optimal path finding
90 min100 pts
Implement the A* (A-star) search algorithm to find the shortest path from a start node to a goal node 
in a weighted graph using a heuristic function.

A* is an informed search algorithm that uses both:
- g(n): actual cost from start to node n
- h(n): heuristic estimate of cost from node n to goal
- f(n) = g(n) + h(n): total estimated cost

The algorithm is optimal and complete when using an admissible heuristic (never overestimates).

Example:
Graph with nodes 0-4, edges with weights, and heuristic values:
Edges: 0->1(4), 0->2(2), 1->3(5), 2->3(1), 3->4(3)
Heuristics to goal(4): h(0)=6, h(1)=5, h(2)=4, h(3)=3, h(4)=0
Find path from 0 to 4.

Requirements:
- Use priority queue (min-heap) based on f(n) = g(n) + h(n)
- Maintain g(n) for each node (actual cost from start)
- Use admissible heuristic h(n) (provided as input)
- Reconstruct and return the path from start to goal
- Handle cases where no path exists
- Time complexity: O(b^d) where b is branching factor, d is depth (with good heuristic, much better)

Test Cases:

Input: 5 5 0 1 4 0 2 2 1 3 5 2 3 1 3 4 3 6 5 4 3 0 0 4
Expected Output: Path found!
Required Constructs: vector, priority_queue, unordered_map, algorithm
Edmonds-Karp Maximum Flow Algorithm
advanced
Implement the Edmonds-Karp algorithm to find maximum flow in a flow network
90 min100 pts
Implement the Edmonds-Karp algorithm to find the maximum flow from a source to a sink 
in a directed flow network.

The Edmonds-Karp algorithm is a specific implementation of the Ford-Fulkerson method that uses 
BFS to find augmenting paths, guaranteeing O(V * E^2) time complexity.

A flow network is a directed graph where:
- Each edge has a capacity (maximum flow it can carry)
- Flow through an edge cannot exceed its capacity
- Flow conservation: incoming flow = outgoing flow (except source and sink)
- Source has only outgoing edges, sink has only incoming edges

Example:
Network with 4 nodes (0=source, 3=sink):
0 -> 1: capacity 10
0 -> 2: capacity 5
1 -> 2: capacity 15
1 -> 3: capacity 10
2 -> 3: capacity 10
Maximum flow: 15

Requirements:
- Use BFS to find augmenting paths
- Maintain residual graph (remaining capacity)
- Update flow along augmenting path
- Return maximum flow value
- Time complexity: O(V * E^2) where V is vertices, E is edges
- Handle multiple edges and cycles

Test Cases:

Input: 4 5 0 1 10 0 2 5 1 2 15 1 3 10 2 3 10 0 3
Expected Output: Maximum flow from 0 to 3:
Required Constructs: vector, queue, algorithm, climits

Your Progress

Keep practicing to improve your C++ skills

0
Beginner Exercises
of 20 completed
0
Intermediate Exercises
of 14 completed
0
Advanced Exercises
of 24 completed