Programming Problem Solving
Programming Problem Solving
Q2. Differentiate between compile-time errors, run-time errors, and logical errors with
suitable examples.
When It Program Difficulty to
Error Type Example Detection
Occurs Execution Fix
Missing
Compile- Before the semicolon, Found by the Program Usually easy
time Error program runs undeclared compiler cannot run to fix
variable
While the
Run-time Division by zero, Found during Program may
program is Moderate
Error invalid array index execution stop or crash
running
Program runs Often
Logical Using + instead of Found by Program runs
but gives wrong hardest to
Error * testing normally
result find
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:
1. Print Debugging — print variable values to check program behavior.
2. Using a Debugger — use tools to find and examine errors.
3. Rubber Duck Debugging — explain the code step by step to find mistakes.
4. Divide and Conquer — check small parts of the code separately.
5. Code Review — ask others to review the code.
6. Unit Testing — test each function individually to find problems.
7. Checking Error Messages — read error messages carefully to identify the cause.
8. Log Analysis — examine log files to track program activities and errors.
9. 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:
1. Containers – Used to store data. Examples: vector, set, map, stack, and queue.
2. Algorithms – Ready-made functions such as sort(), find(), reverse(), and count().
3. Iterators – Used to access and move through elements in a container.
4. Function Objects (Functors) – Special objects that work like functions and help
customize operations.
5. Allocators – Manage memory allocation and deallocation for STL containers.
6. 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.
Q5. Compare vector, list, and map containers with suitable applications.
Vector
1. Stores data in a dynamic array.
2. Elements can be accessed quickly using an index.
3. Easy to add elements at the end.
4. Good for storing lists of numbers or items.
5. Example: vector<int> v;
List
1. Stores data as linked nodes.
2. Easy to add or remove elements in the middle.
3. Accessing elements is slower than a vector.
4. Useful when data changes frequently.
5. Example: list<int> l;
Map
1. Stores data as key-value pairs.
2. Each key is unique.
3. Easy to search data using a key.
4. Useful for storing names with values or frequencies.
5. Example: map<string, int> m;
Applications:
• vector is used when we need to find data quickly.
• vector is useful for storing a list of numbers or items.
• list is used when we often add or remove data.
• list is good when data changes many times.
• map is used when we want to find data using a key.
• map is useful for counting items and storing simple 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:
1. Save time because there is no need to write common algorithms from scratch.
2. Use less code and make programs shorter.
3. Well-tested and more reliable.
4. Usually faster and more efficient.
5. Work with different STL containers through iterators.
6. Improve code readability and maintenance.
7. Reduce the chance of programming mistakes.
8. Easy to learn and use.
9. 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.
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:
1. Create a list of numbers from 2 to N.
2. Start with 2, the first prime number.
3. Mark all multiples of 2 as not prime.
4. Move to the next unmarked number (3) and mark its multiples.
5. Continue this process until all necessary numbers are checked.
6. 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
Algorithm:
1. Input two numbers a and b.
2. Check whether b = 0.
3. If b = 0, return a as the GCD and stop.
4. Otherwise, calculate the remainder r = a mod b.
5. Replace a with b and b with r.
6. Repeat Steps 2–5 until b = 0.
7. 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;
};
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:
1. unique_ptr – Has only one owner. It cannot be copied to another pointer. When it goes
out of scope, the memory is automatically released.
2. shared_ptr – Allows multiple pointers to share the same object. Memory is released
when the last shared_ptr is destroyed.
3. 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?
How Smart Pointers Help Prevent Memory Leakage
A memory leak happens when a program uses memory but does not release it after use. This
can waste memory and make the program slow or unstable.
Smart pointers help prevent memory leaks by automatically releasing memory when it is no
longer needed. Programmers do not need to use delete manually. For example, a unique_ptr
automatically frees memory when it goes out of scope. A shared_ptr keeps track of how many
pointers are using the same object and frees the memory when it is no longer used.
This makes memory management safer, easier, and more reliable.
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.
Feature Directed Graph Undirected Graph
Direction Edges have a direction Edges have no direction
Connection One-way connection Two-way connection
Notation u→v u—v
Degree Has in-degree and out-degree Has only degree
Example Web pages, task scheduling Social networks, road maps
Movement Can move in one direction only Can move in both directions
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:
1. Finding the shortest path in maps and GPS systems.
2. Finding friends or connections in social networks.
3. Sending data through computer networks.
4. Exploring web pages by search engines.
DFS Applications:
1. Finding cycles in a graph or network.
2. Solving mazes and path-finding problems.
3. Task scheduling and ordering tasks.
4. Finding connected groups in a network.
5. 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).
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:
1. Use Fast Input/Output – Read and print data quickly.
2. Choose the Right Data Structure – Use efficient structures such as vector, queue, or
unordered_map.
3. Avoid Unnecessary Loops – Reduce extra calculations and repeated work.
4. Use Dynamic Programming (DP) – Store previous results to avoid solving the same
problem again.
5. Use Bit Operations – Some operations can be done faster using bits.
6. Precompute Values – Calculate useful values before processing queries.
7. Use References – Avoid copying large amounts of data.
8. Use Efficient Algorithms – Prefer faster algorithms with lower time complexity.
These techniques help reduce execution time and memory usage, making programs more
efficient.
Summary:
Linear search is simple and works on any list. Binary search is much faster but requires the data
to be sorted first. For large amounts of data, binary search is usually the better choice.
Q20. Explain Merge Sort and Quick Sort algorithms with suitable examples.
Merge Sort Algorithm
1. Divide the array into two equal halves.
2. Recursively sort the left half.
3. Recursively sort the right half.
4. 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.
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.
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:
1. Use clear and meaningful variable and function names.
2. Write comments to explain important parts of the code.
3. Divide large programs into small functions.
4. Handle errors properly using exception handling.
5. Check user input before processing it.
6. Test the program regularly to find bugs.
7. Follow a consistent coding style and formatting.
8. 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.
Feature Stack Queue
Working Rule LIFO (Last In, First Out) FIFO (First In, First Out)
Data Removal Last added item is removed first First added item is removed first
Insertion Push at the top Insert at the rear (back)
Deletion Pop from the top Delete from the front
Example Browser back button, Undo feature Ticket line, Print queue
STL Example stack<int> s; queue<int> q;
Example:
Stack: If 1, 2, 3 are added, then 3 is removed first.
Summary:
A stack follows Last In, First Out (LIFO), while a queue follows First In, First Out (FIFO).
Q27. Explain the concept of recursion with suitable examples in C++.
Concept of Recursion in C++
Recursion is a programming technique where a function calls itself again and again until a
stopping condition is reached. It is useful for solving problems that can be divided into smaller
similar problems.
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:
1. Makes code shorter and easier to understand.
2. Useful for tree and graph problems.
3. Helps solve problems step by step.
Recursion is widely used in programming to solve problems that can be divided into smaller
similar problems.
Q30. Explain the difference between arrays and linked lists with suitable examples.
Feature Array Linked List
Elements are stored together in Elements can be stored in different
Storage
memory memory locations
Access is slower because nodes are
Access Fast access using index
checked one by one
Slower because elements may need to
Insert/Delete Easier because links can be changed
be shifted
Size Usually fixed Can grow or shrink during execution
Example int arr[5] = {1,2,3,4,5}; 1 → 2 → 3 → 4 → 5 → NULL
Memory
Uses less extra memory Needs extra memory for links (pointers)
Use
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.
Q31. What is Programming Problem Solving? Explain its importance in software
development.
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.
Importance in Software Development:
1. It helps developers solve problems step by step.
2. It improves logical and analytical thinking.
3. It helps create faster and more efficient programs.
4. It is useful for programming tests and job interviews.
5. It increases confidence and coding ability.
6. It helps find and fix software errors more easily.
7. It improves decision-making during development.
8. It helps developers build reliable and high-quality software.
Programming problem solving is a fundamental skill because every software system is built by
solving problems.
Q32. Define recursion. Explain recursive and iterative approaches with examples.
Recursion, Recursive and Iterative Approaches
Recursion is a programming technique where a function calls itself again and again until a
stopping condition is reached. It is useful for solving problems that can be divided into smaller
similar problems.
Recursive Approach: A function solves a problem by calling itself. For example, finding the
factorial of a number using a recursive function.
Iterative Approach: A problem is solved using loops such as for or while. For example,
factorial can be calculated using a loop.
Differences: Recursion usually produces shorter code and is useful for tree-related problems.
Iteration is generally faster, uses less memory, and is preferred for better performance.
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:
1. Improves logical and algorithmic thinking.
2. Increases coding speed and accuracy.
3. Builds knowledge of data structures and algorithms.
4. Improves debugging and analytical skills.
5. Helps in programming contests and job interviews.
6. Encourages learning from other programmers.
7. Increases confidence in solving complex problems.
Competitive programming helps programmers become better problem solvers and software
developers.
Q37. What is lambda expression in C++? Write its syntax with example.
What is Lambda Expression in C++?
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;
};
Q40. What is STL in C++? Explain the role of STL in competitive programming.
What is STL in C++?
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().
Role of STL in Competitive Programming:
1. Saves time because common structures are already available.
2. Reduces coding errors.
3. Provides fast and efficient performance.
4. Makes code shorter and easier to read.
5. Helps manage and search data easily.
6. Supports easy traversal using iterators.
7. Useful for solving contest problems quickly.
STL is an essential tool for competitive programmers because it makes coding faster, simpler,
and more efficient.
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:
1. Read each character of the expression.
2. If the character is '(', push it into the stack.
3. If the character is ')', check the stack.
4. If the stack is empty, parentheses are not balanced.
5. Otherwise, pop one element from the stack.
6. 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.
Mark multiples of 3 → 9, 15
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:
1. Reduces code repetition.
2. Makes code shorter and easier to write.
3. Saves time during contests.
4. Helps create reusable functions and data structures.
5. Makes programs more flexible.
6. STL containers such as vector, stack, and queue are built using templates.
7. Allows the same function to work with different data types.
8. Reduces the chance of coding mistakes.
9. 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.
Q51. Write short note on: i) Compiler Error ii) Runtime Error iii) Logical Error
i) Compiler Error:
A compiler error happens when the code breaks the rules of the programming language. The
compiler finds the error before the program runs. Common examples are missing semicolons,
undeclared variables, and incorrect syntax. The program cannot run until these errors are fixed.
ii) Runtime Error:
A runtime error happens while the program is running. The program compiles successfully but
stops or crashes during execution. Common examples include dividing by zero, accessing
invalid memory, or using an array index that is out of range.
iii) Logical Error:
A logical error happens when the program runs without crashing but produces the wrong result.
The code has no syntax errors, but the logic is incorrect. For example, using addition instead of
multiplication can give the wrong output.
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:
1. Always use delete after new.
2. Use delete[] for dynamic arrays.
3. Use smart pointers such as unique_ptr and shared_ptr.
4. Use tools like Valgrind to detect memory leaks.
5. Prefer stack memory when possible.
6. 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:
1. Using a slow algorithm for a large problem.
2. Too many nested loops.
3. Repeating the same calculation many times.
4. Using slow input/output methods.
5. Missing memoization in recursive programs.
6. Using inefficient data structures.
7. Processing unnecessary data inside loops.
8. Infinite loops caused by coding mistakes.
To avoid TLE, programmers should use efficient algorithms, fast data structures, and optimized
code.