Programming Problem Solving Grouped
Programming Problem Solving Grouped
Q1. What is problem solving in programming? Discuss the major steps involved in solving a
computational problem systematically.
Programming Problem Solving is the process of understanding a problem, finding a
solution, writing code, testing it, and improving it when needed. It helps programmers solve
different types of real-life and software-related problems using logical thinking and
programming skills.
Q2. Differentiate between compile-time errors, run-time errors, and logical errors with
suitable examples.
Compile-time errors stop the program from running. Run-time errors occur during
execution and may crash the program. Logical errors do not stop the program but produce
incorrect results.
Q51. Write short note on: i) Compiler Error ii) Runtime Error iii) Logical Error
Compile-time errors stop the program from running. Run-time errors occur during
execution and may crash the program. Logical errors do not stop the program but produce
incorrect results.
Q3. Explain the importance of debugging and profiling in software development. Briefly
discuss commonly used debugging strategies.
Debugging is the process of finding, analyzing, and fixing errors (bugs) in a program. It
helps programmers identify problems, improve program performance, and ensure that the
software works correctly and produces the expected results.
Profiling is the process of checking a program's performance to find which parts use the
most time or memory. It helps programmers improve the speed and efficiency of a program.
Common Debugging Strategies:
Print Debugging — print variable values to check program behavior.
Using a Debugger — use tools to find and examine errors.
Rubber Duck Debugging — explain the code step by step to find mistakes.
Divide and Conquer — check small parts of the code separately.
Code Review — ask others to review the code.
Unit Testing — test each function individually to find problems.
Checking Error Messages — read error messages carefully to identify the cause.
Log Analysis — examine log files to track program activities and errors.
Reproducing the Bug — run the same steps again to understand the problem better.
Q4. What is the Standard Template Library (STL)? Explain its major components.
STL (Standard Template Library) is a built-in library in C++ that provides ready-made data
structures and algorithms. It includes containers such as vector, map, set, stack, and queue,
along with useful functions like sort(), find(), and reverse().
Major Components of STL:
Containers – Used to store data. Examples: vector, set, map, stack, and queue.
Algorithms – Ready-made functions such as sort(), find(), reverse(), and count().
Iterators – Used to access and move through elements in a container.
Function Objects (Functors) – Special objects that work like functions and help customize
operations.
Allocators – Manage memory allocation and deallocation for STL containers.
Adapters – Modify or simplify the use of containers and functions. Examples: stack, queue,
and priority_queue.
STL makes code shorter, easier to understand, faster, and more efficient. It is widely used in
competitive programming and software development.
Q40. What is STL in C++? Explain the role of STL in competitive programming.
STL (Standard Template Library) is a built-in library in C++ that provides ready-made data
structures and algorithms. It includes containers such as vector, map, set, stack, and queue,
along with useful functions like sort(), find(), and reverse().
Major Components of STL:
Containers – Used to store data. Examples: vector, set, map, stack, and queue.
Algorithms – Ready-made functions such as sort(), find(), reverse(), and count().
Iterators – Used to access and move through elements in a container.
Function Objects (Functors) – Special objects that work like functions and help customize
operations.
Allocators – Manage memory allocation and deallocation for STL containers.
Adapters – Modify or simplify the use of containers and functions. Examples: stack, queue,
and priority_queue.
STL makes code shorter, easier to understand, faster, and more efficient. It is widely used in
competitive programming and software development.
Q8. Describe the Sieve of Eratosthenes algorithm for generating prime numbers.
The Sieve of Eratosthenes is a simple and fast method used to find all prime numbers from 2
to N by removing numbers that are multiples of other numbers.
Steps:
Create a list of numbers from 2 to N.
Start with 2, the first prime number.
Mark all multiples of 2 as not prime.
Move to the next unmarked number (3) and mark its multiples.
Continue this process until all necessary numbers are checked.
The remaining unmarked numbers are prime numbers.
Example (N = 20):
Mark multiples of 2 → 4, 6, 8, 10, 12, 14, 16, 18, 20
Mark multiples of 3 → 9, 15
Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19
This method is widely used in competitive programming for prime number problems.
Q9. Write an algorithm or pseudocode to calculate the Greatest Common Divisor (GCD)
using the Euclidean Algorithm.
The Euclidean Algorithm is a simple method for finding the Greatest Common Divisor (GCD)
of two numbers. It repeatedly divides the numbers until the remainder becomes 0.
Pseudocode:
Start
Input a, b
While b ≠ 0
r = a mod b
a=b
b=r
End While
Print a
Stop
Algorithm:
Input two numbers a and b.
Check whether b = 0.
If b = 0, return a as the GCD and stop.
Otherwise, calculate the remainder r = a mod b.
Replace a with b and b with r.
Repeat Steps 2–5 until b = 0.
The final value of a is the GCD.
Example:
GCD(56, 98) → GCD(98, 56) → GCD(56, 42) → GCD(42, 14) → GCD(14, 0)
Answer: 14.
Algorithm:
Input two numbers a and b.
Check whether b = 0.
If b = 0, return a as the GCD and stop.
Otherwise, calculate the remainder r = a mod b.
Replace a with b and b with r.
Repeat Steps 2–5 until b = 0.
The final value of a is the GCD.
Example:
GCD(56, 98) → GCD(98, 56) → GCD(56, 42) → GCD(42, 14) → GCD(14, 0)
Answer: 14.
Q10. What are lambda expressions in C++? Explain their advantages with examples.
A lambda expression is a small unnamed function introduced in C++11. It can be written
directly inside the code without creating a separate function. Lambda expressions make
programs shorter, cleaner, and easier to understand.
Syntax:
[capture](parameters) {
// code
};
Example:
auto square = [](int x) {
return x * x;
};
Q37. What is lambda expression in C++? Write its syntax with example.
A lambda expression is a small unnamed function introduced in C++11. It can be written
directly inside the code without creating a separate function. Lambda expressions make
programs shorter, cleaner, and easier to understand.
Syntax:
[capture](parameters) {
// code
};
Example:
auto square = [](int x) {
return x * x;
};
Q11. What are smart pointers? Explain different types of smart pointers available in modern
C++.
Smart pointers are special C++ pointers that automatically manage memory. They free
memory when it is no longer needed, helping to prevent memory leaks and making
programs safer and easier to manage.
Types of Smart Pointers:
unique_ptr – Has only one owner. It cannot be copied to another pointer. When it goes out
of scope, the memory is automatically released.
shared_ptr – Allows multiple pointers to share the same object. Memory is released when
the last shared_ptr is destroyed.
weak_ptr – Does not own the object. It is used with shared_ptr and helps avoid circular
references.
Smart pointers make memory management safer, easier, and more reliable than using
normal pointers.
Q12. How do smart pointers help prevent memory leakage in software systems?
Smart pointers are special C++ pointers that automatically manage memory. They free
memory when it is no longer needed, helping to prevent memory leaks and making
programs safer and easier to manage.
Types of Smart Pointers:
unique_ptr – Has only one owner. It cannot be copied to another pointer. When it goes out
of scope, the memory is automatically released.
shared_ptr – Allows multiple pointers to share the same object. Memory is released when
the last shared_ptr is destroyed.
weak_ptr – Does not own the object. It is used with shared_ptr and helps avoid circular
references.
Smart pointers make memory management safer, easier, and more reliable than using
normal pointers.
Q32. Define recursion. Explain recursive and iterative approaches with examples.
Concept of Recursion in C++
Recursion is a method where a function calls itself to solve a problem. A recursive function
must have a base case to stop the recursion; otherwise, it will run forever.
Example: Factorial
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
Example:
factorial(4)
= 4 × factorial(3)
=4×3×2×1
= 24
Advantages of Recursion:
Makes code shorter and easier to understand.
Useful for tree and graph problems.
Helps solve problems step by step.
Recursion is widely used in programming to solve problems that can be divided into smaller
similar problems.
Q5. Compare vector, list, and map containers with suitable applications.
Applications:
vector is best when fast access by index is needed.
list is useful when elements are frequently added or removed.
map is useful for storing and searching data using keys.
vector is commonly used in competitive programming.
list is suitable for dynamic data that changes often.
map is useful for counting frequencies and storing records.
These containers are widely used in C++ programs because they make data storage and
management easier.
Q6. Discuss the advantages of using STL algorithms over manually written algorithms.
Advantages of Using STL Algorithms Over Manually Written Algorithms
STL algorithms are ready-made functions available in the C++ Standard Library. They help
programmers write code more quickly and easily.
Advantages:
Save time because there is no need to write common algorithms from scratch.
Use less code and make programs shorter.
Well-tested and more reliable.
Usually faster and more efficient.
Work with different STL containers through iterators.
Improve code readability and maintenance.
Reduce the chance of programming mistakes.
Easy to learn and use.
Useful in competitive programming where speed is important.
Examples of STL algorithms are sort(), find(), count(), and binary_search(). They make
programming faster, simpler, and more efficient.
Q13. Define graph data structure. Differentiate between directed and undirected graphs.
Define Graph Data Structure
A graph is a non-linear data structure that consists of a set of vertices (nodes) and edges
that connect them. It is used to represent relationships between different objects. Graphs
can be directed or undirected, depending on whether the connections have a direction. They
are widely used in computer networks, social networks, maps, and many other applications.
A directed graph has edges with a specific direction, while an undirected graph has edges
that can be traveled in both directions.
Q14. Explain Breadth First Search (BFS) and Depth First Search (DFS) algorithms.
Breadth First Search (BFS)
BFS is a method used to visit all nodes of a graph step by step. It starts from a node and first
visits all nearby nodes, then moves to the next level. BFS uses a queue. It is often used to
find the shortest path in a graph.
Depth First Search (DFS)
DFS is a method used to visit graph nodes by following one path as far as possible. When it
cannot go further, it returns and checks another path. DFS uses a stack or recursion. It is
useful for exploring all parts of a graph.
Difference: BFS visits nodes level by level, while DFS follows one path deeply before moving
to another path.
Q15. Discuss the applications of graph traversal algorithms in real-world problem solving.
Applications of Graph Traversal Algorithms in Real Life
Graph traversal algorithms such as BFS and DFS are used in many real-world applications.
BFS Applications:
Finding the shortest path in maps and GPS systems.
Finding friends or connections in social networks.
Sending data through computer networks.
Exploring web pages by search engines.
DFS Applications:
Finding cycles in a graph or network.
Solving mazes and path-finding problems.
Task scheduling and ordering tasks.
Finding connected groups in a network.
Exploring all possible paths in a graph.
These algorithms are widely used in computer networks, web applications, transportation
systems, and many other software systems.
Q16. What is time complexity? Explain Big-O notation with example in brief.
What is Time Complexity?
Time complexity is a way to measure how much time an algorithm takes as the input size
increases. It helps programmers compare algorithms and choose the faster one.
Big-O Notation
Big-O notation is used to show the running time of an algorithm in the worst case.
Common Big-O Values:
O(1) – Constant time (e.g., accessing an array element).
O(log n) – Logarithmic time (e.g., binary search).
O(n) – Linear time (e.g., linear search).
O(n log n) – Used in efficient sorting algorithms like merge sort.
O(n²) – Quadratic time (e.g., bubble sort).
Example:
If you search for a number in an unsorted array of 1000 elements, you may need to check all
1000 elements. This is O(n) time complexity.
Time complexity helps programmers write faster and more efficient programs.
Q18. Discuss different optimization techniques used to reduce execution time and memory
usage in competitive programming.
Optimization Techniques in Competitive Programming
Optimization is important in competitive programming because it helps programs run
faster and use less memory.
Common Optimization Techniques:
Use Fast Input/Output – Read and print data quickly.
Choose the Right Data Structure – Use efficient structures such as vector, queue, or
unordered_map.
Avoid Unnecessary Loops – Reduce extra calculations and repeated work.
Use Dynamic Programming (DP) – Store previous results to avoid solving the same problem
again.
Use Bit Operations – Some operations can be done faster using bits.
Precompute Values – Calculate useful values before processing queries.
Use References – Avoid copying large amounts of data.
Use Efficient Algorithms – Prefer faster algorithms with lower time complexity.
These techniques help reduce execution time and memory usage, making programs more
efficient.
Q20. Explain Merge Sort and Quick Sort algorithms with suitable examples.
Merge Sort Algorithm
Divide the array into two equal halves.
Recursively sort the left half.
Recursively sort the right half.
Merge the two sorted halves into one sorted array.
Example:
[5, 3, 1, 4]
→ [5, 3] and [1, 4]
→ [3, 5] and [1, 4]
→ [1, 3, 4, 5]
Time Complexity: O(n log n)
Difference:
Merge Sort divides the array into halves and then merges them.
Quick Sort uses a pivot to divide the array.
Merge Sort uses more memory.
Quick Sort is usually faster in practice.
Q21. Discuss the importance of algorithm analysis in selecting appropriate searching and
sorting techniques.
Importance of Algorithm Analysis in Searching and Sorting
Algorithm analysis helps programmers understand how fast an algorithm works and how
much memory it uses. It helps in choosing the best searching and sorting method for a
problem.
For example, Bubble Sort is slow for large data, while Merge Sort can sort large data much
faster. Similarly, Binary Search is much faster than Linear Search when the data is sorted.
Algorithm analysis helps reduce execution time, save memory, and improve program
performance. In competitive programming, it is important because problems have time and
memory limits. Choosing the right algorithm increases the chance of getting the correct
answer quickly.
Q23. Discuss the use of try, catch, and throw statements in C++ with suitable examples.
Use of try, catch, and throw in C++
C++ uses try, catch, and throw for exception handling.
try: Contains the code that may cause an error.
throw: Used to generate an exception when an error occurs.
catch: Receives and handles the exception.
Example:
try {
int a = 10, b = 0;
if (b == 0)
throw "Division by zero!";
cout << a / b;
}
catch (const char* msg) {
cout << msg;
}
Output:
Division by zero!
In this example, the throw statement sends an error message, and the catch block handles it.
This prevents the program from crashing and allows it to show a proper error message.
Exception handling is commonly used for file handling, user input, and other operations
where errors may occur.
Q24. Explain how robust coding practices improve software quality and maintainability.
How Robust Coding Practices Improve Software Quality and Maintainability
Robust coding practices help make software reliable, easy to understand, and easy to
maintain. They reduce errors and improve program quality.
Common Robust Coding Practices:
Use clear and meaningful variable and function names.
Write comments to explain important parts of the code.
Divide large programs into small functions.
Handle errors properly using exception handling.
Check user input before processing it.
Test the program regularly to find bugs.
Follow a consistent coding style and formatting.
Review code to find mistakes and improvements.
These practices make programs easier to read, debug, update, and maintain. They also help
developers work together more effectively.
Q26. Differentiate between stack and queue data structures with examples.
Example:
Stack: If 1, 2, 3 are added, then 3 is removed first.
Queue: If 1, 2, 3 are added, then 1 is removed first.
Summary:
A stack follows Last In, First Out (LIFO), while a queue follows First In, First Out (FIFO).
Q30. Explain the difference between arrays and linked lists with suitable examples.
Summary:
Array is best when data size is known and fast access is needed.
Linked List is best when data is frequently added or removed and the size changes often.
Q34. What is competitive programming? Discuss its benefits for problem solving skills.
Competitive Programming and Its Benefits
Competitive Programming is an activity where programmers solve coding problems within
a limited time. Participants write programs to solve problems and submit them to online
platforms such as Codeforces, LeetCode, HackerRank, and CodeChef.
Benefits for Problem Solving Skills:
Improves logical and algorithmic thinking.
Increases coding speed and accuracy.
Builds knowledge of data structures and algorithms.
Improves debugging and analytical skills.
Helps in programming contests and job interviews.
Encourages learning from other programmers.
Increases confidence in solving complex problems.
Competitive programming helps programmers become better problem solvers and software
developers.
Q36. Explain how online judges evaluate solutions. Discuss common mistakes made during
programming contests.
Online judges check solutions automatically. After a programmer submits code, the system
runs it on hidden test cases. If the output is correct and the program stays within the time
and memory limits, the result is Accepted (AC). Other results include Wrong Answer (WA),
Time Limit Exceeded (TLE), Runtime Error (RE), Memory Limit Exceeded (MLE), and
Compilation Error (CE).
Common Contest Mistakes:
Wrong logic or missing edge cases.
Slow algorithms causing TLE.
Using incorrect data types.
Loop boundary mistakes.
Misunderstanding the problem statement.
Not testing special cases.
Typing or syntax errors.
Incorrect input or output format.
Q41. Explain pair and tuple in STL. Write a program using STL stack to check balanced
parentheses.
Pair and Tuple in STL
A pair is an STL container that stores two values in a single variable. The two values can be
of the same or different data types and can be accessed using first and second.
Example:
pair<int, string> p = {1, "Hello"};
Values can be accessed using [Link] and [Link].
A tuple is similar to a pair but can store three or more values.
Example:
tuple<int, int, string> t = {1, 2, "OK"};
Program Using STL Stack to Check Balanced Parentheses
Algorithm:
Read each character of the expression.
If the character is '(', push it into the stack.
If the character is ')', check the stack.
If the stack is empty, parentheses are not balanced.
Otherwise, pop one element from the stack.
After checking all characters, if the stack is empty, parentheses are balanced.
stack<char> s;
for(char c : str){
if(c == '(')
[Link](c);
else if(c == ')'){
if([Link]())
return false;
[Link]();
}
}
return [Link]();
Q43. What is computational geometry? Explain distance formula between two points in 2D
geometry.
Computational Geometry and Distance Formula in 2D
Computational Geometry is a branch of computer science that deals with solving geometric
problems using algorithms. It works with points, lines, circles, polygons, and other shapes. It
is used in computer graphics, maps, GPS systems, robotics, and game development. In
programming contests, geometry problems often involve finding distances, areas, angles,
and intersections.
Distance Formula Between Two Points in 2D Geometry
The distance formula is used to find the straight-line distance between two points on a
coordinate plane. For two points P₁(x₁, y₁) and P₂(x₂, y₂), the distance is:
This formula comes from the Pythagorean Theorem. First, we find the horizontal difference
(x₂ − x₁) and vertical difference (y₂ − y₁) between the two points. These form the two sides
of a right triangle. The distance between the points is the hypotenuse of that triangle.
Example: P₁(1,2) and P₂(4,6)
Distance = √((4−1)² + (6−2)²) = √(9 + 16) = √25 = 5
Q47. Define Pascal's Triangle. Explain relationship between Pascal's Triangle and
combinations.
Pascal's Triangle and Its Relationship with Combinations
Pascal's Triangle is a triangular pattern of numbers. The first row starts with 1, and each
new number is found by adding the two numbers directly above it.
Example:
1
11
121
1331
14641
Relationship with Combinations:
Each number in Pascal's Triangle represents a combination value C(n, k). It shows the
number of ways to choose k items from n items.
For example, the row 1 4 6 4 1 represents:
C(4,0), C(4,1), C(4,2), C(4,3), C(4,4)
Pascal's Triangle helps us find combination values easily without using large factorial
calculations. It is widely used in mathematics, probability, counting problems, and
competitive programming.
Q49. What is function template in C++? Discuss the role of templates in competitive
programming.
Function Template in C++ and Its Role in Competitive Programming
A function template is a special function that can work with different data types using the
same code. This means we do not need to write separate functions for int, float, or double.
Example:
template <typename T>
T maxVal(T a, T b){
return (a > b) ? a : b;
}
This function can work with different data types.
Role of Templates in Competitive Programming:
Reduces code repetition.
Makes code shorter and easier to write.
Saves time during contests.
Helps create reusable functions and data structures.
Makes programs more flexible.
STL containers such as vector, stack, and queue are built using templates.
Allows the same function to work with different data types.
Reduces the chance of coding mistakes.
Makes code easier to maintain and understand.
Templates are very useful for writing clean, simple, reusable, and efficient code in
competitive programming.
Q50. Explain permutation with repetition. Solve a sample counting problem using
combinations.
Permutation with Repetition and Combination Example
Permutation with repetition means arranging items where the same item can be used more
than once. If there are n choices and r places, the number of possible arrangements is:
nʳ
Example:
How many 3-digit PINs can be made using digits 0–9?
Answer: 10³ = 1000
Sample Problem Using Combination
A combination is used when choosing items and the order is not important.
Formula:
C(n,r) = n! / [r!(n-r)!]
Example:
A class has 10 students. How many ways can we choose a team of 3 students?
C(10,3) = (10×9×8)/(3×2×1) = 120
Answer: 120 ways
Permutations and combinations are useful for solving counting and selection problems in
mathematics and programming.
Q52. What is dynamic memory allocation in C++? Explain memory leak and its prevention
techniques.
What is Dynamic Memory Allocation in C++?
Dynamic memory allocation is the process of creating memory while a program is running.
In C++, memory is allocated from the heap using the new keyword and released using the
delete keyword when it is no longer needed.
Example:
int* p = new int(5);
delete p;
What is Memory Leak?
A memory leak occurs when dynamically allocated memory is not released after use. As a
result, unused memory remains occupied, causing higher memory usage and possibly
slowing down or crashing the program over time.
Prevention Techniques:
Always use delete after new.
Use delete[] for dynamic arrays.
Use smart pointers such as unique_ptr and shared_ptr.
Use tools like Valgrind to detect memory leaks.
Prefer stack memory when possible.
Review code carefully to ensure all allocated memory is released.
These techniques help make programs more efficient, stable, and memory-safe.
Q53. Explain constructors and destructors in C++. Discuss copy constructor with example.
Constructors and Destructors in C++
A constructor is a special function that is called automatically when an object is created. It is
used to give initial values to object data.
Example:
Car(string n){
name = n;
}
A destructor is a special function that is called automatically when an object is destroyed or
goes out of scope. It is used to free resources and clean up memory.
Example:
~Car(){
cout << "Car destroyed";
}
Copy Constructor
A copy constructor is called when one object is created from another object of the same
class.
Example:
Car c2 = c1;
Here, c2 receives a copy of the values stored in c1. Copy constructors are useful when
copying objects safely, especially when dynamic memory is used.
Q54. What is TLE? Discuss common causes of Time Limit Exceeded (TLE) in programming
contests.
TLE (Time Limit Exceeded) is an error given by an online judge when a program takes more
time than the allowed limit to finish its work. This usually happens when the code is too
slow for large inputs.
Common Causes of TLE:
Using a slow algorithm for a large problem.
Too many nested loops.
Repeating the same calculation many times.
Using slow input/output methods.
Missing memoization in recursive programs.
Using inefficient data structures.
Processing unnecessary data inside loops.
Infinite loops caused by coding mistakes.
To avoid TLE, programmers should use efficient algorithms, fast data structures, and
optimized code.